SemaExpr.cpp revision bfa7aed080e2f6125ed2e30c6d2b300ddbad7005
1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements semantic analysis for expressions. 11// 12//===----------------------------------------------------------------------===// 13 14#include "Sema.h" 15#include "Lookup.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/DeclObjC.h" 18#include "clang/AST/DeclTemplate.h" 19#include "clang/AST/ExprCXX.h" 20#include "clang/AST/ExprObjC.h" 21#include "clang/Basic/PartialDiagnostic.h" 22#include "clang/Basic/SourceManager.h" 23#include "clang/Basic/TargetInfo.h" 24#include "clang/Lex/LiteralSupport.h" 25#include "clang/Lex/Preprocessor.h" 26#include "clang/Parse/DeclSpec.h" 27#include "clang/Parse/Designator.h" 28#include "clang/Parse/Scope.h" 29#include "clang/Parse/Template.h" 30using namespace clang; 31 32 33/// \brief Determine whether the use of this declaration is valid, and 34/// emit any corresponding diagnostics. 35/// 36/// This routine diagnoses various problems with referencing 37/// declarations that can occur when using a declaration. For example, 38/// it might warn if a deprecated or unavailable declaration is being 39/// used, or produce an error (and return true) if a C++0x deleted 40/// function is being used. 41/// 42/// If IgnoreDeprecated is set to true, this should not want about deprecated 43/// decls. 44/// 45/// \returns true if there was an error (this declaration cannot be 46/// referenced), false otherwise. 47/// 48bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) { 49 // See if the decl is deprecated. 50 if (D->getAttr<DeprecatedAttr>()) { 51 EmitDeprecationWarning(D, Loc); 52 } 53 54 // See if the decl is unavailable 55 if (D->getAttr<UnavailableAttr>()) { 56 Diag(Loc, diag::warn_unavailable) << D->getDeclName(); 57 Diag(D->getLocation(), diag::note_unavailable_here) << 0; 58 } 59 60 // See if this is a deleted function. 61 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 62 if (FD->isDeleted()) { 63 Diag(Loc, diag::err_deleted_function_use); 64 Diag(D->getLocation(), diag::note_unavailable_here) << true; 65 return true; 66 } 67 } 68 69 return false; 70} 71 72/// DiagnoseSentinelCalls - This routine checks on method dispatch calls 73/// (and other functions in future), which have been declared with sentinel 74/// attribute. It warns if call does not have the sentinel argument. 75/// 76void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 77 Expr **Args, unsigned NumArgs) { 78 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 79 if (!attr) 80 return; 81 int sentinelPos = attr->getSentinel(); 82 int nullPos = attr->getNullPos(); 83 84 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common 85 // base class. Then we won't be needing two versions of the same code. 86 unsigned int i = 0; 87 bool warnNotEnoughArgs = false; 88 int isMethod = 0; 89 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 90 // skip over named parameters. 91 ObjCMethodDecl::param_iterator P, E = MD->param_end(); 92 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) { 93 if (nullPos) 94 --nullPos; 95 else 96 ++i; 97 } 98 warnNotEnoughArgs = (P != E || i >= NumArgs); 99 isMethod = 1; 100 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 101 // skip over named parameters. 102 ObjCMethodDecl::param_iterator P, E = FD->param_end(); 103 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) { 104 if (nullPos) 105 --nullPos; 106 else 107 ++i; 108 } 109 warnNotEnoughArgs = (P != E || i >= NumArgs); 110 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) { 111 // block or function pointer call. 112 QualType Ty = V->getType(); 113 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) { 114 const FunctionType *FT = Ty->isFunctionPointerType() 115 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>() 116 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>(); 117 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) { 118 unsigned NumArgsInProto = Proto->getNumArgs(); 119 unsigned k; 120 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) { 121 if (nullPos) 122 --nullPos; 123 else 124 ++i; 125 } 126 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs); 127 } 128 if (Ty->isBlockPointerType()) 129 isMethod = 2; 130 } else 131 return; 132 } else 133 return; 134 135 if (warnNotEnoughArgs) { 136 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 137 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod; 138 return; 139 } 140 int sentinel = i; 141 while (sentinelPos > 0 && i < NumArgs-1) { 142 --sentinelPos; 143 ++i; 144 } 145 if (sentinelPos > 0) { 146 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 147 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod; 148 return; 149 } 150 while (i < NumArgs-1) { 151 ++i; 152 ++sentinel; 153 } 154 Expr *sentinelExpr = Args[sentinel]; 155 if (sentinelExpr && (!isa<GNUNullExpr>(sentinelExpr) && 156 (!sentinelExpr->getType()->isPointerType() || 157 !sentinelExpr->isNullPointerConstant(Context, 158 Expr::NPC_ValueDependentIsNull)))) { 159 Diag(Loc, diag::warn_missing_sentinel) << isMethod; 160 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod; 161 } 162 return; 163} 164 165SourceRange Sema::getExprRange(ExprTy *E) const { 166 Expr *Ex = (Expr *)E; 167 return Ex? Ex->getSourceRange() : SourceRange(); 168} 169 170//===----------------------------------------------------------------------===// 171// Standard Promotions and Conversions 172//===----------------------------------------------------------------------===// 173 174/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 175void Sema::DefaultFunctionArrayConversion(Expr *&E) { 176 QualType Ty = E->getType(); 177 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 178 179 if (Ty->isFunctionType()) 180 ImpCastExprToType(E, Context.getPointerType(Ty), 181 CastExpr::CK_FunctionToPointerDecay); 182 else if (Ty->isArrayType()) { 183 // In C90 mode, arrays only promote to pointers if the array expression is 184 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 185 // type 'array of type' is converted to an expression that has type 'pointer 186 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 187 // that has type 'array of type' ...". The relevant change is "an lvalue" 188 // (C90) to "an expression" (C99). 189 // 190 // C++ 4.2p1: 191 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 192 // T" can be converted to an rvalue of type "pointer to T". 193 // 194 if (getLangOptions().C99 || getLangOptions().CPlusPlus || 195 E->isLvalue(Context) == Expr::LV_Valid) 196 ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 197 CastExpr::CK_ArrayToPointerDecay); 198 } 199} 200 201/// UsualUnaryConversions - Performs various conversions that are common to most 202/// operators (C99 6.3). The conversions of array and function types are 203/// sometimes surpressed. For example, the array->pointer conversion doesn't 204/// apply if the array is an argument to the sizeof or address (&) operators. 205/// In these instances, this routine should *not* be called. 206Expr *Sema::UsualUnaryConversions(Expr *&Expr) { 207 QualType Ty = Expr->getType(); 208 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 209 210 // C99 6.3.1.1p2: 211 // 212 // The following may be used in an expression wherever an int or 213 // unsigned int may be used: 214 // - an object or expression with an integer type whose integer 215 // conversion rank is less than or equal to the rank of int 216 // and unsigned int. 217 // - A bit-field of type _Bool, int, signed int, or unsigned int. 218 // 219 // If an int can represent all values of the original type, the 220 // value is converted to an int; otherwise, it is converted to an 221 // unsigned int. These are called the integer promotions. All 222 // other types are unchanged by the integer promotions. 223 QualType PTy = Context.isPromotableBitField(Expr); 224 if (!PTy.isNull()) { 225 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast); 226 return Expr; 227 } 228 if (Ty->isPromotableIntegerType()) { 229 QualType PT = Context.getPromotedIntegerType(Ty); 230 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast); 231 return Expr; 232 } 233 234 DefaultFunctionArrayConversion(Expr); 235 return Expr; 236} 237 238/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 239/// do not have a prototype. Arguments that have type float are promoted to 240/// double. All other argument types are converted by UsualUnaryConversions(). 241void Sema::DefaultArgumentPromotion(Expr *&Expr) { 242 QualType Ty = Expr->getType(); 243 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 244 245 // If this is a 'float' (CVR qualified or typedef) promote to double. 246 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 247 if (BT->getKind() == BuiltinType::Float) 248 return ImpCastExprToType(Expr, Context.DoubleTy, 249 CastExpr::CK_FloatingCast); 250 251 UsualUnaryConversions(Expr); 252} 253 254/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 255/// will warn if the resulting type is not a POD type, and rejects ObjC 256/// interfaces passed by value. This returns true if the argument type is 257/// completely illegal. 258bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) { 259 DefaultArgumentPromotion(Expr); 260 261 if (Expr->getType()->isObjCInterfaceType()) { 262 Diag(Expr->getLocStart(), 263 diag::err_cannot_pass_objc_interface_to_vararg) 264 << Expr->getType() << CT; 265 return true; 266 } 267 268 if (!Expr->getType()->isPODType()) 269 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg) 270 << Expr->getType() << CT; 271 272 return false; 273} 274 275 276/// UsualArithmeticConversions - Performs various conversions that are common to 277/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 278/// routine returns the first non-arithmetic type found. The client is 279/// responsible for emitting appropriate error diagnostics. 280/// FIXME: verify the conversion rules for "complex int" are consistent with 281/// GCC. 282QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr, 283 bool isCompAssign) { 284 if (!isCompAssign) 285 UsualUnaryConversions(lhsExpr); 286 287 UsualUnaryConversions(rhsExpr); 288 289 // For conversion purposes, we ignore any qualifiers. 290 // For example, "const float" and "float" are equivalent. 291 QualType lhs = 292 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType(); 293 QualType rhs = 294 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType(); 295 296 // If both types are identical, no conversion is needed. 297 if (lhs == rhs) 298 return lhs; 299 300 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 301 // The caller can deal with this (e.g. pointer + int). 302 if (!lhs->isArithmeticType() || !rhs->isArithmeticType()) 303 return lhs; 304 305 // Perform bitfield promotions. 306 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr); 307 if (!LHSBitfieldPromoteTy.isNull()) 308 lhs = LHSBitfieldPromoteTy; 309 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr); 310 if (!RHSBitfieldPromoteTy.isNull()) 311 rhs = RHSBitfieldPromoteTy; 312 313 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs); 314 if (!isCompAssign) 315 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown); 316 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown); 317 return destType; 318} 319 320//===----------------------------------------------------------------------===// 321// Semantic Analysis for various Expression Types 322//===----------------------------------------------------------------------===// 323 324 325/// ActOnStringLiteral - The specified tokens were lexed as pasted string 326/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 327/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 328/// multiple tokens. However, the common case is that StringToks points to one 329/// string. 330/// 331Action::OwningExprResult 332Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) { 333 assert(NumStringToks && "Must have at least one string!"); 334 335 StringLiteralParser Literal(StringToks, NumStringToks, PP); 336 if (Literal.hadError) 337 return ExprError(); 338 339 llvm::SmallVector<SourceLocation, 4> StringTokLocs; 340 for (unsigned i = 0; i != NumStringToks; ++i) 341 StringTokLocs.push_back(StringToks[i].getLocation()); 342 343 QualType StrTy = Context.CharTy; 344 if (Literal.AnyWide) StrTy = Context.getWCharType(); 345 if (Literal.Pascal) StrTy = Context.UnsignedCharTy; 346 347 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 348 if (getLangOptions().CPlusPlus) 349 StrTy.addConst(); 350 351 // Get an array type for the string, according to C99 6.4.5. This includes 352 // the nul terminator character as well as the string length for pascal 353 // strings. 354 StrTy = Context.getConstantArrayType(StrTy, 355 llvm::APInt(32, Literal.GetNumStringChars()+1), 356 ArrayType::Normal, 0); 357 358 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 359 return Owned(StringLiteral::Create(Context, Literal.GetString(), 360 Literal.GetStringLength(), 361 Literal.AnyWide, StrTy, 362 &StringTokLocs[0], 363 StringTokLocs.size())); 364} 365 366/// ShouldSnapshotBlockValueReference - Return true if a reference inside of 367/// CurBlock to VD should cause it to be snapshotted (as we do for auto 368/// variables defined outside the block) or false if this is not needed (e.g. 369/// for values inside the block or for globals). 370/// 371/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records 372/// up-to-date. 373/// 374static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock, 375 ValueDecl *VD) { 376 // If the value is defined inside the block, we couldn't snapshot it even if 377 // we wanted to. 378 if (CurBlock->TheDecl == VD->getDeclContext()) 379 return false; 380 381 // If this is an enum constant or function, it is constant, don't snapshot. 382 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD)) 383 return false; 384 385 // If this is a reference to an extern, static, or global variable, no need to 386 // snapshot it. 387 // FIXME: What about 'const' variables in C++? 388 if (const VarDecl *Var = dyn_cast<VarDecl>(VD)) 389 if (!Var->hasLocalStorage()) 390 return false; 391 392 // Blocks that have these can't be constant. 393 CurBlock->hasBlockDeclRefExprs = true; 394 395 // If we have nested blocks, the decl may be declared in an outer block (in 396 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may 397 // be defined outside all of the current blocks (in which case the blocks do 398 // all get the bit). Walk the nesting chain. 399 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock; 400 NextBlock = NextBlock->PrevBlockInfo) { 401 // If we found the defining block for the variable, don't mark the block as 402 // having a reference outside it. 403 if (NextBlock->TheDecl == VD->getDeclContext()) 404 break; 405 406 // Otherwise, the DeclRef from the inner block causes the outer one to need 407 // a snapshot as well. 408 NextBlock->hasBlockDeclRefExprs = true; 409 } 410 411 return true; 412} 413 414 415 416/// BuildDeclRefExpr - Build a DeclRefExpr. 417Sema::OwningExprResult 418Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc, 419 const CXXScopeSpec *SS) { 420 assert(!isa<OverloadedFunctionDecl>(D)); 421 422 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) { 423 Diag(Loc, 424 diag::err_auto_variable_cannot_appear_in_own_initializer) 425 << D->getDeclName(); 426 return ExprError(); 427 } 428 429 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 430 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { 431 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) { 432 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) { 433 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function) 434 << D->getIdentifier() << FD->getDeclName(); 435 Diag(D->getLocation(), diag::note_local_variable_declared_here) 436 << D->getIdentifier(); 437 return ExprError(); 438 } 439 } 440 } 441 } 442 443 MarkDeclarationReferenced(Loc, D); 444 445 return Owned(DeclRefExpr::Create(Context, 446 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0, 447 SS? SS->getRange() : SourceRange(), 448 D, Loc, Ty)); 449} 450 451/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or 452/// variable corresponding to the anonymous union or struct whose type 453/// is Record. 454static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context, 455 RecordDecl *Record) { 456 assert(Record->isAnonymousStructOrUnion() && 457 "Record must be an anonymous struct or union!"); 458 459 // FIXME: Once Decls are directly linked together, this will be an O(1) 460 // operation rather than a slow walk through DeclContext's vector (which 461 // itself will be eliminated). DeclGroups might make this even better. 462 DeclContext *Ctx = Record->getDeclContext(); 463 for (DeclContext::decl_iterator D = Ctx->decls_begin(), 464 DEnd = Ctx->decls_end(); 465 D != DEnd; ++D) { 466 if (*D == Record) { 467 // The object for the anonymous struct/union directly 468 // follows its type in the list of declarations. 469 ++D; 470 assert(D != DEnd && "Missing object for anonymous record"); 471 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed"); 472 return *D; 473 } 474 } 475 476 assert(false && "Missing object for anonymous record"); 477 return 0; 478} 479 480/// \brief Given a field that represents a member of an anonymous 481/// struct/union, build the path from that field's context to the 482/// actual member. 483/// 484/// Construct the sequence of field member references we'll have to 485/// perform to get to the field in the anonymous union/struct. The 486/// list of members is built from the field outward, so traverse it 487/// backwards to go from an object in the current context to the field 488/// we found. 489/// 490/// \returns The variable from which the field access should begin, 491/// for an anonymous struct/union that is not a member of another 492/// class. Otherwise, returns NULL. 493VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field, 494 llvm::SmallVectorImpl<FieldDecl *> &Path) { 495 assert(Field->getDeclContext()->isRecord() && 496 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion() 497 && "Field must be stored inside an anonymous struct or union"); 498 499 Path.push_back(Field); 500 VarDecl *BaseObject = 0; 501 DeclContext *Ctx = Field->getDeclContext(); 502 do { 503 RecordDecl *Record = cast<RecordDecl>(Ctx); 504 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record); 505 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject)) 506 Path.push_back(AnonField); 507 else { 508 BaseObject = cast<VarDecl>(AnonObject); 509 break; 510 } 511 Ctx = Ctx->getParent(); 512 } while (Ctx->isRecord() && 513 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()); 514 515 return BaseObject; 516} 517 518Sema::OwningExprResult 519Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc, 520 FieldDecl *Field, 521 Expr *BaseObjectExpr, 522 SourceLocation OpLoc) { 523 llvm::SmallVector<FieldDecl *, 4> AnonFields; 524 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field, 525 AnonFields); 526 527 // Build the expression that refers to the base object, from 528 // which we will build a sequence of member references to each 529 // of the anonymous union objects and, eventually, the field we 530 // found via name lookup. 531 bool BaseObjectIsPointer = false; 532 Qualifiers BaseQuals; 533 if (BaseObject) { 534 // BaseObject is an anonymous struct/union variable (and is, 535 // therefore, not part of another non-anonymous record). 536 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context); 537 MarkDeclarationReferenced(Loc, BaseObject); 538 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(), 539 SourceLocation()); 540 BaseQuals 541 = Context.getCanonicalType(BaseObject->getType()).getQualifiers(); 542 } else if (BaseObjectExpr) { 543 // The caller provided the base object expression. Determine 544 // whether its a pointer and whether it adds any qualifiers to the 545 // anonymous struct/union fields we're looking into. 546 QualType ObjectType = BaseObjectExpr->getType(); 547 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) { 548 BaseObjectIsPointer = true; 549 ObjectType = ObjectPtr->getPointeeType(); 550 } 551 BaseQuals 552 = Context.getCanonicalType(ObjectType).getQualifiers(); 553 } else { 554 // We've found a member of an anonymous struct/union that is 555 // inside a non-anonymous struct/union, so in a well-formed 556 // program our base object expression is "this". 557 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { 558 if (!MD->isStatic()) { 559 QualType AnonFieldType 560 = Context.getTagDeclType( 561 cast<RecordDecl>(AnonFields.back()->getDeclContext())); 562 QualType ThisType = Context.getTagDeclType(MD->getParent()); 563 if ((Context.getCanonicalType(AnonFieldType) 564 == Context.getCanonicalType(ThisType)) || 565 IsDerivedFrom(ThisType, AnonFieldType)) { 566 // Our base object expression is "this". 567 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(), 568 MD->getThisType(Context)); 569 BaseObjectIsPointer = true; 570 } 571 } else { 572 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method) 573 << Field->getDeclName()); 574 } 575 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers()); 576 } 577 578 if (!BaseObjectExpr) 579 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use) 580 << Field->getDeclName()); 581 } 582 583 // Build the implicit member references to the field of the 584 // anonymous struct/union. 585 Expr *Result = BaseObjectExpr; 586 Qualifiers ResultQuals = BaseQuals; 587 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator 588 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend(); 589 FI != FIEnd; ++FI) { 590 QualType MemberType = (*FI)->getType(); 591 Qualifiers MemberTypeQuals = 592 Context.getCanonicalType(MemberType).getQualifiers(); 593 594 // CVR attributes from the base are picked up by members, 595 // except that 'mutable' members don't pick up 'const'. 596 if ((*FI)->isMutable()) 597 ResultQuals.removeConst(); 598 599 // GC attributes are never picked up by members. 600 ResultQuals.removeObjCGCAttr(); 601 602 // TR 18037 does not allow fields to be declared with address spaces. 603 assert(!MemberTypeQuals.hasAddressSpace()); 604 605 Qualifiers NewQuals = ResultQuals + MemberTypeQuals; 606 if (NewQuals != MemberTypeQuals) 607 MemberType = Context.getQualifiedType(MemberType, NewQuals); 608 609 MarkDeclarationReferenced(Loc, *FI); 610 // FIXME: Might this end up being a qualified name? 611 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI, 612 OpLoc, MemberType); 613 BaseObjectIsPointer = false; 614 ResultQuals = NewQuals; 615 } 616 617 return Owned(Result); 618} 619 620static void DecomposeTemplateName(LookupResult &R, TemplateName TName) { 621 if (TemplateDecl *TD = TName.getAsTemplateDecl()) 622 R.addDecl(TD); 623 else if (OverloadedFunctionDecl *OD 624 = TName.getAsOverloadedFunctionDecl()) 625 for (OverloadIterator I(OD), E; I != E; ++I) 626 R.addDecl(*I); 627 628 R.resolveKind(); 629} 630 631Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S, 632 const CXXScopeSpec &SS, 633 UnqualifiedId &Id, 634 bool HasTrailingLParen, 635 bool isAddressOfOperand) { 636 assert(!(isAddressOfOperand && HasTrailingLParen) && 637 "cannot be direct & operand and have a trailing lparen"); 638 639 if (SS.isInvalid()) 640 return ExprError(); 641 642 TemplateArgumentListInfo ExplicitTemplateArgs; 643 644 // Decompose the UnqualifiedId into the following data. 645 DeclarationName Name; 646 SourceLocation NameLoc; 647 const TemplateArgumentListInfo *TemplateArgs; 648 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 649 ExplicitTemplateArgs.setLAngleLoc(Id.TemplateId->LAngleLoc); 650 ExplicitTemplateArgs.setRAngleLoc(Id.TemplateId->RAngleLoc); 651 652 ASTTemplateArgsPtr TemplateArgsPtr(*this, 653 Id.TemplateId->getTemplateArgs(), 654 Id.TemplateId->NumArgs); 655 translateTemplateArguments(TemplateArgsPtr, ExplicitTemplateArgs); 656 TemplateArgsPtr.release(); 657 658 TemplateName TName = 659 TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>(); 660 661 Name = Context.getNameForTemplate(TName); 662 NameLoc = Id.TemplateId->TemplateNameLoc; 663 TemplateArgs = &ExplicitTemplateArgs; 664 } else { 665 Name = GetNameFromUnqualifiedId(Id); 666 NameLoc = Id.StartLocation; 667 TemplateArgs = 0; 668 } 669 670 IdentifierInfo *II = Name.getAsIdentifierInfo(); 671 672 // C++ [temp.dep.expr]p3: 673 // An id-expression is type-dependent if it contains: 674 // -- a nested-name-specifier that contains a class-name that 675 // names a dependent type. 676 // Determine whether this is a member of an unknown specialization; 677 // we need to handle these differently. 678 if (SS.isSet() && !computeDeclContext(SS, false)) { 679 bool CheckForImplicitMember = !isAddressOfOperand; 680 681 return ActOnDependentIdExpression(SS, Name, NameLoc, 682 CheckForImplicitMember, 683 TemplateArgs); 684 } 685 686 // Perform the required lookup. 687 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName); 688 if (TemplateArgs) { 689 TemplateName TName = 690 TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>(); 691 692 // Just re-use the lookup done by isTemplateName. 693 DecomposeTemplateName(R, TName); 694 } else { 695 LookupParsedName(R, S, &SS, true); 696 697 // If this reference is in an Objective-C method, then we need to do 698 // some special Objective-C lookup, too. 699 if (!SS.isSet() && II && getCurMethodDecl()) { 700 OwningExprResult E(LookupInObjCMethod(R, S, II)); 701 if (E.isInvalid()) 702 return ExprError(); 703 704 Expr *Ex = E.takeAs<Expr>(); 705 if (Ex) return Owned(Ex); 706 } 707 } 708 709 if (R.isAmbiguous()) 710 return ExprError(); 711 712 // Determine whether this name might be a candidate for 713 // argument-dependent lookup. 714 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 715 716 if (R.empty() && !ADL) { 717 // Otherwise, this could be an implicitly declared function reference (legal 718 // in C90, extension in C99, forbidden in C++). 719 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) { 720 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 721 if (D) R.addDecl(D); 722 } 723 724 // If this name wasn't predeclared and if this is not a function 725 // call, diagnose the problem. 726 if (R.empty()) { 727 if (!SS.isEmpty()) 728 return ExprError(Diag(NameLoc, diag::err_no_member) 729 << Name << computeDeclContext(SS, false) 730 << SS.getRange()); 731 else if (Name.getNameKind() == DeclarationName::CXXOperatorName || 732 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) 733 return ExprError(Diag(NameLoc, diag::err_undeclared_use) 734 << Name); 735 else 736 return ExprError(Diag(NameLoc, diag::err_undeclared_var_use) << Name); 737 } 738 } 739 740 // This is guaranteed from this point on. 741 assert(!R.empty() || ADL); 742 743 if (VarDecl *Var = R.getAsSingle<VarDecl>()) { 744 // Warn about constructs like: 745 // if (void *X = foo()) { ... } else { X }. 746 // In the else block, the pointer is always false. 747 748 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) { 749 Scope *CheckS = S; 750 while (CheckS && CheckS->getControlParent()) { 751 if (CheckS->isWithinElse() && 752 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) { 753 ExprError(Diag(NameLoc, diag::warn_value_always_zero) 754 << Var->getDeclName() 755 << (Var->getType()->isPointerType()? 2 : 756 Var->getType()->isBooleanType()? 1 : 0)); 757 break; 758 } 759 760 // Move to the parent of this scope. 761 CheckS = CheckS->getParent(); 762 } 763 } 764 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) { 765 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) { 766 // C99 DR 316 says that, if a function type comes from a 767 // function definition (without a prototype), that type is only 768 // used for checking compatibility. Therefore, when referencing 769 // the function, we pretend that we don't have the full function 770 // type. 771 if (DiagnoseUseOfDecl(Func, NameLoc)) 772 return ExprError(); 773 774 QualType T = Func->getType(); 775 QualType NoProtoType = T; 776 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>()) 777 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType()); 778 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS); 779 } 780 } 781 782 // &SomeClass::foo is an abstract member reference, regardless of 783 // the nature of foo, but &SomeClass::foo(...) is not. If this is 784 // *not* an abstract member reference, and any of the results is a 785 // class member (which necessarily means they're all class members), 786 // then we make an implicit member reference instead. 787 // 788 // This check considers all the same information as the "needs ADL" 789 // check, but there's no simple logical relationship other than the 790 // fact that they can never be simultaneously true. We could 791 // calculate them both in one pass if that proves important for 792 // performance. 793 if (!ADL) { 794 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty()); 795 796 if (!isAbstractMemberPointer && !R.empty() && 797 isa<CXXRecordDecl>((*R.begin())->getDeclContext())) { 798 return BuildImplicitMemberReferenceExpr(SS, R, TemplateArgs); 799 } 800 } 801 802 if (TemplateArgs) 803 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs); 804 805 return BuildDeclarationNameExpr(SS, R, ADL); 806} 807 808/// ActOnDeclarationNameExpr - Build a C++ qualified declaration name, 809/// generally during template instantiation. There's a large number 810/// of things which don't need to be done along this path. 811Sema::OwningExprResult 812Sema::BuildQualifiedDeclarationNameExpr(const CXXScopeSpec &SS, 813 DeclarationName Name, 814 SourceLocation NameLoc) { 815 DeclContext *DC; 816 if (!(DC = computeDeclContext(SS, false)) || 817 DC->isDependentContext() || 818 RequireCompleteDeclContext(SS)) 819 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0); 820 821 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName); 822 LookupQualifiedName(R, DC); 823 824 if (R.isAmbiguous()) 825 return ExprError(); 826 827 if (R.empty()) { 828 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange(); 829 return ExprError(); 830 } 831 832 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false); 833} 834 835/// LookupInObjCMethod - The parser has read a name in, and Sema has 836/// detected that we're currently inside an ObjC method. Perform some 837/// additional lookup. 838/// 839/// Ideally, most of this would be done by lookup, but there's 840/// actually quite a lot of extra work involved. 841/// 842/// Returns a null sentinel to indicate trivial success. 843Sema::OwningExprResult 844Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 845 IdentifierInfo *II) { 846 SourceLocation Loc = Lookup.getNameLoc(); 847 848 // There are two cases to handle here. 1) scoped lookup could have failed, 849 // in which case we should look for an ivar. 2) scoped lookup could have 850 // found a decl, but that decl is outside the current instance method (i.e. 851 // a global variable). In these two cases, we do a lookup for an ivar with 852 // this name, if the lookup sucedes, we replace it our current decl. 853 854 // If we're in a class method, we don't normally want to look for 855 // ivars. But if we don't find anything else, and there's an 856 // ivar, that's an error. 857 bool IsClassMethod = getCurMethodDecl()->isClassMethod(); 858 859 bool LookForIvars; 860 if (Lookup.empty()) 861 LookForIvars = true; 862 else if (IsClassMethod) 863 LookForIvars = false; 864 else 865 LookForIvars = (Lookup.isSingleResult() && 866 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 867 868 if (LookForIvars) { 869 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface(); 870 ObjCInterfaceDecl *ClassDeclared; 871 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 872 // Diagnose using an ivar in a class method. 873 if (IsClassMethod) 874 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 875 << IV->getDeclName()); 876 877 // If we're referencing an invalid decl, just return this as a silent 878 // error node. The error diagnostic was already emitted on the decl. 879 if (IV->isInvalidDecl()) 880 return ExprError(); 881 882 // Check if referencing a field with __attribute__((deprecated)). 883 if (DiagnoseUseOfDecl(IV, Loc)) 884 return ExprError(); 885 886 // Diagnose the use of an ivar outside of the declaring class. 887 if (IV->getAccessControl() == ObjCIvarDecl::Private && 888 ClassDeclared != IFace) 889 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 890 891 // FIXME: This should use a new expr for a direct reference, don't 892 // turn this into Self->ivar, just return a BareIVarExpr or something. 893 IdentifierInfo &II = Context.Idents.get("self"); 894 UnqualifiedId SelfName; 895 SelfName.setIdentifier(&II, SourceLocation()); 896 CXXScopeSpec SelfScopeSpec; 897 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, 898 SelfName, false, false); 899 MarkDeclarationReferenced(Loc, IV); 900 return Owned(new (Context) 901 ObjCIvarRefExpr(IV, IV->getType(), Loc, 902 SelfExpr.takeAs<Expr>(), true, true)); 903 } 904 } else if (getCurMethodDecl()->isInstanceMethod()) { 905 // We should warn if a local variable hides an ivar. 906 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface(); 907 ObjCInterfaceDecl *ClassDeclared; 908 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 909 if (IV->getAccessControl() != ObjCIvarDecl::Private || 910 IFace == ClassDeclared) 911 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 912 } 913 } 914 915 // Needed to implement property "super.method" notation. 916 if (Lookup.empty() && II->isStr("super")) { 917 QualType T; 918 919 if (getCurMethodDecl()->isInstanceMethod()) 920 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType( 921 getCurMethodDecl()->getClassInterface())); 922 else 923 T = Context.getObjCClassType(); 924 return Owned(new (Context) ObjCSuperExpr(Loc, T)); 925 } 926 927 // Sentinel value saying that we didn't do anything special. 928 return Owned((Expr*) 0); 929} 930 931/// \brief Cast member's object to its own class if necessary. 932bool 933Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) { 934 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member)) 935 if (CXXRecordDecl *RD = 936 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) { 937 QualType DestType = 938 Context.getCanonicalType(Context.getTypeDeclType(RD)); 939 if (DestType->isDependentType() || From->getType()->isDependentType()) 940 return false; 941 QualType FromRecordType = From->getType(); 942 QualType DestRecordType = DestType; 943 if (FromRecordType->getAs<PointerType>()) { 944 DestType = Context.getPointerType(DestType); 945 FromRecordType = FromRecordType->getPointeeType(); 946 } 947 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) && 948 CheckDerivedToBaseConversion(FromRecordType, 949 DestRecordType, 950 From->getSourceRange().getBegin(), 951 From->getSourceRange())) 952 return true; 953 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase, 954 /*isLvalue=*/true); 955 } 956 return false; 957} 958 959/// \brief Build a MemberExpr AST node. 960static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow, 961 const CXXScopeSpec *SS, NamedDecl *Member, 962 SourceLocation Loc, QualType Ty, 963 const TemplateArgumentListInfo *TemplateArgs = 0) { 964 NestedNameSpecifier *Qualifier = 0; 965 SourceRange QualifierRange; 966 if (SS && SS->isSet()) { 967 Qualifier = (NestedNameSpecifier *) SS->getScopeRep(); 968 QualifierRange = SS->getRange(); 969 } 970 971 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange, 972 Member, Loc, TemplateArgs, Ty); 973} 974 975/// Builds an implicit member access expression from the given 976/// unqualified lookup set, which is known to contain only class 977/// members. 978Sema::OwningExprResult 979Sema::BuildImplicitMemberReferenceExpr(const CXXScopeSpec &SS, 980 LookupResult &R, 981 const TemplateArgumentListInfo *TemplateArgs) { 982 assert(!R.empty() && !R.isAmbiguous()); 983 984 NamedDecl *D = R.getAsSingleDecl(Context); 985 SourceLocation Loc = R.getNameLoc(); 986 987 // We may have found a field within an anonymous union or struct 988 // (C++ [class.union]). 989 // FIXME: This needs to happen post-isImplicitMemberReference? 990 // FIXME: template-ids inside anonymous structs? 991 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) 992 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion()) 993 return BuildAnonymousStructUnionMemberReference(Loc, FD); 994 995 QualType ThisType; 996 QualType MemberType; 997 if (isImplicitMemberReference(SS, D, Loc, ThisType, MemberType)) { 998 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType); 999 MarkDeclarationReferenced(Loc, D); 1000 if (PerformObjectMemberConversion(This, D)) 1001 return ExprError(); 1002 1003 bool ShouldCheckUse = true; 1004 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 1005 // Don't diagnose the use of a virtual member function unless it's 1006 // explicitly qualified. 1007 if (MD->isVirtual() && !SS.isSet()) 1008 ShouldCheckUse = false; 1009 } 1010 1011 if (ShouldCheckUse && DiagnoseUseOfDecl(D, Loc)) 1012 return ExprError(); 1013 return Owned(BuildMemberExpr(Context, This, true, &SS, D, Loc, MemberType, 1014 TemplateArgs)); 1015 } 1016 1017 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 1018 if (!Method->isStatic()) 1019 return ExprError(Diag(Loc, diag::err_member_call_without_object)); 1020 } 1021 1022 if (isa<FieldDecl>(D)) { 1023 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { 1024 if (MD->isStatic()) { 1025 // "invalid use of member 'x' in static member function" 1026 Diag(Loc, diag::err_invalid_member_use_in_static_method) 1027 << D->getDeclName(); 1028 return ExprError(); 1029 } 1030 } 1031 1032 // Any other ways we could have found the field in a well-formed 1033 // program would have been turned into implicit member expressions 1034 // above. 1035 Diag(Loc, diag::err_invalid_non_static_member_use) 1036 << D->getDeclName(); 1037 return ExprError(); 1038 } 1039 1040 // We're not in an implicit member-reference context, but the lookup 1041 // results might not require an instance. Try to build a non-member 1042 // decl reference. 1043 if (TemplateArgs) 1044 return BuildTemplateIdExpr(SS, R, /* ADL */ false, *TemplateArgs); 1045 1046 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false); 1047} 1048 1049bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 1050 const LookupResult &R, 1051 bool HasTrailingLParen) { 1052 // Only when used directly as the postfix-expression of a call. 1053 if (!HasTrailingLParen) 1054 return false; 1055 1056 // Never if a scope specifier was provided. 1057 if (SS.isSet()) 1058 return false; 1059 1060 // Only in C++ or ObjC++. 1061 if (!getLangOptions().CPlusPlus) 1062 return false; 1063 1064 // Turn off ADL when we find certain kinds of declarations during 1065 // normal lookup: 1066 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 1067 NamedDecl *D = *I; 1068 1069 // C++0x [basic.lookup.argdep]p3: 1070 // -- a declaration of a class member 1071 // Since using decls preserve this property, we check this on the 1072 // original decl. 1073 if (D->getDeclContext()->isRecord()) 1074 return false; 1075 1076 // C++0x [basic.lookup.argdep]p3: 1077 // -- a block-scope function declaration that is not a 1078 // using-declaration 1079 // NOTE: we also trigger this for function templates (in fact, we 1080 // don't check the decl type at all, since all other decl types 1081 // turn off ADL anyway). 1082 if (isa<UsingShadowDecl>(D)) 1083 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 1084 else if (D->getDeclContext()->isFunctionOrMethod()) 1085 return false; 1086 1087 // C++0x [basic.lookup.argdep]p3: 1088 // -- a declaration that is neither a function or a function 1089 // template 1090 // And also for builtin functions. 1091 if (isa<FunctionDecl>(D)) { 1092 FunctionDecl *FDecl = cast<FunctionDecl>(D); 1093 1094 // But also builtin functions. 1095 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 1096 return false; 1097 } else if (!isa<FunctionTemplateDecl>(D)) 1098 return false; 1099 } 1100 1101 return true; 1102} 1103 1104 1105/// Diagnoses obvious problems with the use of the given declaration 1106/// as an expression. This is only actually called for lookups that 1107/// were not overloaded, and it doesn't promise that the declaration 1108/// will in fact be used. 1109static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 1110 if (isa<TypedefDecl>(D)) { 1111 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 1112 return true; 1113 } 1114 1115 if (isa<ObjCInterfaceDecl>(D)) { 1116 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 1117 return true; 1118 } 1119 1120 if (isa<NamespaceDecl>(D)) { 1121 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 1122 return true; 1123 } 1124 1125 return false; 1126} 1127 1128Sema::OwningExprResult 1129Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 1130 LookupResult &R, 1131 bool NeedsADL) { 1132 assert(R.getResultKind() != LookupResult::FoundUnresolvedValue); 1133 1134 // If this isn't an overloaded result and we don't need ADL, just 1135 // build an ordinary singleton decl ref. 1136 if (!NeedsADL && !R.isOverloadedResult()) 1137 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl()); 1138 1139 // We only need to check the declaration if there's exactly one 1140 // result, because in the overloaded case the results can only be 1141 // functions and function templates. 1142 if (R.isSingleResult() && 1143 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 1144 return ExprError(); 1145 1146 bool Dependent 1147 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0); 1148 UnresolvedLookupExpr *ULE 1149 = UnresolvedLookupExpr::Create(Context, Dependent, 1150 (NestedNameSpecifier*) SS.getScopeRep(), 1151 SS.getRange(), 1152 R.getLookupName(), R.getNameLoc(), 1153 NeedsADL, R.isOverloadedResult()); 1154 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1155 ULE->addDecl(*I); 1156 1157 return Owned(ULE); 1158} 1159 1160 1161/// \brief Complete semantic analysis for a reference to the given declaration. 1162Sema::OwningExprResult 1163Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 1164 SourceLocation Loc, NamedDecl *D) { 1165 assert(D && "Cannot refer to a NULL declaration"); 1166 assert(!isa<FunctionTemplateDecl>(D) && 1167 "Cannot refer unambiguously to a function template"); 1168 DeclarationName Name = D->getDeclName(); 1169 1170 if (CheckDeclInExpr(*this, Loc, D)) 1171 return ExprError(); 1172 1173 ValueDecl *VD = cast<ValueDecl>(D); 1174 1175 // Check whether this declaration can be used. Note that we suppress 1176 // this check when we're going to perform argument-dependent lookup 1177 // on this function name, because this might not be the function 1178 // that overload resolution actually selects. 1179 if (DiagnoseUseOfDecl(VD, Loc)) 1180 return ExprError(); 1181 1182 // Only create DeclRefExpr's for valid Decl's. 1183 if (VD->isInvalidDecl()) 1184 return ExprError(); 1185 1186 // If the identifier reference is inside a block, and it refers to a value 1187 // that is outside the block, create a BlockDeclRefExpr instead of a 1188 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when 1189 // the block is formed. 1190 // 1191 // We do not do this for things like enum constants, global variables, etc, 1192 // as they do not get snapshotted. 1193 // 1194 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) { 1195 MarkDeclarationReferenced(Loc, VD); 1196 QualType ExprTy = VD->getType().getNonReferenceType(); 1197 // The BlocksAttr indicates the variable is bound by-reference. 1198 if (VD->getAttr<BlocksAttr>()) 1199 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true)); 1200 // This is to record that a 'const' was actually synthesize and added. 1201 bool constAdded = !ExprTy.isConstQualified(); 1202 // Variable will be bound by-copy, make it const within the closure. 1203 1204 ExprTy.addConst(); 1205 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false, 1206 constAdded)); 1207 } 1208 // If this reference is not in a block or if the referenced variable is 1209 // within the block, create a normal DeclRefExpr. 1210 1211 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS); 1212} 1213 1214Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, 1215 tok::TokenKind Kind) { 1216 PredefinedExpr::IdentType IT; 1217 1218 switch (Kind) { 1219 default: assert(0 && "Unknown simple primary expr!"); 1220 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 1221 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 1222 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 1223 } 1224 1225 // Pre-defined identifiers are of type char[x], where x is the length of the 1226 // string. 1227 1228 Decl *currentDecl = getCurFunctionOrMethodDecl(); 1229 if (!currentDecl) { 1230 Diag(Loc, diag::ext_predef_outside_function); 1231 currentDecl = Context.getTranslationUnitDecl(); 1232 } 1233 1234 QualType ResTy; 1235 if (cast<DeclContext>(currentDecl)->isDependentContext()) { 1236 ResTy = Context.DependentTy; 1237 } else { 1238 unsigned Length = 1239 PredefinedExpr::ComputeName(Context, IT, currentDecl).length(); 1240 1241 llvm::APInt LengthI(32, Length + 1); 1242 ResTy = Context.CharTy.withConst(); 1243 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 1244 } 1245 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 1246} 1247 1248Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) { 1249 llvm::SmallString<16> CharBuffer; 1250 CharBuffer.resize(Tok.getLength()); 1251 const char *ThisTokBegin = &CharBuffer[0]; 1252 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin); 1253 1254 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 1255 Tok.getLocation(), PP); 1256 if (Literal.hadError()) 1257 return ExprError(); 1258 1259 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy; 1260 1261 return Owned(new (Context) CharacterLiteral(Literal.getValue(), 1262 Literal.isWide(), 1263 type, Tok.getLocation())); 1264} 1265 1266Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) { 1267 // Fast path for a single digit (which is quite common). A single digit 1268 // cannot have a trigraph, escaped newline, radix prefix, or type suffix. 1269 if (Tok.getLength() == 1) { 1270 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 1271 unsigned IntSize = Context.Target.getIntWidth(); 1272 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'), 1273 Context.IntTy, Tok.getLocation())); 1274 } 1275 1276 llvm::SmallString<512> IntegerBuffer; 1277 // Add padding so that NumericLiteralParser can overread by one character. 1278 IntegerBuffer.resize(Tok.getLength()+1); 1279 const char *ThisTokBegin = &IntegerBuffer[0]; 1280 1281 // Get the spelling of the token, which eliminates trigraphs, etc. 1282 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin); 1283 1284 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 1285 Tok.getLocation(), PP); 1286 if (Literal.hadError) 1287 return ExprError(); 1288 1289 Expr *Res; 1290 1291 if (Literal.isFloatingLiteral()) { 1292 QualType Ty; 1293 if (Literal.isFloat) 1294 Ty = Context.FloatTy; 1295 else if (!Literal.isLong) 1296 Ty = Context.DoubleTy; 1297 else 1298 Ty = Context.LongDoubleTy; 1299 1300 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty); 1301 1302 // isExact will be set by GetFloatValue(). 1303 bool isExact = false; 1304 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact); 1305 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation()); 1306 1307 } else if (!Literal.isIntegerLiteral()) { 1308 return ExprError(); 1309 } else { 1310 QualType Ty; 1311 1312 // long long is a C99 feature. 1313 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x && 1314 Literal.isLongLong) 1315 Diag(Tok.getLocation(), diag::ext_longlong); 1316 1317 // Get the value in the widest-possible width. 1318 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0); 1319 1320 if (Literal.GetIntegerValue(ResultVal)) { 1321 // If this value didn't fit into uintmax_t, warn and force to ull. 1322 Diag(Tok.getLocation(), diag::warn_integer_too_large); 1323 Ty = Context.UnsignedLongLongTy; 1324 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 1325 "long long is not intmax_t?"); 1326 } else { 1327 // If this value fits into a ULL, try to figure out what else it fits into 1328 // according to the rules of C99 6.4.4.1p5. 1329 1330 // Octal, Hexadecimal, and integers with a U suffix are allowed to 1331 // be an unsigned int. 1332 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 1333 1334 // Check from smallest to largest, picking the smallest type we can. 1335 unsigned Width = 0; 1336 if (!Literal.isLong && !Literal.isLongLong) { 1337 // Are int/unsigned possibilities? 1338 unsigned IntSize = Context.Target.getIntWidth(); 1339 1340 // Does it fit in a unsigned int? 1341 if (ResultVal.isIntN(IntSize)) { 1342 // Does it fit in a signed int? 1343 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 1344 Ty = Context.IntTy; 1345 else if (AllowUnsigned) 1346 Ty = Context.UnsignedIntTy; 1347 Width = IntSize; 1348 } 1349 } 1350 1351 // Are long/unsigned long possibilities? 1352 if (Ty.isNull() && !Literal.isLongLong) { 1353 unsigned LongSize = Context.Target.getLongWidth(); 1354 1355 // Does it fit in a unsigned long? 1356 if (ResultVal.isIntN(LongSize)) { 1357 // Does it fit in a signed long? 1358 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 1359 Ty = Context.LongTy; 1360 else if (AllowUnsigned) 1361 Ty = Context.UnsignedLongTy; 1362 Width = LongSize; 1363 } 1364 } 1365 1366 // Finally, check long long if needed. 1367 if (Ty.isNull()) { 1368 unsigned LongLongSize = Context.Target.getLongLongWidth(); 1369 1370 // Does it fit in a unsigned long long? 1371 if (ResultVal.isIntN(LongLongSize)) { 1372 // Does it fit in a signed long long? 1373 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0) 1374 Ty = Context.LongLongTy; 1375 else if (AllowUnsigned) 1376 Ty = Context.UnsignedLongLongTy; 1377 Width = LongLongSize; 1378 } 1379 } 1380 1381 // If we still couldn't decide a type, we probably have something that 1382 // does not fit in a signed long long, but has no U suffix. 1383 if (Ty.isNull()) { 1384 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 1385 Ty = Context.UnsignedLongLongTy; 1386 Width = Context.Target.getLongLongWidth(); 1387 } 1388 1389 if (ResultVal.getBitWidth() != Width) 1390 ResultVal.trunc(Width); 1391 } 1392 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation()); 1393 } 1394 1395 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 1396 if (Literal.isImaginary) 1397 Res = new (Context) ImaginaryLiteral(Res, 1398 Context.getComplexType(Res->getType())); 1399 1400 return Owned(Res); 1401} 1402 1403Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L, 1404 SourceLocation R, ExprArg Val) { 1405 Expr *E = Val.takeAs<Expr>(); 1406 assert((E != 0) && "ActOnParenExpr() missing expr"); 1407 return Owned(new (Context) ParenExpr(L, R, E)); 1408} 1409 1410/// The UsualUnaryConversions() function is *not* called by this routine. 1411/// See C99 6.3.2.1p[2-4] for more details. 1412bool Sema::CheckSizeOfAlignOfOperand(QualType exprType, 1413 SourceLocation OpLoc, 1414 const SourceRange &ExprRange, 1415 bool isSizeof) { 1416 if (exprType->isDependentType()) 1417 return false; 1418 1419 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 1420 // the result is the size of the referenced type." 1421 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 1422 // result shall be the alignment of the referenced type." 1423 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>()) 1424 exprType = Ref->getPointeeType(); 1425 1426 // C99 6.5.3.4p1: 1427 if (exprType->isFunctionType()) { 1428 // alignof(function) is allowed as an extension. 1429 if (isSizeof) 1430 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange; 1431 return false; 1432 } 1433 1434 // Allow sizeof(void)/alignof(void) as an extension. 1435 if (exprType->isVoidType()) { 1436 Diag(OpLoc, diag::ext_sizeof_void_type) 1437 << (isSizeof ? "sizeof" : "__alignof") << ExprRange; 1438 return false; 1439 } 1440 1441 if (RequireCompleteType(OpLoc, exprType, 1442 isSizeof ? diag::err_sizeof_incomplete_type : 1443 PDiag(diag::err_alignof_incomplete_type) 1444 << ExprRange)) 1445 return true; 1446 1447 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode. 1448 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) { 1449 Diag(OpLoc, diag::err_sizeof_nonfragile_interface) 1450 << exprType << isSizeof << ExprRange; 1451 return true; 1452 } 1453 1454 return false; 1455} 1456 1457bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc, 1458 const SourceRange &ExprRange) { 1459 E = E->IgnoreParens(); 1460 1461 // alignof decl is always ok. 1462 if (isa<DeclRefExpr>(E)) 1463 return false; 1464 1465 // Cannot know anything else if the expression is dependent. 1466 if (E->isTypeDependent()) 1467 return false; 1468 1469 if (E->getBitField()) { 1470 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange; 1471 return true; 1472 } 1473 1474 // Alignment of a field access is always okay, so long as it isn't a 1475 // bit-field. 1476 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) 1477 if (isa<FieldDecl>(ME->getMemberDecl())) 1478 return false; 1479 1480 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false); 1481} 1482 1483/// \brief Build a sizeof or alignof expression given a type operand. 1484Action::OwningExprResult 1485Sema::CreateSizeOfAlignOfExpr(DeclaratorInfo *DInfo, 1486 SourceLocation OpLoc, 1487 bool isSizeOf, SourceRange R) { 1488 if (!DInfo) 1489 return ExprError(); 1490 1491 QualType T = DInfo->getType(); 1492 1493 if (!T->isDependentType() && 1494 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf)) 1495 return ExprError(); 1496 1497 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 1498 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, DInfo, 1499 Context.getSizeType(), OpLoc, 1500 R.getEnd())); 1501} 1502 1503/// \brief Build a sizeof or alignof expression given an expression 1504/// operand. 1505Action::OwningExprResult 1506Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc, 1507 bool isSizeOf, SourceRange R) { 1508 // Verify that the operand is valid. 1509 bool isInvalid = false; 1510 if (E->isTypeDependent()) { 1511 // Delay type-checking for type-dependent expressions. 1512 } else if (!isSizeOf) { 1513 isInvalid = CheckAlignOfExpr(E, OpLoc, R); 1514 } else if (E->getBitField()) { // C99 6.5.3.4p1. 1515 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0; 1516 isInvalid = true; 1517 } else { 1518 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true); 1519 } 1520 1521 if (isInvalid) 1522 return ExprError(); 1523 1524 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 1525 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E, 1526 Context.getSizeType(), OpLoc, 1527 R.getEnd())); 1528} 1529 1530/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and 1531/// the same for @c alignof and @c __alignof 1532/// Note that the ArgRange is invalid if isType is false. 1533Action::OwningExprResult 1534Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType, 1535 void *TyOrEx, const SourceRange &ArgRange) { 1536 // If error parsing type, ignore. 1537 if (TyOrEx == 0) return ExprError(); 1538 1539 if (isType) { 1540 DeclaratorInfo *DInfo; 1541 (void) GetTypeFromParser(TyOrEx, &DInfo); 1542 return CreateSizeOfAlignOfExpr(DInfo, OpLoc, isSizeof, ArgRange); 1543 } 1544 1545 Expr *ArgEx = (Expr *)TyOrEx; 1546 Action::OwningExprResult Result 1547 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange()); 1548 1549 if (Result.isInvalid()) 1550 DeleteExpr(ArgEx); 1551 1552 return move(Result); 1553} 1554 1555QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) { 1556 if (V->isTypeDependent()) 1557 return Context.DependentTy; 1558 1559 // These operators return the element type of a complex type. 1560 if (const ComplexType *CT = V->getType()->getAs<ComplexType>()) 1561 return CT->getElementType(); 1562 1563 // Otherwise they pass through real integer and floating point types here. 1564 if (V->getType()->isArithmeticType()) 1565 return V->getType(); 1566 1567 // Reject anything else. 1568 Diag(Loc, diag::err_realimag_invalid_type) << V->getType() 1569 << (isReal ? "__real" : "__imag"); 1570 return QualType(); 1571} 1572 1573 1574 1575Action::OwningExprResult 1576Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 1577 tok::TokenKind Kind, ExprArg Input) { 1578 UnaryOperator::Opcode Opc; 1579 switch (Kind) { 1580 default: assert(0 && "Unknown unary op!"); 1581 case tok::plusplus: Opc = UnaryOperator::PostInc; break; 1582 case tok::minusminus: Opc = UnaryOperator::PostDec; break; 1583 } 1584 1585 return BuildUnaryOp(S, OpLoc, Opc, move(Input)); 1586} 1587 1588Action::OwningExprResult 1589Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc, 1590 ExprArg Idx, SourceLocation RLoc) { 1591 // Since this might be a postfix expression, get rid of ParenListExprs. 1592 Base = MaybeConvertParenListExprToParenExpr(S, move(Base)); 1593 1594 Expr *LHSExp = static_cast<Expr*>(Base.get()), 1595 *RHSExp = static_cast<Expr*>(Idx.get()); 1596 1597 if (getLangOptions().CPlusPlus && 1598 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) { 1599 Base.release(); 1600 Idx.release(); 1601 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 1602 Context.DependentTy, RLoc)); 1603 } 1604 1605 if (getLangOptions().CPlusPlus && 1606 (LHSExp->getType()->isRecordType() || 1607 LHSExp->getType()->isEnumeralType() || 1608 RHSExp->getType()->isRecordType() || 1609 RHSExp->getType()->isEnumeralType())) { 1610 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx)); 1611 } 1612 1613 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc); 1614} 1615 1616 1617Action::OwningExprResult 1618Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc, 1619 ExprArg Idx, SourceLocation RLoc) { 1620 Expr *LHSExp = static_cast<Expr*>(Base.get()); 1621 Expr *RHSExp = static_cast<Expr*>(Idx.get()); 1622 1623 // Perform default conversions. 1624 DefaultFunctionArrayConversion(LHSExp); 1625 DefaultFunctionArrayConversion(RHSExp); 1626 1627 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 1628 1629 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 1630 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 1631 // in the subscript position. As a result, we need to derive the array base 1632 // and index from the expression types. 1633 Expr *BaseExpr, *IndexExpr; 1634 QualType ResultType; 1635 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 1636 BaseExpr = LHSExp; 1637 IndexExpr = RHSExp; 1638 ResultType = Context.DependentTy; 1639 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 1640 BaseExpr = LHSExp; 1641 IndexExpr = RHSExp; 1642 ResultType = PTy->getPointeeType(); 1643 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 1644 // Handle the uncommon case of "123[Ptr]". 1645 BaseExpr = RHSExp; 1646 IndexExpr = LHSExp; 1647 ResultType = PTy->getPointeeType(); 1648 } else if (const ObjCObjectPointerType *PTy = 1649 LHSTy->getAs<ObjCObjectPointerType>()) { 1650 BaseExpr = LHSExp; 1651 IndexExpr = RHSExp; 1652 ResultType = PTy->getPointeeType(); 1653 } else if (const ObjCObjectPointerType *PTy = 1654 RHSTy->getAs<ObjCObjectPointerType>()) { 1655 // Handle the uncommon case of "123[Ptr]". 1656 BaseExpr = RHSExp; 1657 IndexExpr = LHSExp; 1658 ResultType = PTy->getPointeeType(); 1659 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 1660 BaseExpr = LHSExp; // vectors: V[123] 1661 IndexExpr = RHSExp; 1662 1663 // FIXME: need to deal with const... 1664 ResultType = VTy->getElementType(); 1665 } else if (LHSTy->isArrayType()) { 1666 // If we see an array that wasn't promoted by 1667 // DefaultFunctionArrayConversion, it must be an array that 1668 // wasn't promoted because of the C90 rule that doesn't 1669 // allow promoting non-lvalue arrays. Warn, then 1670 // force the promotion here. 1671 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 1672 LHSExp->getSourceRange(); 1673 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 1674 CastExpr::CK_ArrayToPointerDecay); 1675 LHSTy = LHSExp->getType(); 1676 1677 BaseExpr = LHSExp; 1678 IndexExpr = RHSExp; 1679 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 1680 } else if (RHSTy->isArrayType()) { 1681 // Same as previous, except for 123[f().a] case 1682 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 1683 RHSExp->getSourceRange(); 1684 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 1685 CastExpr::CK_ArrayToPointerDecay); 1686 RHSTy = RHSExp->getType(); 1687 1688 BaseExpr = RHSExp; 1689 IndexExpr = LHSExp; 1690 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 1691 } else { 1692 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 1693 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 1694 } 1695 // C99 6.5.2.1p1 1696 if (!(IndexExpr->getType()->isIntegerType() && 1697 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent()) 1698 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 1699 << IndexExpr->getSourceRange()); 1700 1701 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 1702 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 1703 && !IndexExpr->isTypeDependent()) 1704 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 1705 1706 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 1707 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 1708 // type. Note that Functions are not objects, and that (in C99 parlance) 1709 // incomplete types are not object types. 1710 if (ResultType->isFunctionType()) { 1711 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 1712 << ResultType << BaseExpr->getSourceRange(); 1713 return ExprError(); 1714 } 1715 1716 if (!ResultType->isDependentType() && 1717 RequireCompleteType(LLoc, ResultType, 1718 PDiag(diag::err_subscript_incomplete_type) 1719 << BaseExpr->getSourceRange())) 1720 return ExprError(); 1721 1722 // Diagnose bad cases where we step over interface counts. 1723 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) { 1724 Diag(LLoc, diag::err_subscript_nonfragile_interface) 1725 << ResultType << BaseExpr->getSourceRange(); 1726 return ExprError(); 1727 } 1728 1729 Base.release(); 1730 Idx.release(); 1731 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 1732 ResultType, RLoc)); 1733} 1734 1735QualType Sema:: 1736CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc, 1737 const IdentifierInfo *CompName, 1738 SourceLocation CompLoc) { 1739 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements, 1740 // see FIXME there. 1741 // 1742 // FIXME: This logic can be greatly simplified by splitting it along 1743 // halving/not halving and reworking the component checking. 1744 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>(); 1745 1746 // The vector accessor can't exceed the number of elements. 1747 const char *compStr = CompName->getNameStart(); 1748 1749 // This flag determines whether or not the component is one of the four 1750 // special names that indicate a subset of exactly half the elements are 1751 // to be selected. 1752 bool HalvingSwizzle = false; 1753 1754 // This flag determines whether or not CompName has an 's' char prefix, 1755 // indicating that it is a string of hex values to be used as vector indices. 1756 bool HexSwizzle = *compStr == 's' || *compStr == 'S'; 1757 1758 // Check that we've found one of the special components, or that the component 1759 // names must come from the same set. 1760 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") || 1761 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) { 1762 HalvingSwizzle = true; 1763 } else if (vecType->getPointAccessorIdx(*compStr) != -1) { 1764 do 1765 compStr++; 1766 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1); 1767 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) { 1768 do 1769 compStr++; 1770 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1); 1771 } 1772 1773 if (!HalvingSwizzle && *compStr) { 1774 // We didn't get to the end of the string. This means the component names 1775 // didn't come from the same set *or* we encountered an illegal name. 1776 Diag(OpLoc, diag::err_ext_vector_component_name_illegal) 1777 << std::string(compStr,compStr+1) << SourceRange(CompLoc); 1778 return QualType(); 1779 } 1780 1781 // Ensure no component accessor exceeds the width of the vector type it 1782 // operates on. 1783 if (!HalvingSwizzle) { 1784 compStr = CompName->getNameStart(); 1785 1786 if (HexSwizzle) 1787 compStr++; 1788 1789 while (*compStr) { 1790 if (!vecType->isAccessorWithinNumElements(*compStr++)) { 1791 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length) 1792 << baseType << SourceRange(CompLoc); 1793 return QualType(); 1794 } 1795 } 1796 } 1797 1798 // If this is a halving swizzle, verify that the base type has an even 1799 // number of elements. 1800 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) { 1801 Diag(OpLoc, diag::err_ext_vector_component_requires_even) 1802 << baseType << SourceRange(CompLoc); 1803 return QualType(); 1804 } 1805 1806 // The component accessor looks fine - now we need to compute the actual type. 1807 // The vector type is implied by the component accessor. For example, 1808 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc. 1809 // vec4.s0 is a float, vec4.s23 is a vec3, etc. 1810 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2. 1811 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2 1812 : CompName->getLength(); 1813 if (HexSwizzle) 1814 CompSize--; 1815 1816 if (CompSize == 1) 1817 return vecType->getElementType(); 1818 1819 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize); 1820 // Now look up the TypeDefDecl from the vector type. Without this, 1821 // diagostics look bad. We want extended vector types to appear built-in. 1822 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) { 1823 if (ExtVectorDecls[i]->getUnderlyingType() == VT) 1824 return Context.getTypedefType(ExtVectorDecls[i]); 1825 } 1826 return VT; // should never get here (a typedef type should always be found). 1827} 1828 1829static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl, 1830 IdentifierInfo *Member, 1831 const Selector &Sel, 1832 ASTContext &Context) { 1833 1834 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member)) 1835 return PD; 1836 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel)) 1837 return OMD; 1838 1839 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(), 1840 E = PDecl->protocol_end(); I != E; ++I) { 1841 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel, 1842 Context)) 1843 return D; 1844 } 1845 return 0; 1846} 1847 1848static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy, 1849 IdentifierInfo *Member, 1850 const Selector &Sel, 1851 ASTContext &Context) { 1852 // Check protocols on qualified interfaces. 1853 Decl *GDecl = 0; 1854 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(), 1855 E = QIdTy->qual_end(); I != E; ++I) { 1856 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) { 1857 GDecl = PD; 1858 break; 1859 } 1860 // Also must look for a getter name which uses property syntax. 1861 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) { 1862 GDecl = OMD; 1863 break; 1864 } 1865 } 1866 if (!GDecl) { 1867 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(), 1868 E = QIdTy->qual_end(); I != E; ++I) { 1869 // Search in the protocol-qualifier list of current protocol. 1870 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context); 1871 if (GDecl) 1872 return GDecl; 1873 } 1874 } 1875 return GDecl; 1876} 1877 1878Action::OwningExprResult 1879Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc, 1880 tok::TokenKind OpKind, SourceLocation MemberLoc, 1881 DeclarationName MemberName, 1882 const TemplateArgumentListInfo *ExplicitTemplateArgs, 1883 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS, 1884 NamedDecl *FirstQualifierInScope) { 1885 if (SS && SS->isInvalid()) 1886 return ExprError(); 1887 1888 // Since this might be a postfix expression, get rid of ParenListExprs. 1889 Base = MaybeConvertParenListExprToParenExpr(S, move(Base)); 1890 1891 Expr *BaseExpr = Base.takeAs<Expr>(); 1892 assert(BaseExpr && "no base expression"); 1893 1894 // Perform default conversions. 1895 DefaultFunctionArrayConversion(BaseExpr); 1896 1897 QualType BaseType = BaseExpr->getType(); 1898 1899 // If the user is trying to apply -> or . to a function pointer 1900 // type, it's probably because the forgot parentheses to call that 1901 // function. Suggest the addition of those parentheses, build the 1902 // call, and continue on. 1903 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 1904 if (const FunctionProtoType *Fun 1905 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) { 1906 QualType ResultTy = Fun->getResultType(); 1907 if (Fun->getNumArgs() == 0 && 1908 ((OpKind == tok::period && ResultTy->isRecordType()) || 1909 (OpKind == tok::arrow && ResultTy->isPointerType() && 1910 ResultTy->getAs<PointerType>()->getPointeeType() 1911 ->isRecordType()))) { 1912 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd()); 1913 Diag(Loc, diag::err_member_reference_needs_call) 1914 << QualType(Fun, 0) 1915 << CodeModificationHint::CreateInsertion(Loc, "()"); 1916 1917 OwningExprResult NewBase 1918 = ActOnCallExpr(S, ExprArg(*this, BaseExpr), Loc, 1919 MultiExprArg(*this, 0, 0), 0, Loc); 1920 if (NewBase.isInvalid()) 1921 return move(NewBase); 1922 1923 BaseExpr = NewBase.takeAs<Expr>(); 1924 DefaultFunctionArrayConversion(BaseExpr); 1925 BaseType = BaseExpr->getType(); 1926 } 1927 } 1928 } 1929 1930 // If this is an Objective-C pseudo-builtin and a definition is provided then 1931 // use that. 1932 if (BaseType->isObjCIdType()) { 1933 // We have an 'id' type. Rather than fall through, we check if this 1934 // is a reference to 'isa'. 1935 if (BaseType != Context.ObjCIdRedefinitionType) { 1936 BaseType = Context.ObjCIdRedefinitionType; 1937 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast); 1938 } 1939 } 1940 assert(!BaseType.isNull() && "no type for member expression"); 1941 1942 // Handle properties on ObjC 'Class' types. 1943 if (OpKind == tok::period && BaseType->isObjCClassType()) { 1944 // Also must look for a getter name which uses property syntax. 1945 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 1946 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 1947 if (ObjCMethodDecl *MD = getCurMethodDecl()) { 1948 ObjCInterfaceDecl *IFace = MD->getClassInterface(); 1949 ObjCMethodDecl *Getter; 1950 // FIXME: need to also look locally in the implementation. 1951 if ((Getter = IFace->lookupClassMethod(Sel))) { 1952 // Check the use of this method. 1953 if (DiagnoseUseOfDecl(Getter, MemberLoc)) 1954 return ExprError(); 1955 } 1956 // If we found a getter then this may be a valid dot-reference, we 1957 // will look for the matching setter, in case it is needed. 1958 Selector SetterSel = 1959 SelectorTable::constructSetterName(PP.getIdentifierTable(), 1960 PP.getSelectorTable(), Member); 1961 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel); 1962 if (!Setter) { 1963 // If this reference is in an @implementation, also check for 'private' 1964 // methods. 1965 Setter = IFace->lookupPrivateInstanceMethod(SetterSel); 1966 } 1967 // Look through local category implementations associated with the class. 1968 if (!Setter) 1969 Setter = IFace->getCategoryClassMethod(SetterSel); 1970 1971 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) 1972 return ExprError(); 1973 1974 if (Getter || Setter) { 1975 QualType PType; 1976 1977 if (Getter) 1978 PType = Getter->getResultType(); 1979 else 1980 // Get the expression type from Setter's incoming parameter. 1981 PType = (*(Setter->param_end() -1))->getType(); 1982 // FIXME: we must check that the setter has property type. 1983 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, 1984 PType, 1985 Setter, MemberLoc, BaseExpr)); 1986 } 1987 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 1988 << MemberName << BaseType); 1989 } 1990 } 1991 1992 if (BaseType->isObjCClassType() && 1993 BaseType != Context.ObjCClassRedefinitionType) { 1994 BaseType = Context.ObjCClassRedefinitionType; 1995 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast); 1996 } 1997 1998 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr 1999 // must have pointer type, and the accessed type is the pointee. 2000 if (OpKind == tok::arrow) { 2001 if (BaseType->isDependentType()) { 2002 NestedNameSpecifier *Qualifier = 0; 2003 if (SS) { 2004 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep()); 2005 if (!FirstQualifierInScope) 2006 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier); 2007 } 2008 2009 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, true, 2010 OpLoc, Qualifier, 2011 SS? SS->getRange() : SourceRange(), 2012 FirstQualifierInScope, 2013 MemberName, 2014 MemberLoc, 2015 ExplicitTemplateArgs)); 2016 } 2017 else if (const PointerType *PT = BaseType->getAs<PointerType>()) 2018 BaseType = PT->getPointeeType(); 2019 else if (BaseType->isObjCObjectPointerType()) 2020 ; 2021 else 2022 return ExprError(Diag(MemberLoc, 2023 diag::err_typecheck_member_reference_arrow) 2024 << BaseType << BaseExpr->getSourceRange()); 2025 } else if (BaseType->isDependentType()) { 2026 // Require that the base type isn't a pointer type 2027 // (so we'll report an error for) 2028 // T* t; 2029 // t.f; 2030 // 2031 // In Obj-C++, however, the above expression is valid, since it could be 2032 // accessing the 'f' property if T is an Obj-C interface. The extra check 2033 // allows this, while still reporting an error if T is a struct pointer. 2034 const PointerType *PT = BaseType->getAs<PointerType>(); 2035 2036 if (!PT || (getLangOptions().ObjC1 && 2037 !PT->getPointeeType()->isRecordType())) { 2038 NestedNameSpecifier *Qualifier = 0; 2039 if (SS) { 2040 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep()); 2041 if (!FirstQualifierInScope) 2042 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier); 2043 } 2044 2045 return Owned(CXXDependentScopeMemberExpr::Create(Context, 2046 BaseExpr, false, 2047 OpLoc, 2048 Qualifier, 2049 SS? SS->getRange() : SourceRange(), 2050 FirstQualifierInScope, 2051 MemberName, 2052 MemberLoc, 2053 ExplicitTemplateArgs)); 2054 } 2055 } 2056 2057 // Handle field access to simple records. This also handles access to fields 2058 // of the ObjC 'id' struct. 2059 if (const RecordType *RTy = BaseType->getAs<RecordType>()) { 2060 RecordDecl *RDecl = RTy->getDecl(); 2061 if (RequireCompleteType(OpLoc, BaseType, 2062 PDiag(diag::err_typecheck_incomplete_tag) 2063 << BaseExpr->getSourceRange())) 2064 return ExprError(); 2065 2066 DeclContext *DC = RDecl; 2067 if (SS && SS->isSet()) { 2068 // If the member name was a qualified-id, look into the 2069 // nested-name-specifier. 2070 DC = computeDeclContext(*SS, false); 2071 2072 if (!isa<TypeDecl>(DC)) { 2073 Diag(MemberLoc, diag::err_qualified_member_nonclass) 2074 << DC << SS->getRange(); 2075 return ExprError(); 2076 } 2077 2078 // FIXME: If DC is not computable, we should build a 2079 // CXXDependentScopeMemberExpr. 2080 assert(DC && "Cannot handle non-computable dependent contexts in lookup"); 2081 } 2082 2083 // The record definition is complete, now make sure the member is valid. 2084 LookupResult Result(*this, MemberName, MemberLoc, LookupMemberName); 2085 LookupQualifiedName(Result, DC); 2086 2087 if (Result.empty()) 2088 return ExprError(Diag(MemberLoc, diag::err_no_member) 2089 << MemberName << DC << BaseExpr->getSourceRange()); 2090 if (Result.isAmbiguous()) 2091 return ExprError(); 2092 2093 NamedDecl *MemberDecl = Result.getAsSingleDecl(Context); 2094 2095 if (SS && SS->isSet()) { 2096 TypeDecl* TyD = cast<TypeDecl>(MemberDecl->getDeclContext()); 2097 QualType BaseTypeCanon 2098 = Context.getCanonicalType(BaseType).getUnqualifiedType(); 2099 QualType MemberTypeCanon 2100 = Context.getCanonicalType(Context.getTypeDeclType(TyD)); 2101 2102 if (BaseTypeCanon != MemberTypeCanon && 2103 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon)) 2104 return ExprError(Diag(SS->getBeginLoc(), 2105 diag::err_not_direct_base_or_virtual) 2106 << MemberTypeCanon << BaseTypeCanon); 2107 } 2108 2109 // If the decl being referenced had an error, return an error for this 2110 // sub-expr without emitting another error, in order to avoid cascading 2111 // error cases. 2112 if (MemberDecl->isInvalidDecl()) 2113 return ExprError(); 2114 2115 bool ShouldCheckUse = true; 2116 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) { 2117 // Don't diagnose the use of a virtual member function unless it's 2118 // explicitly qualified. 2119 if (MD->isVirtual() && (!SS || !SS->isSet())) 2120 ShouldCheckUse = false; 2121 } 2122 2123 // Check the use of this field 2124 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) 2125 return ExprError(); 2126 2127 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) { 2128 // We may have found a field within an anonymous union or struct 2129 // (C++ [class.union]). 2130 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion()) 2131 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD, 2132 BaseExpr, OpLoc); 2133 2134 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref] 2135 QualType MemberType = FD->getType(); 2136 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) 2137 MemberType = Ref->getPointeeType(); 2138 else { 2139 Qualifiers BaseQuals = BaseType.getQualifiers(); 2140 BaseQuals.removeObjCGCAttr(); 2141 if (FD->isMutable()) BaseQuals.removeConst(); 2142 2143 Qualifiers MemberQuals 2144 = Context.getCanonicalType(MemberType).getQualifiers(); 2145 2146 Qualifiers Combined = BaseQuals + MemberQuals; 2147 if (Combined != MemberQuals) 2148 MemberType = Context.getQualifiedType(MemberType, Combined); 2149 } 2150 2151 MarkDeclarationReferenced(MemberLoc, FD); 2152 if (PerformObjectMemberConversion(BaseExpr, FD)) 2153 return ExprError(); 2154 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS, 2155 FD, MemberLoc, MemberType)); 2156 } 2157 2158 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) { 2159 MarkDeclarationReferenced(MemberLoc, MemberDecl); 2160 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS, 2161 Var, MemberLoc, 2162 Var->getType().getNonReferenceType())); 2163 } 2164 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) { 2165 MarkDeclarationReferenced(MemberLoc, MemberDecl); 2166 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS, 2167 MemberFn, MemberLoc, 2168 MemberFn->getType())); 2169 } 2170 if (FunctionTemplateDecl *FunTmpl 2171 = dyn_cast<FunctionTemplateDecl>(MemberDecl)) { 2172 MarkDeclarationReferenced(MemberLoc, MemberDecl); 2173 2174 if (ExplicitTemplateArgs) 2175 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow, 2176 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0), 2177 SS? SS->getRange() : SourceRange(), 2178 FunTmpl, MemberLoc, 2179 ExplicitTemplateArgs, 2180 Context.OverloadTy)); 2181 2182 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS, 2183 FunTmpl, MemberLoc, 2184 Context.OverloadTy)); 2185 } 2186 if (OverloadedFunctionDecl *Ovl 2187 = dyn_cast<OverloadedFunctionDecl>(MemberDecl)) { 2188 if (ExplicitTemplateArgs) 2189 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow, 2190 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0), 2191 SS? SS->getRange() : SourceRange(), 2192 Ovl, MemberLoc, ExplicitTemplateArgs, 2193 Context.OverloadTy)); 2194 2195 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS, 2196 Ovl, MemberLoc, Context.OverloadTy)); 2197 } 2198 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) { 2199 MarkDeclarationReferenced(MemberLoc, MemberDecl); 2200 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS, 2201 Enum, MemberLoc, Enum->getType())); 2202 } 2203 if (isa<TypeDecl>(MemberDecl)) 2204 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type) 2205 << MemberName << int(OpKind == tok::arrow)); 2206 2207 // We found a declaration kind that we didn't expect. This is a 2208 // generic error message that tells the user that she can't refer 2209 // to this member with '.' or '->'. 2210 return ExprError(Diag(MemberLoc, 2211 diag::err_typecheck_member_reference_unknown) 2212 << MemberName << int(OpKind == tok::arrow)); 2213 } 2214 2215 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring 2216 // into a record type was handled above, any destructor we see here is a 2217 // pseudo-destructor. 2218 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) { 2219 // C++ [expr.pseudo]p2: 2220 // The left hand side of the dot operator shall be of scalar type. The 2221 // left hand side of the arrow operator shall be of pointer to scalar 2222 // type. 2223 if (!BaseType->isScalarType()) 2224 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar) 2225 << BaseType << BaseExpr->getSourceRange()); 2226 2227 // [...] The type designated by the pseudo-destructor-name shall be the 2228 // same as the object type. 2229 if (!MemberName.getCXXNameType()->isDependentType() && 2230 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType())) 2231 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch) 2232 << BaseType << MemberName.getCXXNameType() 2233 << BaseExpr->getSourceRange() << SourceRange(MemberLoc)); 2234 2235 // [...] Furthermore, the two type-names in a pseudo-destructor-name of 2236 // the form 2237 // 2238 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name 2239 // 2240 // shall designate the same scalar type. 2241 // 2242 // FIXME: DPG can't see any way to trigger this particular clause, so it 2243 // isn't checked here. 2244 2245 // FIXME: We've lost the precise spelling of the type by going through 2246 // DeclarationName. Can we do better? 2247 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr, 2248 OpKind == tok::arrow, 2249 OpLoc, 2250 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0), 2251 SS? SS->getRange() : SourceRange(), 2252 MemberName.getCXXNameType(), 2253 MemberLoc)); 2254 } 2255 2256 // Handle access to Objective-C instance variables, such as "Obj->ivar" and 2257 // (*Obj).ivar. 2258 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) || 2259 (OpKind == tok::period && BaseType->isObjCInterfaceType())) { 2260 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>(); 2261 const ObjCInterfaceType *IFaceT = 2262 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>(); 2263 if (IFaceT) { 2264 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 2265 2266 ObjCInterfaceDecl *IDecl = IFaceT->getDecl(); 2267 ObjCInterfaceDecl *ClassDeclared; 2268 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 2269 2270 if (IV) { 2271 // If the decl being referenced had an error, return an error for this 2272 // sub-expr without emitting another error, in order to avoid cascading 2273 // error cases. 2274 if (IV->isInvalidDecl()) 2275 return ExprError(); 2276 2277 // Check whether we can reference this field. 2278 if (DiagnoseUseOfDecl(IV, MemberLoc)) 2279 return ExprError(); 2280 if (IV->getAccessControl() != ObjCIvarDecl::Public && 2281 IV->getAccessControl() != ObjCIvarDecl::Package) { 2282 ObjCInterfaceDecl *ClassOfMethodDecl = 0; 2283 if (ObjCMethodDecl *MD = getCurMethodDecl()) 2284 ClassOfMethodDecl = MD->getClassInterface(); 2285 else if (ObjCImpDecl && getCurFunctionDecl()) { 2286 // Case of a c-function declared inside an objc implementation. 2287 // FIXME: For a c-style function nested inside an objc implementation 2288 // class, there is no implementation context available, so we pass 2289 // down the context as argument to this routine. Ideally, this context 2290 // need be passed down in the AST node and somehow calculated from the 2291 // AST for a function decl. 2292 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>(); 2293 if (ObjCImplementationDecl *IMPD = 2294 dyn_cast<ObjCImplementationDecl>(ImplDecl)) 2295 ClassOfMethodDecl = IMPD->getClassInterface(); 2296 else if (ObjCCategoryImplDecl* CatImplClass = 2297 dyn_cast<ObjCCategoryImplDecl>(ImplDecl)) 2298 ClassOfMethodDecl = CatImplClass->getClassInterface(); 2299 } 2300 2301 if (IV->getAccessControl() == ObjCIvarDecl::Private) { 2302 if (ClassDeclared != IDecl || 2303 ClassOfMethodDecl != ClassDeclared) 2304 Diag(MemberLoc, diag::error_private_ivar_access) 2305 << IV->getDeclName(); 2306 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl)) 2307 // @protected 2308 Diag(MemberLoc, diag::error_protected_ivar_access) 2309 << IV->getDeclName(); 2310 } 2311 2312 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(), 2313 MemberLoc, BaseExpr, 2314 OpKind == tok::arrow)); 2315 } 2316 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar) 2317 << IDecl->getDeclName() << MemberName 2318 << BaseExpr->getSourceRange()); 2319 } 2320 } 2321 // Handle properties on 'id' and qualified "id". 2322 if (OpKind == tok::period && (BaseType->isObjCIdType() || 2323 BaseType->isObjCQualifiedIdType())) { 2324 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>(); 2325 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 2326 2327 // Check protocols on qualified interfaces. 2328 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 2329 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) { 2330 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) { 2331 // Check the use of this declaration 2332 if (DiagnoseUseOfDecl(PD, MemberLoc)) 2333 return ExprError(); 2334 2335 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(), 2336 MemberLoc, BaseExpr)); 2337 } 2338 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) { 2339 // Check the use of this method. 2340 if (DiagnoseUseOfDecl(OMD, MemberLoc)) 2341 return ExprError(); 2342 2343 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel, 2344 OMD->getResultType(), 2345 OMD, OpLoc, MemberLoc, 2346 NULL, 0)); 2347 } 2348 } 2349 2350 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 2351 << MemberName << BaseType); 2352 } 2353 // Handle Objective-C property access, which is "Obj.property" where Obj is a 2354 // pointer to a (potentially qualified) interface type. 2355 const ObjCObjectPointerType *OPT; 2356 if (OpKind == tok::period && 2357 (OPT = BaseType->getAsObjCInterfacePointerType())) { 2358 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType(); 2359 ObjCInterfaceDecl *IFace = IFaceT->getDecl(); 2360 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 2361 2362 // Search for a declared property first. 2363 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) { 2364 // Check whether we can reference this property. 2365 if (DiagnoseUseOfDecl(PD, MemberLoc)) 2366 return ExprError(); 2367 QualType ResTy = PD->getType(); 2368 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 2369 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel); 2370 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc)) 2371 ResTy = Getter->getResultType(); 2372 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy, 2373 MemberLoc, BaseExpr)); 2374 } 2375 // Check protocols on qualified interfaces. 2376 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), 2377 E = OPT->qual_end(); I != E; ++I) 2378 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) { 2379 // Check whether we can reference this property. 2380 if (DiagnoseUseOfDecl(PD, MemberLoc)) 2381 return ExprError(); 2382 2383 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(), 2384 MemberLoc, BaseExpr)); 2385 } 2386 // If that failed, look for an "implicit" property by seeing if the nullary 2387 // selector is implemented. 2388 2389 // FIXME: The logic for looking up nullary and unary selectors should be 2390 // shared with the code in ActOnInstanceMessage. 2391 2392 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 2393 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel); 2394 2395 // If this reference is in an @implementation, check for 'private' methods. 2396 if (!Getter) 2397 Getter = IFace->lookupPrivateInstanceMethod(Sel); 2398 2399 // Look through local category implementations associated with the class. 2400 if (!Getter) 2401 Getter = IFace->getCategoryInstanceMethod(Sel); 2402 if (Getter) { 2403 // Check if we can reference this property. 2404 if (DiagnoseUseOfDecl(Getter, MemberLoc)) 2405 return ExprError(); 2406 } 2407 // If we found a getter then this may be a valid dot-reference, we 2408 // will look for the matching setter, in case it is needed. 2409 Selector SetterSel = 2410 SelectorTable::constructSetterName(PP.getIdentifierTable(), 2411 PP.getSelectorTable(), Member); 2412 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel); 2413 if (!Setter) { 2414 // If this reference is in an @implementation, also check for 'private' 2415 // methods. 2416 Setter = IFace->lookupPrivateInstanceMethod(SetterSel); 2417 } 2418 // Look through local category implementations associated with the class. 2419 if (!Setter) 2420 Setter = IFace->getCategoryInstanceMethod(SetterSel); 2421 2422 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) 2423 return ExprError(); 2424 2425 if (Getter || Setter) { 2426 QualType PType; 2427 2428 if (Getter) 2429 PType = Getter->getResultType(); 2430 else 2431 // Get the expression type from Setter's incoming parameter. 2432 PType = (*(Setter->param_end() -1))->getType(); 2433 // FIXME: we must check that the setter has property type. 2434 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType, 2435 Setter, MemberLoc, BaseExpr)); 2436 } 2437 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 2438 << MemberName << BaseType); 2439 } 2440 2441 // Handle the following exceptional case (*Obj).isa. 2442 if (OpKind == tok::period && 2443 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) && 2444 MemberName.getAsIdentifierInfo()->isStr("isa")) 2445 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc, 2446 Context.getObjCIdType())); 2447 2448 // Handle 'field access' to vectors, such as 'V.xx'. 2449 if (BaseType->isExtVectorType()) { 2450 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 2451 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc); 2452 if (ret.isNull()) 2453 return ExprError(); 2454 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member, 2455 MemberLoc)); 2456 } 2457 2458 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union) 2459 << BaseType << BaseExpr->getSourceRange(); 2460 2461 return ExprError(); 2462} 2463 2464Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg Base, 2465 SourceLocation OpLoc, 2466 tok::TokenKind OpKind, 2467 const CXXScopeSpec &SS, 2468 UnqualifiedId &Member, 2469 DeclPtrTy ObjCImpDecl, 2470 bool HasTrailingLParen) { 2471 if (Member.getKind() == UnqualifiedId::IK_TemplateId) { 2472 TemplateName Template 2473 = TemplateName::getFromVoidPointer(Member.TemplateId->Template); 2474 2475 // FIXME: We're going to end up looking up the template based on its name, 2476 // twice! 2477 DeclarationName Name; 2478 if (TemplateDecl *ActualTemplate = Template.getAsTemplateDecl()) 2479 Name = ActualTemplate->getDeclName(); 2480 else if (OverloadedFunctionDecl *Ovl = Template.getAsOverloadedFunctionDecl()) 2481 Name = Ovl->getDeclName(); 2482 else { 2483 DependentTemplateName *DTN = Template.getAsDependentTemplateName(); 2484 if (DTN->isIdentifier()) 2485 Name = DTN->getIdentifier(); 2486 else 2487 Name = Context.DeclarationNames.getCXXOperatorName(DTN->getOperator()); 2488 } 2489 2490 // Translate the parser's template argument list in our AST format. 2491 ASTTemplateArgsPtr TemplateArgsPtr(*this, 2492 Member.TemplateId->getTemplateArgs(), 2493 Member.TemplateId->NumArgs); 2494 2495 TemplateArgumentListInfo TemplateArgs; 2496 TemplateArgs.setLAngleLoc(Member.TemplateId->LAngleLoc); 2497 TemplateArgs.setRAngleLoc(Member.TemplateId->RAngleLoc); 2498 translateTemplateArguments(TemplateArgsPtr, TemplateArgs); 2499 TemplateArgsPtr.release(); 2500 2501 // Do we have the save the actual template name? We might need it... 2502 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, 2503 Member.TemplateId->TemplateNameLoc, 2504 Name, &TemplateArgs, DeclPtrTy(), 2505 &SS); 2506 } 2507 2508 // FIXME: We lose a lot of source information by mapping directly to the 2509 // DeclarationName. 2510 OwningExprResult Result 2511 = BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, 2512 Member.getSourceRange().getBegin(), 2513 GetNameFromUnqualifiedId(Member), 2514 ObjCImpDecl, &SS); 2515 2516 if (Result.isInvalid() || HasTrailingLParen || 2517 Member.getKind() != UnqualifiedId::IK_DestructorName) 2518 return move(Result); 2519 2520 // The only way a reference to a destructor can be used is to 2521 // immediately call them. Since the next token is not a '(', produce a 2522 // diagnostic and build the call now. 2523 Expr *E = (Expr *)Result.get(); 2524 SourceLocation ExpectedLParenLoc 2525 = PP.getLocForEndOfToken(Member.getSourceRange().getEnd()); 2526 Diag(E->getLocStart(), diag::err_dtor_expr_without_call) 2527 << isa<CXXPseudoDestructorExpr>(E) 2528 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()"); 2529 2530 return ActOnCallExpr(0, move(Result), ExpectedLParenLoc, 2531 MultiExprArg(*this, 0, 0), 0, ExpectedLParenLoc); 2532} 2533 2534Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 2535 FunctionDecl *FD, 2536 ParmVarDecl *Param) { 2537 if (Param->hasUnparsedDefaultArg()) { 2538 Diag (CallLoc, 2539 diag::err_use_of_default_argument_to_function_declared_later) << 2540 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 2541 Diag(UnparsedDefaultArgLocs[Param], 2542 diag::note_default_argument_declared_here); 2543 } else { 2544 if (Param->hasUninstantiatedDefaultArg()) { 2545 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 2546 2547 // Instantiate the expression. 2548 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD); 2549 2550 InstantiatingTemplate Inst(*this, CallLoc, Param, 2551 ArgList.getInnermost().getFlatArgumentList(), 2552 ArgList.getInnermost().flat_size()); 2553 2554 OwningExprResult Result = SubstExpr(UninstExpr, ArgList); 2555 if (Result.isInvalid()) 2556 return ExprError(); 2557 2558 if (SetParamDefaultArgument(Param, move(Result), 2559 /*FIXME:EqualLoc*/ 2560 UninstExpr->getSourceRange().getBegin())) 2561 return ExprError(); 2562 } 2563 2564 Expr *DefaultExpr = Param->getDefaultArg(); 2565 2566 // If the default expression creates temporaries, we need to 2567 // push them to the current stack of expression temporaries so they'll 2568 // be properly destroyed. 2569 if (CXXExprWithTemporaries *E 2570 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) { 2571 assert(!E->shouldDestroyTemporaries() && 2572 "Can't destroy temporaries in a default argument expr!"); 2573 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I) 2574 ExprTemporaries.push_back(E->getTemporary(I)); 2575 } 2576 } 2577 2578 // We already type-checked the argument, so we know it works. 2579 return Owned(CXXDefaultArgExpr::Create(Context, Param)); 2580} 2581 2582/// ConvertArgumentsForCall - Converts the arguments specified in 2583/// Args/NumArgs to the parameter types of the function FDecl with 2584/// function prototype Proto. Call is the call expression itself, and 2585/// Fn is the function expression. For a C++ member function, this 2586/// routine does not attempt to convert the object argument. Returns 2587/// true if the call is ill-formed. 2588bool 2589Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 2590 FunctionDecl *FDecl, 2591 const FunctionProtoType *Proto, 2592 Expr **Args, unsigned NumArgs, 2593 SourceLocation RParenLoc) { 2594 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 2595 // assignment, to the types of the corresponding parameter, ... 2596 unsigned NumArgsInProto = Proto->getNumArgs(); 2597 bool Invalid = false; 2598 2599 // If too few arguments are available (and we don't have default 2600 // arguments for the remaining parameters), don't make the call. 2601 if (NumArgs < NumArgsInProto) { 2602 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) 2603 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args) 2604 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange(); 2605 Call->setNumArgs(Context, NumArgsInProto); 2606 } 2607 2608 // If too many are passed and not variadic, error on the extras and drop 2609 // them. 2610 if (NumArgs > NumArgsInProto) { 2611 if (!Proto->isVariadic()) { 2612 Diag(Args[NumArgsInProto]->getLocStart(), 2613 diag::err_typecheck_call_too_many_args) 2614 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange() 2615 << SourceRange(Args[NumArgsInProto]->getLocStart(), 2616 Args[NumArgs-1]->getLocEnd()); 2617 // This deletes the extra arguments. 2618 Call->setNumArgs(Context, NumArgsInProto); 2619 return true; 2620 } 2621 } 2622 llvm::SmallVector<Expr *, 8> AllArgs; 2623 VariadicCallType CallType = 2624 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply; 2625 if (Fn->getType()->isBlockPointerType()) 2626 CallType = VariadicBlock; // Block 2627 else if (isa<MemberExpr>(Fn)) 2628 CallType = VariadicMethod; 2629 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl, 2630 Proto, 0, Args, NumArgs, AllArgs, CallType); 2631 if (Invalid) 2632 return true; 2633 unsigned TotalNumArgs = AllArgs.size(); 2634 for (unsigned i = 0; i < TotalNumArgs; ++i) 2635 Call->setArg(i, AllArgs[i]); 2636 2637 return false; 2638} 2639 2640bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, 2641 FunctionDecl *FDecl, 2642 const FunctionProtoType *Proto, 2643 unsigned FirstProtoArg, 2644 Expr **Args, unsigned NumArgs, 2645 llvm::SmallVector<Expr *, 8> &AllArgs, 2646 VariadicCallType CallType) { 2647 unsigned NumArgsInProto = Proto->getNumArgs(); 2648 unsigned NumArgsToCheck = NumArgs; 2649 bool Invalid = false; 2650 if (NumArgs != NumArgsInProto) 2651 // Use default arguments for missing arguments 2652 NumArgsToCheck = NumArgsInProto; 2653 unsigned ArgIx = 0; 2654 // Continue to check argument types (even if we have too few/many args). 2655 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) { 2656 QualType ProtoArgType = Proto->getArgType(i); 2657 2658 Expr *Arg; 2659 if (ArgIx < NumArgs) { 2660 Arg = Args[ArgIx++]; 2661 2662 if (RequireCompleteType(Arg->getSourceRange().getBegin(), 2663 ProtoArgType, 2664 PDiag(diag::err_call_incomplete_argument) 2665 << Arg->getSourceRange())) 2666 return true; 2667 2668 // Pass the argument. 2669 if (PerformCopyInitialization(Arg, ProtoArgType, "passing")) 2670 return true; 2671 2672 if (!ProtoArgType->isReferenceType()) 2673 Arg = MaybeBindToTemporary(Arg).takeAs<Expr>(); 2674 } else { 2675 ParmVarDecl *Param = FDecl->getParamDecl(i); 2676 2677 OwningExprResult ArgExpr = 2678 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 2679 if (ArgExpr.isInvalid()) 2680 return true; 2681 2682 Arg = ArgExpr.takeAs<Expr>(); 2683 } 2684 AllArgs.push_back(Arg); 2685 } 2686 2687 // If this is a variadic call, handle args passed through "...". 2688 if (CallType != VariadicDoesNotApply) { 2689 // Promote the arguments (C99 6.5.2.2p7). 2690 for (unsigned i = ArgIx; i < NumArgs; i++) { 2691 Expr *Arg = Args[i]; 2692 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType); 2693 AllArgs.push_back(Arg); 2694 } 2695 } 2696 return Invalid; 2697} 2698 2699/// \brief "Deconstruct" the function argument of a call expression to find 2700/// the underlying declaration (if any), the name of the called function, 2701/// whether argument-dependent lookup is available, whether it has explicit 2702/// template arguments, etc. 2703void Sema::DeconstructCallFunction(Expr *FnExpr, 2704 llvm::SmallVectorImpl<NamedDecl*> &Fns, 2705 DeclarationName &Name, 2706 NestedNameSpecifier *&Qualifier, 2707 SourceRange &QualifierRange, 2708 bool &ArgumentDependentLookup, 2709 bool &Overloaded, 2710 bool &HasExplicitTemplateArguments, 2711 TemplateArgumentListInfo &ExplicitTemplateArgs) { 2712 // Set defaults for all of the output parameters. 2713 Name = DeclarationName(); 2714 Qualifier = 0; 2715 QualifierRange = SourceRange(); 2716 ArgumentDependentLookup = false; 2717 Overloaded = false; 2718 HasExplicitTemplateArguments = false; 2719 2720 // If we're directly calling a function, get the appropriate declaration. 2721 // Also, in C++, keep track of whether we should perform argument-dependent 2722 // lookup and whether there were any explicitly-specified template arguments. 2723 while (true) { 2724 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr)) 2725 FnExpr = IcExpr->getSubExpr(); 2726 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) { 2727 FnExpr = PExpr->getSubExpr(); 2728 } else if (isa<UnaryOperator>(FnExpr) && 2729 cast<UnaryOperator>(FnExpr)->getOpcode() 2730 == UnaryOperator::AddrOf) { 2731 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr(); 2732 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) { 2733 Fns.push_back(cast<NamedDecl>(DRExpr->getDecl())); 2734 ArgumentDependentLookup = false; 2735 if ((Qualifier = DRExpr->getQualifier())) 2736 QualifierRange = DRExpr->getQualifierRange(); 2737 break; 2738 } else if (UnresolvedLookupExpr *UnresLookup 2739 = dyn_cast<UnresolvedLookupExpr>(FnExpr)) { 2740 Name = UnresLookup->getName(); 2741 Fns.append(UnresLookup->decls_begin(), UnresLookup->decls_end()); 2742 ArgumentDependentLookup = UnresLookup->requiresADL(); 2743 Overloaded = UnresLookup->isOverloaded(); 2744 if ((Qualifier = UnresLookup->getQualifier())) 2745 QualifierRange = UnresLookup->getQualifierRange(); 2746 if (UnresLookup->hasExplicitTemplateArgs()) { 2747 HasExplicitTemplateArguments = true; 2748 UnresLookup->copyTemplateArgumentsInto(ExplicitTemplateArgs); 2749 } 2750 break; 2751 } else { 2752 break; 2753 } 2754 } 2755} 2756 2757/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 2758/// This provides the location of the left/right parens and a list of comma 2759/// locations. 2760Action::OwningExprResult 2761Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc, 2762 MultiExprArg args, 2763 SourceLocation *CommaLocs, SourceLocation RParenLoc) { 2764 unsigned NumArgs = args.size(); 2765 2766 // Since this might be a postfix expression, get rid of ParenListExprs. 2767 fn = MaybeConvertParenListExprToParenExpr(S, move(fn)); 2768 2769 Expr *Fn = fn.takeAs<Expr>(); 2770 Expr **Args = reinterpret_cast<Expr**>(args.release()); 2771 assert(Fn && "no function call expression"); 2772 2773 if (getLangOptions().CPlusPlus) { 2774 // If this is a pseudo-destructor expression, build the call immediately. 2775 if (isa<CXXPseudoDestructorExpr>(Fn)) { 2776 if (NumArgs > 0) { 2777 // Pseudo-destructor calls should not have any arguments. 2778 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 2779 << CodeModificationHint::CreateRemoval( 2780 SourceRange(Args[0]->getLocStart(), 2781 Args[NumArgs-1]->getLocEnd())); 2782 2783 for (unsigned I = 0; I != NumArgs; ++I) 2784 Args[I]->Destroy(Context); 2785 2786 NumArgs = 0; 2787 } 2788 2789 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy, 2790 RParenLoc)); 2791 } 2792 2793 // Determine whether this is a dependent call inside a C++ template, 2794 // in which case we won't do any semantic analysis now. 2795 // FIXME: Will need to cache the results of name lookup (including ADL) in 2796 // Fn. 2797 bool Dependent = false; 2798 if (Fn->isTypeDependent()) 2799 Dependent = true; 2800 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs)) 2801 Dependent = true; 2802 2803 if (Dependent) 2804 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs, 2805 Context.DependentTy, RParenLoc)); 2806 2807 // Determine whether this is a call to an object (C++ [over.call.object]). 2808 if (Fn->getType()->isRecordType()) 2809 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs, 2810 CommaLocs, RParenLoc)); 2811 2812 // Determine whether this is a call to a member function. 2813 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) { 2814 NamedDecl *MemDecl = MemExpr->getMemberDecl(); 2815 if (isa<OverloadedFunctionDecl>(MemDecl) || 2816 isa<CXXMethodDecl>(MemDecl) || 2817 (isa<FunctionTemplateDecl>(MemDecl) && 2818 isa<CXXMethodDecl>( 2819 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl()))) 2820 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs, 2821 CommaLocs, RParenLoc)); 2822 } 2823 2824 // Determine whether this is a call to a pointer-to-member function. 2825 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Fn->IgnoreParens())) { 2826 if (BO->getOpcode() == BinaryOperator::PtrMemD || 2827 BO->getOpcode() == BinaryOperator::PtrMemI) { 2828 if (const FunctionProtoType *FPT = 2829 dyn_cast<FunctionProtoType>(BO->getType())) { 2830 QualType ResultTy = FPT->getResultType().getNonReferenceType(); 2831 2832 ExprOwningPtr<CXXMemberCallExpr> 2833 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args, 2834 NumArgs, ResultTy, 2835 RParenLoc)); 2836 2837 if (CheckCallReturnType(FPT->getResultType(), 2838 BO->getRHS()->getSourceRange().getBegin(), 2839 TheCall.get(), 0)) 2840 return ExprError(); 2841 2842 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs, 2843 RParenLoc)) 2844 return ExprError(); 2845 2846 return Owned(MaybeBindToTemporary(TheCall.release()).release()); 2847 } 2848 return ExprError(Diag(Fn->getLocStart(), 2849 diag::err_typecheck_call_not_function) 2850 << Fn->getType() << Fn->getSourceRange()); 2851 } 2852 } 2853 } 2854 2855 // If we're directly calling a function, get the appropriate declaration. 2856 // Also, in C++, keep track of whether we should perform argument-dependent 2857 // lookup and whether there were any explicitly-specified template arguments. 2858 llvm::SmallVector<NamedDecl*,8> Fns; 2859 DeclarationName UnqualifiedName; 2860 bool Overloaded; 2861 bool ADL; 2862 bool HasExplicitTemplateArgs = 0; 2863 TemplateArgumentListInfo ExplicitTemplateArgs; 2864 NestedNameSpecifier *Qualifier = 0; 2865 SourceRange QualifierRange; 2866 DeconstructCallFunction(Fn, Fns, UnqualifiedName, Qualifier, QualifierRange, 2867 ADL, Overloaded, HasExplicitTemplateArgs, 2868 ExplicitTemplateArgs); 2869 2870 NamedDecl *NDecl; // the specific declaration we're calling, if applicable 2871 FunctionDecl *FDecl; // same, if it's known to be a function 2872 2873 if (Overloaded || ADL) { 2874#ifndef NDEBUG 2875 if (ADL) { 2876 // To do ADL, we must have found an unqualified name. 2877 assert(UnqualifiedName && "found no unqualified name for ADL"); 2878 2879 // We don't perform ADL for implicit declarations of builtins. 2880 // Verify that this was correctly set up. 2881 if (Fns.size() == 1 && (FDecl = dyn_cast<FunctionDecl>(Fns[0])) && 2882 FDecl->getBuiltinID() && FDecl->isImplicit()) 2883 assert(0 && "performing ADL for builtin"); 2884 2885 // We don't perform ADL in C. 2886 assert(getLangOptions().CPlusPlus && "ADL enabled in C"); 2887 } 2888 2889 if (Overloaded) { 2890 // To be overloaded, we must either have multiple functions or 2891 // at least one function template (which is effectively an 2892 // infinite set of functions). 2893 assert((Fns.size() > 1 || 2894 (Fns.size() == 1 && 2895 isa<FunctionTemplateDecl>(Fns[0]->getUnderlyingDecl()))) 2896 && "unrecognized overload situation"); 2897 } 2898#endif 2899 2900 FDecl = ResolveOverloadedCallFn(Fn, Fns, UnqualifiedName, 2901 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0), 2902 LParenLoc, Args, NumArgs, CommaLocs, 2903 RParenLoc, ADL); 2904 if (!FDecl) 2905 return ExprError(); 2906 2907 Fn = FixOverloadedFunctionReference(Fn, FDecl); 2908 2909 NDecl = FDecl; 2910 } else { 2911 assert(Fns.size() <= 1 && "overloaded without Overloaded flag"); 2912 if (Fns.empty()) 2913 NDecl = FDecl = 0; 2914 else { 2915 NDecl = Fns[0]; 2916 FDecl = dyn_cast<FunctionDecl>(NDecl); 2917 } 2918 } 2919 2920 // Promote the function operand. 2921 UsualUnaryConversions(Fn); 2922 2923 // Make the call expr early, before semantic checks. This guarantees cleanup 2924 // of arguments and function on error. 2925 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn, 2926 Args, NumArgs, 2927 Context.BoolTy, 2928 RParenLoc)); 2929 2930 const FunctionType *FuncT; 2931 if (!Fn->getType()->isBlockPointerType()) { 2932 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 2933 // have type pointer to function". 2934 const PointerType *PT = Fn->getType()->getAs<PointerType>(); 2935 if (PT == 0) 2936 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 2937 << Fn->getType() << Fn->getSourceRange()); 2938 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 2939 } else { // This is a block call. 2940 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()-> 2941 getAs<FunctionType>(); 2942 } 2943 if (FuncT == 0) 2944 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 2945 << Fn->getType() << Fn->getSourceRange()); 2946 2947 // Check for a valid return type 2948 if (CheckCallReturnType(FuncT->getResultType(), 2949 Fn->getSourceRange().getBegin(), TheCall.get(), 2950 FDecl)) 2951 return ExprError(); 2952 2953 // We know the result type of the call, set it. 2954 TheCall->setType(FuncT->getResultType().getNonReferenceType()); 2955 2956 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) { 2957 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs, 2958 RParenLoc)) 2959 return ExprError(); 2960 } else { 2961 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 2962 2963 if (FDecl) { 2964 // Check if we have too few/too many template arguments, based 2965 // on our knowledge of the function definition. 2966 const FunctionDecl *Def = 0; 2967 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) { 2968 const FunctionProtoType *Proto = 2969 Def->getType()->getAs<FunctionProtoType>(); 2970 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) { 2971 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 2972 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange(); 2973 } 2974 } 2975 } 2976 2977 // Promote the arguments (C99 6.5.2.2p6). 2978 for (unsigned i = 0; i != NumArgs; i++) { 2979 Expr *Arg = Args[i]; 2980 DefaultArgumentPromotion(Arg); 2981 if (RequireCompleteType(Arg->getSourceRange().getBegin(), 2982 Arg->getType(), 2983 PDiag(diag::err_call_incomplete_argument) 2984 << Arg->getSourceRange())) 2985 return ExprError(); 2986 TheCall->setArg(i, Arg); 2987 } 2988 } 2989 2990 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 2991 if (!Method->isStatic()) 2992 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 2993 << Fn->getSourceRange()); 2994 2995 // Check for sentinels 2996 if (NDecl) 2997 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs); 2998 2999 // Do special checking on direct calls to functions. 3000 if (FDecl) { 3001 if (CheckFunctionCall(FDecl, TheCall.get())) 3002 return ExprError(); 3003 3004 if (unsigned BuiltinID = FDecl->getBuiltinID()) 3005 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take()); 3006 } else if (NDecl) { 3007 if (CheckBlockCall(NDecl, TheCall.get())) 3008 return ExprError(); 3009 } 3010 3011 return MaybeBindToTemporary(TheCall.take()); 3012} 3013 3014Action::OwningExprResult 3015Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty, 3016 SourceLocation RParenLoc, ExprArg InitExpr) { 3017 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type"); 3018 //FIXME: Preserve type source info. 3019 QualType literalType = GetTypeFromParser(Ty); 3020 // FIXME: put back this assert when initializers are worked out. 3021 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 3022 Expr *literalExpr = static_cast<Expr*>(InitExpr.get()); 3023 3024 if (literalType->isArrayType()) { 3025 if (literalType->isVariableArrayType()) 3026 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 3027 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())); 3028 } else if (!literalType->isDependentType() && 3029 RequireCompleteType(LParenLoc, literalType, 3030 PDiag(diag::err_typecheck_decl_incomplete_type) 3031 << SourceRange(LParenLoc, 3032 literalExpr->getSourceRange().getEnd()))) 3033 return ExprError(); 3034 3035 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc, 3036 DeclarationName(), /*FIXME:DirectInit=*/false)) 3037 return ExprError(); 3038 3039 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 3040 if (isFileScope) { // 6.5.2.5p3 3041 if (CheckForConstantInitializer(literalExpr, literalType)) 3042 return ExprError(); 3043 } 3044 InitExpr.release(); 3045 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType, 3046 literalExpr, isFileScope)); 3047} 3048 3049Action::OwningExprResult 3050Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist, 3051 SourceLocation RBraceLoc) { 3052 unsigned NumInit = initlist.size(); 3053 Expr **InitList = reinterpret_cast<Expr**>(initlist.release()); 3054 3055 // Semantic analysis for initializers is done by ActOnDeclarator() and 3056 // CheckInitializer() - it requires knowledge of the object being intialized. 3057 3058 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit, 3059 RBraceLoc); 3060 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 3061 return Owned(E); 3062} 3063 3064static CastExpr::CastKind getScalarCastKind(ASTContext &Context, 3065 QualType SrcTy, QualType DestTy) { 3066 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 3067 return CastExpr::CK_NoOp; 3068 3069 if (SrcTy->hasPointerRepresentation()) { 3070 if (DestTy->hasPointerRepresentation()) 3071 return CastExpr::CK_BitCast; 3072 if (DestTy->isIntegerType()) 3073 return CastExpr::CK_PointerToIntegral; 3074 } 3075 3076 if (SrcTy->isIntegerType()) { 3077 if (DestTy->isIntegerType()) 3078 return CastExpr::CK_IntegralCast; 3079 if (DestTy->hasPointerRepresentation()) 3080 return CastExpr::CK_IntegralToPointer; 3081 if (DestTy->isRealFloatingType()) 3082 return CastExpr::CK_IntegralToFloating; 3083 } 3084 3085 if (SrcTy->isRealFloatingType()) { 3086 if (DestTy->isRealFloatingType()) 3087 return CastExpr::CK_FloatingCast; 3088 if (DestTy->isIntegerType()) 3089 return CastExpr::CK_FloatingToIntegral; 3090 } 3091 3092 // FIXME: Assert here. 3093 // assert(false && "Unhandled cast combination!"); 3094 return CastExpr::CK_Unknown; 3095} 3096 3097/// CheckCastTypes - Check type constraints for casting between types. 3098bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr, 3099 CastExpr::CastKind& Kind, 3100 CXXMethodDecl *& ConversionDecl, 3101 bool FunctionalStyle) { 3102 if (getLangOptions().CPlusPlus) 3103 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle, 3104 ConversionDecl); 3105 3106 DefaultFunctionArrayConversion(castExpr); 3107 3108 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression 3109 // type needs to be scalar. 3110 if (castType->isVoidType()) { 3111 // Cast to void allows any expr type. 3112 Kind = CastExpr::CK_ToVoid; 3113 return false; 3114 } 3115 3116 if (!castType->isScalarType() && !castType->isVectorType()) { 3117 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) && 3118 (castType->isStructureType() || castType->isUnionType())) { 3119 // GCC struct/union extension: allow cast to self. 3120 // FIXME: Check that the cast destination type is complete. 3121 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar) 3122 << castType << castExpr->getSourceRange(); 3123 Kind = CastExpr::CK_NoOp; 3124 return false; 3125 } 3126 3127 if (castType->isUnionType()) { 3128 // GCC cast to union extension 3129 RecordDecl *RD = castType->getAs<RecordType>()->getDecl(); 3130 RecordDecl::field_iterator Field, FieldEnd; 3131 for (Field = RD->field_begin(), FieldEnd = RD->field_end(); 3132 Field != FieldEnd; ++Field) { 3133 if (Context.hasSameUnqualifiedType(Field->getType(), 3134 castExpr->getType())) { 3135 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union) 3136 << castExpr->getSourceRange(); 3137 break; 3138 } 3139 } 3140 if (Field == FieldEnd) 3141 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type) 3142 << castExpr->getType() << castExpr->getSourceRange(); 3143 Kind = CastExpr::CK_ToUnion; 3144 return false; 3145 } 3146 3147 // Reject any other conversions to non-scalar types. 3148 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar) 3149 << castType << castExpr->getSourceRange(); 3150 } 3151 3152 if (!castExpr->getType()->isScalarType() && 3153 !castExpr->getType()->isVectorType()) { 3154 return Diag(castExpr->getLocStart(), 3155 diag::err_typecheck_expect_scalar_operand) 3156 << castExpr->getType() << castExpr->getSourceRange(); 3157 } 3158 3159 if (castType->isExtVectorType()) 3160 return CheckExtVectorCast(TyR, castType, castExpr, Kind); 3161 3162 if (castType->isVectorType()) 3163 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind); 3164 if (castExpr->getType()->isVectorType()) 3165 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind); 3166 3167 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) 3168 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR; 3169 3170 if (isa<ObjCSelectorExpr>(castExpr)) 3171 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr); 3172 3173 if (!castType->isArithmeticType()) { 3174 QualType castExprType = castExpr->getType(); 3175 if (!castExprType->isIntegralType() && castExprType->isArithmeticType()) 3176 return Diag(castExpr->getLocStart(), 3177 diag::err_cast_pointer_from_non_pointer_int) 3178 << castExprType << castExpr->getSourceRange(); 3179 } else if (!castExpr->getType()->isArithmeticType()) { 3180 if (!castType->isIntegralType() && castType->isArithmeticType()) 3181 return Diag(castExpr->getLocStart(), 3182 diag::err_cast_pointer_to_non_pointer_int) 3183 << castType << castExpr->getSourceRange(); 3184 } 3185 3186 Kind = getScalarCastKind(Context, castExpr->getType(), castType); 3187 return false; 3188} 3189 3190bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 3191 CastExpr::CastKind &Kind) { 3192 assert(VectorTy->isVectorType() && "Not a vector type!"); 3193 3194 if (Ty->isVectorType() || Ty->isIntegerType()) { 3195 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 3196 return Diag(R.getBegin(), 3197 Ty->isVectorType() ? 3198 diag::err_invalid_conversion_between_vectors : 3199 diag::err_invalid_conversion_between_vector_and_integer) 3200 << VectorTy << Ty << R; 3201 } else 3202 return Diag(R.getBegin(), 3203 diag::err_invalid_conversion_between_vector_and_scalar) 3204 << VectorTy << Ty << R; 3205 3206 Kind = CastExpr::CK_BitCast; 3207 return false; 3208} 3209 3210bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr, 3211 CastExpr::CastKind &Kind) { 3212 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 3213 3214 QualType SrcTy = CastExpr->getType(); 3215 3216 // If SrcTy is a VectorType, the total size must match to explicitly cast to 3217 // an ExtVectorType. 3218 if (SrcTy->isVectorType()) { 3219 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 3220 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 3221 << DestTy << SrcTy << R; 3222 Kind = CastExpr::CK_BitCast; 3223 return false; 3224 } 3225 3226 // All non-pointer scalars can be cast to ExtVector type. The appropriate 3227 // conversion will take place first from scalar to elt type, and then 3228 // splat from elt type to vector. 3229 if (SrcTy->isPointerType()) 3230 return Diag(R.getBegin(), 3231 diag::err_invalid_conversion_between_vector_and_scalar) 3232 << DestTy << SrcTy << R; 3233 3234 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 3235 ImpCastExprToType(CastExpr, DestElemTy, 3236 getScalarCastKind(Context, SrcTy, DestElemTy)); 3237 3238 Kind = CastExpr::CK_VectorSplat; 3239 return false; 3240} 3241 3242Action::OwningExprResult 3243Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty, 3244 SourceLocation RParenLoc, ExprArg Op) { 3245 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 3246 3247 assert((Ty != 0) && (Op.get() != 0) && 3248 "ActOnCastExpr(): missing type or expr"); 3249 3250 Expr *castExpr = (Expr *)Op.get(); 3251 //FIXME: Preserve type source info. 3252 QualType castType = GetTypeFromParser(Ty); 3253 3254 // If the Expr being casted is a ParenListExpr, handle it specially. 3255 if (isa<ParenListExpr>(castExpr)) 3256 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType); 3257 CXXMethodDecl *Method = 0; 3258 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr, 3259 Kind, Method)) 3260 return ExprError(); 3261 3262 if (Method) { 3263 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind, 3264 Method, move(Op)); 3265 3266 if (CastArg.isInvalid()) 3267 return ExprError(); 3268 3269 castExpr = CastArg.takeAs<Expr>(); 3270 } else { 3271 Op.release(); 3272 } 3273 3274 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(), 3275 Kind, castExpr, castType, 3276 LParenLoc, RParenLoc)); 3277} 3278 3279/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence 3280/// of comma binary operators. 3281Action::OwningExprResult 3282Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) { 3283 Expr *expr = EA.takeAs<Expr>(); 3284 ParenListExpr *E = dyn_cast<ParenListExpr>(expr); 3285 if (!E) 3286 return Owned(expr); 3287 3288 OwningExprResult Result(*this, E->getExpr(0)); 3289 3290 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 3291 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result), 3292 Owned(E->getExpr(i))); 3293 3294 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result)); 3295} 3296 3297Action::OwningExprResult 3298Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc, 3299 SourceLocation RParenLoc, ExprArg Op, 3300 QualType Ty) { 3301 ParenListExpr *PE = (ParenListExpr *)Op.get(); 3302 3303 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')' 3304 // then handle it as such. 3305 if (getLangOptions().AltiVec && Ty->isVectorType()) { 3306 if (PE->getNumExprs() == 0) { 3307 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer); 3308 return ExprError(); 3309 } 3310 3311 llvm::SmallVector<Expr *, 8> initExprs; 3312 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i) 3313 initExprs.push_back(PE->getExpr(i)); 3314 3315 // FIXME: This means that pretty-printing the final AST will produce curly 3316 // braces instead of the original commas. 3317 Op.release(); 3318 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0], 3319 initExprs.size(), RParenLoc); 3320 E->setType(Ty); 3321 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc, 3322 Owned(E)); 3323 } else { 3324 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 3325 // sequence of BinOp comma operators. 3326 Op = MaybeConvertParenListExprToParenExpr(S, move(Op)); 3327 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op)); 3328 } 3329} 3330 3331Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L, 3332 SourceLocation R, 3333 MultiExprArg Val) { 3334 unsigned nexprs = Val.size(); 3335 Expr **exprs = reinterpret_cast<Expr**>(Val.release()); 3336 assert((exprs != 0) && "ActOnParenListExpr() missing expr list"); 3337 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R); 3338 return Owned(expr); 3339} 3340 3341/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension. 3342/// In that case, lhs = cond. 3343/// C99 6.5.15 3344QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS, 3345 SourceLocation QuestionLoc) { 3346 // C++ is sufficiently different to merit its own checker. 3347 if (getLangOptions().CPlusPlus) 3348 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc); 3349 3350 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional); 3351 3352 UsualUnaryConversions(Cond); 3353 UsualUnaryConversions(LHS); 3354 UsualUnaryConversions(RHS); 3355 QualType CondTy = Cond->getType(); 3356 QualType LHSTy = LHS->getType(); 3357 QualType RHSTy = RHS->getType(); 3358 3359 // first, check the condition. 3360 if (!CondTy->isScalarType()) { // C99 6.5.15p2 3361 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) 3362 << CondTy; 3363 return QualType(); 3364 } 3365 3366 // Now check the two expressions. 3367 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 3368 return CheckVectorOperands(QuestionLoc, LHS, RHS); 3369 3370 // If both operands have arithmetic type, do the usual arithmetic conversions 3371 // to find a common type: C99 6.5.15p3,5. 3372 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 3373 UsualArithmeticConversions(LHS, RHS); 3374 return LHS->getType(); 3375 } 3376 3377 // If both operands are the same structure or union type, the result is that 3378 // type. 3379 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 3380 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 3381 if (LHSRT->getDecl() == RHSRT->getDecl()) 3382 // "If both the operands have structure or union type, the result has 3383 // that type." This implies that CV qualifiers are dropped. 3384 return LHSTy.getUnqualifiedType(); 3385 // FIXME: Type of conditional expression must be complete in C mode. 3386 } 3387 3388 // C99 6.5.15p5: "If both operands have void type, the result has void type." 3389 // The following || allows only one side to be void (a GCC-ism). 3390 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 3391 if (!LHSTy->isVoidType()) 3392 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void) 3393 << RHS->getSourceRange(); 3394 if (!RHSTy->isVoidType()) 3395 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void) 3396 << LHS->getSourceRange(); 3397 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid); 3398 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid); 3399 return Context.VoidTy; 3400 } 3401 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 3402 // the type of the other operand." 3403 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) && 3404 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 3405 // promote the null to a pointer. 3406 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown); 3407 return LHSTy; 3408 } 3409 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) && 3410 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 3411 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown); 3412 return RHSTy; 3413 } 3414 // Handle things like Class and struct objc_class*. Here we case the result 3415 // to the pseudo-builtin, because that will be implicitly cast back to the 3416 // redefinition type if an attempt is made to access its fields. 3417 if (LHSTy->isObjCClassType() && 3418 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) { 3419 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast); 3420 return LHSTy; 3421 } 3422 if (RHSTy->isObjCClassType() && 3423 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) { 3424 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast); 3425 return RHSTy; 3426 } 3427 // And the same for struct objc_object* / id 3428 if (LHSTy->isObjCIdType() && 3429 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) { 3430 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast); 3431 return LHSTy; 3432 } 3433 if (RHSTy->isObjCIdType() && 3434 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) { 3435 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast); 3436 return RHSTy; 3437 } 3438 // Handle block pointer types. 3439 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 3440 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 3441 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 3442 QualType destType = Context.getPointerType(Context.VoidTy); 3443 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast); 3444 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast); 3445 return destType; 3446 } 3447 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 3448 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 3449 return QualType(); 3450 } 3451 // We have 2 block pointer types. 3452 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 3453 // Two identical block pointer types are always compatible. 3454 return LHSTy; 3455 } 3456 // The block pointer types aren't identical, continue checking. 3457 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType(); 3458 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType(); 3459 3460 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 3461 rhptee.getUnqualifiedType())) { 3462 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers) 3463 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 3464 // In this situation, we assume void* type. No especially good 3465 // reason, but this is what gcc does, and we do have to pick 3466 // to get a consistent AST. 3467 QualType incompatTy = Context.getPointerType(Context.VoidTy); 3468 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast); 3469 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast); 3470 return incompatTy; 3471 } 3472 // The block pointer types are compatible. 3473 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast); 3474 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast); 3475 return LHSTy; 3476 } 3477 // Check constraints for Objective-C object pointers types. 3478 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 3479 3480 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 3481 // Two identical object pointer types are always compatible. 3482 return LHSTy; 3483 } 3484 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>(); 3485 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>(); 3486 QualType compositeType = LHSTy; 3487 3488 // If both operands are interfaces and either operand can be 3489 // assigned to the other, use that type as the composite 3490 // type. This allows 3491 // xxx ? (A*) a : (B*) b 3492 // where B is a subclass of A. 3493 // 3494 // Additionally, as for assignment, if either type is 'id' 3495 // allow silent coercion. Finally, if the types are 3496 // incompatible then make sure to use 'id' as the composite 3497 // type so the result is acceptable for sending messages to. 3498 3499 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 3500 // It could return the composite type. 3501 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 3502 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 3503 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 3504 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 3505 } else if ((LHSTy->isObjCQualifiedIdType() || 3506 RHSTy->isObjCQualifiedIdType()) && 3507 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 3508 // Need to handle "id<xx>" explicitly. 3509 // GCC allows qualified id and any Objective-C type to devolve to 3510 // id. Currently localizing to here until clear this should be 3511 // part of ObjCQualifiedIdTypesAreCompatible. 3512 compositeType = Context.getObjCIdType(); 3513 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 3514 compositeType = Context.getObjCIdType(); 3515 } else if (!(compositeType = 3516 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 3517 ; 3518 else { 3519 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 3520 << LHSTy << RHSTy 3521 << LHS->getSourceRange() << RHS->getSourceRange(); 3522 QualType incompatTy = Context.getObjCIdType(); 3523 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast); 3524 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast); 3525 return incompatTy; 3526 } 3527 // The object pointer types are compatible. 3528 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast); 3529 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast); 3530 return compositeType; 3531 } 3532 // Check Objective-C object pointer types and 'void *' 3533 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 3534 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 3535 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 3536 QualType destPointee 3537 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 3538 QualType destType = Context.getPointerType(destPointee); 3539 // Add qualifiers if necessary. 3540 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp); 3541 // Promote to void*. 3542 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast); 3543 return destType; 3544 } 3545 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 3546 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 3547 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 3548 QualType destPointee 3549 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 3550 QualType destType = Context.getPointerType(destPointee); 3551 // Add qualifiers if necessary. 3552 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp); 3553 // Promote to void*. 3554 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast); 3555 return destType; 3556 } 3557 // Check constraints for C object pointers types (C99 6.5.15p3,6). 3558 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 3559 // get the "pointed to" types 3560 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 3561 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 3562 3563 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 3564 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 3565 // Figure out necessary qualifiers (C99 6.5.15p6) 3566 QualType destPointee 3567 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 3568 QualType destType = Context.getPointerType(destPointee); 3569 // Add qualifiers if necessary. 3570 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp); 3571 // Promote to void*. 3572 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast); 3573 return destType; 3574 } 3575 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 3576 QualType destPointee 3577 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 3578 QualType destType = Context.getPointerType(destPointee); 3579 // Add qualifiers if necessary. 3580 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp); 3581 // Promote to void*. 3582 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast); 3583 return destType; 3584 } 3585 3586 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 3587 // Two identical pointer types are always compatible. 3588 return LHSTy; 3589 } 3590 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 3591 rhptee.getUnqualifiedType())) { 3592 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers) 3593 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 3594 // In this situation, we assume void* type. No especially good 3595 // reason, but this is what gcc does, and we do have to pick 3596 // to get a consistent AST. 3597 QualType incompatTy = Context.getPointerType(Context.VoidTy); 3598 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast); 3599 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast); 3600 return incompatTy; 3601 } 3602 // The pointer types are compatible. 3603 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to 3604 // differently qualified versions of compatible types, the result type is 3605 // a pointer to an appropriately qualified version of the *composite* 3606 // type. 3607 // FIXME: Need to calculate the composite type. 3608 // FIXME: Need to add qualifiers 3609 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast); 3610 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast); 3611 return LHSTy; 3612 } 3613 3614 // GCC compatibility: soften pointer/integer mismatch. 3615 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) { 3616 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch) 3617 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 3618 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer); 3619 return RHSTy; 3620 } 3621 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) { 3622 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch) 3623 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 3624 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer); 3625 return LHSTy; 3626 } 3627 3628 // Otherwise, the operands are not compatible. 3629 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 3630 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 3631 return QualType(); 3632} 3633 3634/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 3635/// in the case of a the GNU conditional expr extension. 3636Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 3637 SourceLocation ColonLoc, 3638 ExprArg Cond, ExprArg LHS, 3639 ExprArg RHS) { 3640 Expr *CondExpr = (Expr *) Cond.get(); 3641 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get(); 3642 3643 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 3644 // was the condition. 3645 bool isLHSNull = LHSExpr == 0; 3646 if (isLHSNull) 3647 LHSExpr = CondExpr; 3648 3649 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, 3650 RHSExpr, QuestionLoc); 3651 if (result.isNull()) 3652 return ExprError(); 3653 3654 Cond.release(); 3655 LHS.release(); 3656 RHS.release(); 3657 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc, 3658 isLHSNull ? 0 : LHSExpr, 3659 ColonLoc, RHSExpr, result)); 3660} 3661 3662// CheckPointerTypesForAssignment - This is a very tricky routine (despite 3663// being closely modeled after the C99 spec:-). The odd characteristic of this 3664// routine is it effectively iqnores the qualifiers on the top level pointee. 3665// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 3666// FIXME: add a couple examples in this comment. 3667Sema::AssignConvertType 3668Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) { 3669 QualType lhptee, rhptee; 3670 3671 if ((lhsType->isObjCClassType() && 3672 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) || 3673 (rhsType->isObjCClassType() && 3674 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) { 3675 return Compatible; 3676 } 3677 3678 // get the "pointed to" type (ignoring qualifiers at the top level) 3679 lhptee = lhsType->getAs<PointerType>()->getPointeeType(); 3680 rhptee = rhsType->getAs<PointerType>()->getPointeeType(); 3681 3682 // make sure we operate on the canonical type 3683 lhptee = Context.getCanonicalType(lhptee); 3684 rhptee = Context.getCanonicalType(rhptee); 3685 3686 AssignConvertType ConvTy = Compatible; 3687 3688 // C99 6.5.16.1p1: This following citation is common to constraints 3689 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 3690 // qualifiers of the type *pointed to* by the right; 3691 // FIXME: Handle ExtQualType 3692 if (!lhptee.isAtLeastAsQualifiedAs(rhptee)) 3693 ConvTy = CompatiblePointerDiscardsQualifiers; 3694 3695 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 3696 // incomplete type and the other is a pointer to a qualified or unqualified 3697 // version of void... 3698 if (lhptee->isVoidType()) { 3699 if (rhptee->isIncompleteOrObjectType()) 3700 return ConvTy; 3701 3702 // As an extension, we allow cast to/from void* to function pointer. 3703 assert(rhptee->isFunctionType()); 3704 return FunctionVoidPointer; 3705 } 3706 3707 if (rhptee->isVoidType()) { 3708 if (lhptee->isIncompleteOrObjectType()) 3709 return ConvTy; 3710 3711 // As an extension, we allow cast to/from void* to function pointer. 3712 assert(lhptee->isFunctionType()); 3713 return FunctionVoidPointer; 3714 } 3715 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 3716 // unqualified versions of compatible types, ... 3717 lhptee = lhptee.getUnqualifiedType(); 3718 rhptee = rhptee.getUnqualifiedType(); 3719 if (!Context.typesAreCompatible(lhptee, rhptee)) { 3720 // Check if the pointee types are compatible ignoring the sign. 3721 // We explicitly check for char so that we catch "char" vs 3722 // "unsigned char" on systems where "char" is unsigned. 3723 if (lhptee->isCharType()) 3724 lhptee = Context.UnsignedCharTy; 3725 else if (lhptee->isSignedIntegerType()) 3726 lhptee = Context.getCorrespondingUnsignedType(lhptee); 3727 3728 if (rhptee->isCharType()) 3729 rhptee = Context.UnsignedCharTy; 3730 else if (rhptee->isSignedIntegerType()) 3731 rhptee = Context.getCorrespondingUnsignedType(rhptee); 3732 3733 if (lhptee == rhptee) { 3734 // Types are compatible ignoring the sign. Qualifier incompatibility 3735 // takes priority over sign incompatibility because the sign 3736 // warning can be disabled. 3737 if (ConvTy != Compatible) 3738 return ConvTy; 3739 return IncompatiblePointerSign; 3740 } 3741 3742 // If we are a multi-level pointer, it's possible that our issue is simply 3743 // one of qualification - e.g. char ** -> const char ** is not allowed. If 3744 // the eventual target type is the same and the pointers have the same 3745 // level of indirection, this must be the issue. 3746 if (lhptee->isPointerType() && rhptee->isPointerType()) { 3747 do { 3748 lhptee = lhptee->getAs<PointerType>()->getPointeeType(); 3749 rhptee = rhptee->getAs<PointerType>()->getPointeeType(); 3750 3751 lhptee = Context.getCanonicalType(lhptee); 3752 rhptee = Context.getCanonicalType(rhptee); 3753 } while (lhptee->isPointerType() && rhptee->isPointerType()); 3754 3755 if (Context.hasSameUnqualifiedType(lhptee, rhptee)) 3756 return IncompatibleNestedPointerQualifiers; 3757 } 3758 3759 // General pointer incompatibility takes priority over qualifiers. 3760 return IncompatiblePointer; 3761 } 3762 return ConvTy; 3763} 3764 3765/// CheckBlockPointerTypesForAssignment - This routine determines whether two 3766/// block pointer types are compatible or whether a block and normal pointer 3767/// are compatible. It is more restrict than comparing two function pointer 3768// types. 3769Sema::AssignConvertType 3770Sema::CheckBlockPointerTypesForAssignment(QualType lhsType, 3771 QualType rhsType) { 3772 QualType lhptee, rhptee; 3773 3774 // get the "pointed to" type (ignoring qualifiers at the top level) 3775 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType(); 3776 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType(); 3777 3778 // make sure we operate on the canonical type 3779 lhptee = Context.getCanonicalType(lhptee); 3780 rhptee = Context.getCanonicalType(rhptee); 3781 3782 AssignConvertType ConvTy = Compatible; 3783 3784 // For blocks we enforce that qualifiers are identical. 3785 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers()) 3786 ConvTy = CompatiblePointerDiscardsQualifiers; 3787 3788 if (!Context.typesAreCompatible(lhptee, rhptee)) 3789 return IncompatibleBlockPointer; 3790 return ConvTy; 3791} 3792 3793/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 3794/// has code to accommodate several GCC extensions when type checking 3795/// pointers. Here are some objectionable examples that GCC considers warnings: 3796/// 3797/// int a, *pint; 3798/// short *pshort; 3799/// struct foo *pfoo; 3800/// 3801/// pint = pshort; // warning: assignment from incompatible pointer type 3802/// a = pint; // warning: assignment makes integer from pointer without a cast 3803/// pint = a; // warning: assignment makes pointer from integer without a cast 3804/// pint = pfoo; // warning: assignment from incompatible pointer type 3805/// 3806/// As a result, the code for dealing with pointers is more complex than the 3807/// C99 spec dictates. 3808/// 3809Sema::AssignConvertType 3810Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) { 3811 // Get canonical types. We're not formatting these types, just comparing 3812 // them. 3813 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType(); 3814 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType(); 3815 3816 if (lhsType == rhsType) 3817 return Compatible; // Common case: fast path an exact match. 3818 3819 if ((lhsType->isObjCClassType() && 3820 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) || 3821 (rhsType->isObjCClassType() && 3822 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) { 3823 return Compatible; 3824 } 3825 3826 // If the left-hand side is a reference type, then we are in a 3827 // (rare!) case where we've allowed the use of references in C, 3828 // e.g., as a parameter type in a built-in function. In this case, 3829 // just make sure that the type referenced is compatible with the 3830 // right-hand side type. The caller is responsible for adjusting 3831 // lhsType so that the resulting expression does not have reference 3832 // type. 3833 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) { 3834 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) 3835 return Compatible; 3836 return Incompatible; 3837 } 3838 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 3839 // to the same ExtVector type. 3840 if (lhsType->isExtVectorType()) { 3841 if (rhsType->isExtVectorType()) 3842 return lhsType == rhsType ? Compatible : Incompatible; 3843 if (!rhsType->isVectorType() && rhsType->isArithmeticType()) 3844 return Compatible; 3845 } 3846 3847 if (lhsType->isVectorType() || rhsType->isVectorType()) { 3848 // If we are allowing lax vector conversions, and LHS and RHS are both 3849 // vectors, the total size only needs to be the same. This is a bitcast; 3850 // no bits are changed but the result type is different. 3851 if (getLangOptions().LaxVectorConversions && 3852 lhsType->isVectorType() && rhsType->isVectorType()) { 3853 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) 3854 return IncompatibleVectors; 3855 } 3856 return Incompatible; 3857 } 3858 3859 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) 3860 return Compatible; 3861 3862 if (isa<PointerType>(lhsType)) { 3863 if (rhsType->isIntegerType()) 3864 return IntToPointer; 3865 3866 if (isa<PointerType>(rhsType)) 3867 return CheckPointerTypesForAssignment(lhsType, rhsType); 3868 3869 // In general, C pointers are not compatible with ObjC object pointers. 3870 if (isa<ObjCObjectPointerType>(rhsType)) { 3871 if (lhsType->isVoidPointerType()) // an exception to the rule. 3872 return Compatible; 3873 return IncompatiblePointer; 3874 } 3875 if (rhsType->getAs<BlockPointerType>()) { 3876 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) 3877 return Compatible; 3878 3879 // Treat block pointers as objects. 3880 if (getLangOptions().ObjC1 && lhsType->isObjCIdType()) 3881 return Compatible; 3882 } 3883 return Incompatible; 3884 } 3885 3886 if (isa<BlockPointerType>(lhsType)) { 3887 if (rhsType->isIntegerType()) 3888 return IntToBlockPointer; 3889 3890 // Treat block pointers as objects. 3891 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) 3892 return Compatible; 3893 3894 if (rhsType->isBlockPointerType()) 3895 return CheckBlockPointerTypesForAssignment(lhsType, rhsType); 3896 3897 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) { 3898 if (RHSPT->getPointeeType()->isVoidType()) 3899 return Compatible; 3900 } 3901 return Incompatible; 3902 } 3903 3904 if (isa<ObjCObjectPointerType>(lhsType)) { 3905 if (rhsType->isIntegerType()) 3906 return IntToPointer; 3907 3908 // In general, C pointers are not compatible with ObjC object pointers. 3909 if (isa<PointerType>(rhsType)) { 3910 if (rhsType->isVoidPointerType()) // an exception to the rule. 3911 return Compatible; 3912 return IncompatiblePointer; 3913 } 3914 if (rhsType->isObjCObjectPointerType()) { 3915 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType()) 3916 return Compatible; 3917 if (Context.typesAreCompatible(lhsType, rhsType)) 3918 return Compatible; 3919 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) 3920 return IncompatibleObjCQualifiedId; 3921 return IncompatiblePointer; 3922 } 3923 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) { 3924 if (RHSPT->getPointeeType()->isVoidType()) 3925 return Compatible; 3926 } 3927 // Treat block pointers as objects. 3928 if (rhsType->isBlockPointerType()) 3929 return Compatible; 3930 return Incompatible; 3931 } 3932 if (isa<PointerType>(rhsType)) { 3933 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer. 3934 if (lhsType == Context.BoolTy) 3935 return Compatible; 3936 3937 if (lhsType->isIntegerType()) 3938 return PointerToInt; 3939 3940 if (isa<PointerType>(lhsType)) 3941 return CheckPointerTypesForAssignment(lhsType, rhsType); 3942 3943 if (isa<BlockPointerType>(lhsType) && 3944 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) 3945 return Compatible; 3946 return Incompatible; 3947 } 3948 if (isa<ObjCObjectPointerType>(rhsType)) { 3949 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer. 3950 if (lhsType == Context.BoolTy) 3951 return Compatible; 3952 3953 if (lhsType->isIntegerType()) 3954 return PointerToInt; 3955 3956 // In general, C pointers are not compatible with ObjC object pointers. 3957 if (isa<PointerType>(lhsType)) { 3958 if (lhsType->isVoidPointerType()) // an exception to the rule. 3959 return Compatible; 3960 return IncompatiblePointer; 3961 } 3962 if (isa<BlockPointerType>(lhsType) && 3963 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) 3964 return Compatible; 3965 return Incompatible; 3966 } 3967 3968 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) { 3969 if (Context.typesAreCompatible(lhsType, rhsType)) 3970 return Compatible; 3971 } 3972 return Incompatible; 3973} 3974 3975/// \brief Constructs a transparent union from an expression that is 3976/// used to initialize the transparent union. 3977static void ConstructTransparentUnion(ASTContext &C, Expr *&E, 3978 QualType UnionType, FieldDecl *Field) { 3979 // Build an initializer list that designates the appropriate member 3980 // of the transparent union. 3981 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(), 3982 &E, 1, 3983 SourceLocation()); 3984 Initializer->setType(UnionType); 3985 Initializer->setInitializedFieldInUnion(Field); 3986 3987 // Build a compound literal constructing a value of the transparent 3988 // union type from this initializer list. 3989 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer, 3990 false); 3991} 3992 3993Sema::AssignConvertType 3994Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) { 3995 QualType FromType = rExpr->getType(); 3996 3997 // If the ArgType is a Union type, we want to handle a potential 3998 // transparent_union GCC extension. 3999 const RecordType *UT = ArgType->getAsUnionType(); 4000 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4001 return Incompatible; 4002 4003 // The field to initialize within the transparent union. 4004 RecordDecl *UD = UT->getDecl(); 4005 FieldDecl *InitField = 0; 4006 // It's compatible if the expression matches any of the fields. 4007 for (RecordDecl::field_iterator it = UD->field_begin(), 4008 itend = UD->field_end(); 4009 it != itend; ++it) { 4010 if (it->getType()->isPointerType()) { 4011 // If the transparent union contains a pointer type, we allow: 4012 // 1) void pointer 4013 // 2) null pointer constant 4014 if (FromType->isPointerType()) 4015 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 4016 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast); 4017 InitField = *it; 4018 break; 4019 } 4020 4021 if (rExpr->isNullPointerConstant(Context, 4022 Expr::NPC_ValueDependentIsNull)) { 4023 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer); 4024 InitField = *it; 4025 break; 4026 } 4027 } 4028 4029 if (CheckAssignmentConstraints(it->getType(), rExpr->getType()) 4030 == Compatible) { 4031 InitField = *it; 4032 break; 4033 } 4034 } 4035 4036 if (!InitField) 4037 return Incompatible; 4038 4039 ConstructTransparentUnion(Context, rExpr, ArgType, InitField); 4040 return Compatible; 4041} 4042 4043Sema::AssignConvertType 4044Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) { 4045 if (getLangOptions().CPlusPlus) { 4046 if (!lhsType->isRecordType()) { 4047 // C++ 5.17p3: If the left operand is not of class type, the 4048 // expression is implicitly converted (C++ 4) to the 4049 // cv-unqualified type of the left operand. 4050 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(), 4051 "assigning")) 4052 return Incompatible; 4053 return Compatible; 4054 } 4055 4056 // FIXME: Currently, we fall through and treat C++ classes like C 4057 // structures. 4058 } 4059 4060 // C99 6.5.16.1p1: the left operand is a pointer and the right is 4061 // a null pointer constant. 4062 if ((lhsType->isPointerType() || 4063 lhsType->isObjCObjectPointerType() || 4064 lhsType->isBlockPointerType()) 4065 && rExpr->isNullPointerConstant(Context, 4066 Expr::NPC_ValueDependentIsNull)) { 4067 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown); 4068 return Compatible; 4069 } 4070 4071 // This check seems unnatural, however it is necessary to ensure the proper 4072 // conversion of functions/arrays. If the conversion were done for all 4073 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 4074 // expressions that surpress this implicit conversion (&, sizeof). 4075 // 4076 // Suppress this for references: C++ 8.5.3p5. 4077 if (!lhsType->isReferenceType()) 4078 DefaultFunctionArrayConversion(rExpr); 4079 4080 Sema::AssignConvertType result = 4081 CheckAssignmentConstraints(lhsType, rExpr->getType()); 4082 4083 // C99 6.5.16.1p2: The value of the right operand is converted to the 4084 // type of the assignment expression. 4085 // CheckAssignmentConstraints allows the left-hand side to be a reference, 4086 // so that we can use references in built-in functions even in C. 4087 // The getNonReferenceType() call makes sure that the resulting expression 4088 // does not have reference type. 4089 if (result != Incompatible && rExpr->getType() != lhsType) 4090 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(), 4091 CastExpr::CK_Unknown); 4092 return result; 4093} 4094 4095QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) { 4096 Diag(Loc, diag::err_typecheck_invalid_operands) 4097 << lex->getType() << rex->getType() 4098 << lex->getSourceRange() << rex->getSourceRange(); 4099 return QualType(); 4100} 4101 4102inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, 4103 Expr *&rex) { 4104 // For conversion purposes, we ignore any qualifiers. 4105 // For example, "const float" and "float" are equivalent. 4106 QualType lhsType = 4107 Context.getCanonicalType(lex->getType()).getUnqualifiedType(); 4108 QualType rhsType = 4109 Context.getCanonicalType(rex->getType()).getUnqualifiedType(); 4110 4111 // If the vector types are identical, return. 4112 if (lhsType == rhsType) 4113 return lhsType; 4114 4115 // Handle the case of a vector & extvector type of the same size and element 4116 // type. It would be nice if we only had one vector type someday. 4117 if (getLangOptions().LaxVectorConversions) { 4118 // FIXME: Should we warn here? 4119 if (const VectorType *LV = lhsType->getAs<VectorType>()) { 4120 if (const VectorType *RV = rhsType->getAs<VectorType>()) 4121 if (LV->getElementType() == RV->getElementType() && 4122 LV->getNumElements() == RV->getNumElements()) { 4123 return lhsType->isExtVectorType() ? lhsType : rhsType; 4124 } 4125 } 4126 } 4127 4128 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can 4129 // swap back (so that we don't reverse the inputs to a subtract, for instance. 4130 bool swapped = false; 4131 if (rhsType->isExtVectorType()) { 4132 swapped = true; 4133 std::swap(rex, lex); 4134 std::swap(rhsType, lhsType); 4135 } 4136 4137 // Handle the case of an ext vector and scalar. 4138 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) { 4139 QualType EltTy = LV->getElementType(); 4140 if (EltTy->isIntegralType() && rhsType->isIntegralType()) { 4141 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) { 4142 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast); 4143 if (swapped) std::swap(rex, lex); 4144 return lhsType; 4145 } 4146 } 4147 if (EltTy->isRealFloatingType() && rhsType->isScalarType() && 4148 rhsType->isRealFloatingType()) { 4149 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) { 4150 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast); 4151 if (swapped) std::swap(rex, lex); 4152 return lhsType; 4153 } 4154 } 4155 } 4156 4157 // Vectors of different size or scalar and non-ext-vector are errors. 4158 Diag(Loc, diag::err_typecheck_vector_not_convertable) 4159 << lex->getType() << rex->getType() 4160 << lex->getSourceRange() << rex->getSourceRange(); 4161 return QualType(); 4162} 4163 4164inline QualType Sema::CheckMultiplyDivideOperands( 4165 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) { 4166 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 4167 return CheckVectorOperands(Loc, lex, rex); 4168 4169 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 4170 4171 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 4172 return compType; 4173 return InvalidOperands(Loc, lex, rex); 4174} 4175 4176inline QualType Sema::CheckRemainderOperands( 4177 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) { 4178 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { 4179 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 4180 return CheckVectorOperands(Loc, lex, rex); 4181 return InvalidOperands(Loc, lex, rex); 4182 } 4183 4184 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 4185 4186 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 4187 return compType; 4188 return InvalidOperands(Loc, lex, rex); 4189} 4190 4191inline QualType Sema::CheckAdditionOperands( // C99 6.5.6 4192 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) { 4193 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { 4194 QualType compType = CheckVectorOperands(Loc, lex, rex); 4195 if (CompLHSTy) *CompLHSTy = compType; 4196 return compType; 4197 } 4198 4199 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy); 4200 4201 // handle the common case first (both operands are arithmetic). 4202 if (lex->getType()->isArithmeticType() && 4203 rex->getType()->isArithmeticType()) { 4204 if (CompLHSTy) *CompLHSTy = compType; 4205 return compType; 4206 } 4207 4208 // Put any potential pointer into PExp 4209 Expr* PExp = lex, *IExp = rex; 4210 if (IExp->getType()->isAnyPointerType()) 4211 std::swap(PExp, IExp); 4212 4213 if (PExp->getType()->isAnyPointerType()) { 4214 4215 if (IExp->getType()->isIntegerType()) { 4216 QualType PointeeTy = PExp->getType()->getPointeeType(); 4217 4218 // Check for arithmetic on pointers to incomplete types. 4219 if (PointeeTy->isVoidType()) { 4220 if (getLangOptions().CPlusPlus) { 4221 Diag(Loc, diag::err_typecheck_pointer_arith_void_type) 4222 << lex->getSourceRange() << rex->getSourceRange(); 4223 return QualType(); 4224 } 4225 4226 // GNU extension: arithmetic on pointer to void 4227 Diag(Loc, diag::ext_gnu_void_ptr) 4228 << lex->getSourceRange() << rex->getSourceRange(); 4229 } else if (PointeeTy->isFunctionType()) { 4230 if (getLangOptions().CPlusPlus) { 4231 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 4232 << lex->getType() << lex->getSourceRange(); 4233 return QualType(); 4234 } 4235 4236 // GNU extension: arithmetic on pointer to function 4237 Diag(Loc, diag::ext_gnu_ptr_func_arith) 4238 << lex->getType() << lex->getSourceRange(); 4239 } else { 4240 // Check if we require a complete type. 4241 if (((PExp->getType()->isPointerType() && 4242 !PExp->getType()->isDependentType()) || 4243 PExp->getType()->isObjCObjectPointerType()) && 4244 RequireCompleteType(Loc, PointeeTy, 4245 PDiag(diag::err_typecheck_arithmetic_incomplete_type) 4246 << PExp->getSourceRange() 4247 << PExp->getType())) 4248 return QualType(); 4249 } 4250 // Diagnose bad cases where we step over interface counts. 4251 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) { 4252 Diag(Loc, diag::err_arithmetic_nonfragile_interface) 4253 << PointeeTy << PExp->getSourceRange(); 4254 return QualType(); 4255 } 4256 4257 if (CompLHSTy) { 4258 QualType LHSTy = Context.isPromotableBitField(lex); 4259 if (LHSTy.isNull()) { 4260 LHSTy = lex->getType(); 4261 if (LHSTy->isPromotableIntegerType()) 4262 LHSTy = Context.getPromotedIntegerType(LHSTy); 4263 } 4264 *CompLHSTy = LHSTy; 4265 } 4266 return PExp->getType(); 4267 } 4268 } 4269 4270 return InvalidOperands(Loc, lex, rex); 4271} 4272 4273// C99 6.5.6 4274QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex, 4275 SourceLocation Loc, QualType* CompLHSTy) { 4276 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { 4277 QualType compType = CheckVectorOperands(Loc, lex, rex); 4278 if (CompLHSTy) *CompLHSTy = compType; 4279 return compType; 4280 } 4281 4282 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy); 4283 4284 // Enforce type constraints: C99 6.5.6p3. 4285 4286 // Handle the common case first (both operands are arithmetic). 4287 if (lex->getType()->isArithmeticType() 4288 && rex->getType()->isArithmeticType()) { 4289 if (CompLHSTy) *CompLHSTy = compType; 4290 return compType; 4291 } 4292 4293 // Either ptr - int or ptr - ptr. 4294 if (lex->getType()->isAnyPointerType()) { 4295 QualType lpointee = lex->getType()->getPointeeType(); 4296 4297 // The LHS must be an completely-defined object type. 4298 4299 bool ComplainAboutVoid = false; 4300 Expr *ComplainAboutFunc = 0; 4301 if (lpointee->isVoidType()) { 4302 if (getLangOptions().CPlusPlus) { 4303 Diag(Loc, diag::err_typecheck_pointer_arith_void_type) 4304 << lex->getSourceRange() << rex->getSourceRange(); 4305 return QualType(); 4306 } 4307 4308 // GNU C extension: arithmetic on pointer to void 4309 ComplainAboutVoid = true; 4310 } else if (lpointee->isFunctionType()) { 4311 if (getLangOptions().CPlusPlus) { 4312 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 4313 << lex->getType() << lex->getSourceRange(); 4314 return QualType(); 4315 } 4316 4317 // GNU C extension: arithmetic on pointer to function 4318 ComplainAboutFunc = lex; 4319 } else if (!lpointee->isDependentType() && 4320 RequireCompleteType(Loc, lpointee, 4321 PDiag(diag::err_typecheck_sub_ptr_object) 4322 << lex->getSourceRange() 4323 << lex->getType())) 4324 return QualType(); 4325 4326 // Diagnose bad cases where we step over interface counts. 4327 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) { 4328 Diag(Loc, diag::err_arithmetic_nonfragile_interface) 4329 << lpointee << lex->getSourceRange(); 4330 return QualType(); 4331 } 4332 4333 // The result type of a pointer-int computation is the pointer type. 4334 if (rex->getType()->isIntegerType()) { 4335 if (ComplainAboutVoid) 4336 Diag(Loc, diag::ext_gnu_void_ptr) 4337 << lex->getSourceRange() << rex->getSourceRange(); 4338 if (ComplainAboutFunc) 4339 Diag(Loc, diag::ext_gnu_ptr_func_arith) 4340 << ComplainAboutFunc->getType() 4341 << ComplainAboutFunc->getSourceRange(); 4342 4343 if (CompLHSTy) *CompLHSTy = lex->getType(); 4344 return lex->getType(); 4345 } 4346 4347 // Handle pointer-pointer subtractions. 4348 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) { 4349 QualType rpointee = RHSPTy->getPointeeType(); 4350 4351 // RHS must be a completely-type object type. 4352 // Handle the GNU void* extension. 4353 if (rpointee->isVoidType()) { 4354 if (getLangOptions().CPlusPlus) { 4355 Diag(Loc, diag::err_typecheck_pointer_arith_void_type) 4356 << lex->getSourceRange() << rex->getSourceRange(); 4357 return QualType(); 4358 } 4359 4360 ComplainAboutVoid = true; 4361 } else if (rpointee->isFunctionType()) { 4362 if (getLangOptions().CPlusPlus) { 4363 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 4364 << rex->getType() << rex->getSourceRange(); 4365 return QualType(); 4366 } 4367 4368 // GNU extension: arithmetic on pointer to function 4369 if (!ComplainAboutFunc) 4370 ComplainAboutFunc = rex; 4371 } else if (!rpointee->isDependentType() && 4372 RequireCompleteType(Loc, rpointee, 4373 PDiag(diag::err_typecheck_sub_ptr_object) 4374 << rex->getSourceRange() 4375 << rex->getType())) 4376 return QualType(); 4377 4378 if (getLangOptions().CPlusPlus) { 4379 // Pointee types must be the same: C++ [expr.add] 4380 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 4381 Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 4382 << lex->getType() << rex->getType() 4383 << lex->getSourceRange() << rex->getSourceRange(); 4384 return QualType(); 4385 } 4386 } else { 4387 // Pointee types must be compatible C99 6.5.6p3 4388 if (!Context.typesAreCompatible( 4389 Context.getCanonicalType(lpointee).getUnqualifiedType(), 4390 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 4391 Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 4392 << lex->getType() << rex->getType() 4393 << lex->getSourceRange() << rex->getSourceRange(); 4394 return QualType(); 4395 } 4396 } 4397 4398 if (ComplainAboutVoid) 4399 Diag(Loc, diag::ext_gnu_void_ptr) 4400 << lex->getSourceRange() << rex->getSourceRange(); 4401 if (ComplainAboutFunc) 4402 Diag(Loc, diag::ext_gnu_ptr_func_arith) 4403 << ComplainAboutFunc->getType() 4404 << ComplainAboutFunc->getSourceRange(); 4405 4406 if (CompLHSTy) *CompLHSTy = lex->getType(); 4407 return Context.getPointerDiffType(); 4408 } 4409 } 4410 4411 return InvalidOperands(Loc, lex, rex); 4412} 4413 4414// C99 6.5.7 4415QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, 4416 bool isCompAssign) { 4417 // C99 6.5.7p2: Each of the operands shall have integer type. 4418 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType()) 4419 return InvalidOperands(Loc, lex, rex); 4420 4421 // Vector shifts promote their scalar inputs to vector type. 4422 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 4423 return CheckVectorOperands(Loc, lex, rex); 4424 4425 // Shifts don't perform usual arithmetic conversions, they just do integer 4426 // promotions on each operand. C99 6.5.7p3 4427 QualType LHSTy = Context.isPromotableBitField(lex); 4428 if (LHSTy.isNull()) { 4429 LHSTy = lex->getType(); 4430 if (LHSTy->isPromotableIntegerType()) 4431 LHSTy = Context.getPromotedIntegerType(LHSTy); 4432 } 4433 if (!isCompAssign) 4434 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast); 4435 4436 UsualUnaryConversions(rex); 4437 4438 // Sanity-check shift operands 4439 llvm::APSInt Right; 4440 // Check right/shifter operand 4441 if (!rex->isValueDependent() && 4442 rex->isIntegerConstantExpr(Right, Context)) { 4443 if (Right.isNegative()) 4444 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange(); 4445 else { 4446 llvm::APInt LeftBits(Right.getBitWidth(), 4447 Context.getTypeSize(lex->getType())); 4448 if (Right.uge(LeftBits)) 4449 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange(); 4450 } 4451 } 4452 4453 // "The type of the result is that of the promoted left operand." 4454 return LHSTy; 4455} 4456 4457/// \brief Implements -Wsign-compare. 4458/// 4459/// \param lex the left-hand expression 4460/// \param rex the right-hand expression 4461/// \param OpLoc the location of the joining operator 4462/// \param Equality whether this is an "equality-like" join, which 4463/// suppresses the warning in some cases 4464void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc, 4465 const PartialDiagnostic &PD, bool Equality) { 4466 // Don't warn if we're in an unevaluated context. 4467 if (ExprEvalContext == Unevaluated) 4468 return; 4469 4470 QualType lt = lex->getType(), rt = rex->getType(); 4471 4472 // Only warn if both operands are integral. 4473 if (!lt->isIntegerType() || !rt->isIntegerType()) 4474 return; 4475 4476 // If either expression is value-dependent, don't warn. We'll get another 4477 // chance at instantiation time. 4478 if (lex->isValueDependent() || rex->isValueDependent()) 4479 return; 4480 4481 // The rule is that the signed operand becomes unsigned, so isolate the 4482 // signed operand. 4483 Expr *signedOperand, *unsignedOperand; 4484 if (lt->isSignedIntegerType()) { 4485 if (rt->isSignedIntegerType()) return; 4486 signedOperand = lex; 4487 unsignedOperand = rex; 4488 } else { 4489 if (!rt->isSignedIntegerType()) return; 4490 signedOperand = rex; 4491 unsignedOperand = lex; 4492 } 4493 4494 // If the unsigned type is strictly smaller than the signed type, 4495 // then (1) the result type will be signed and (2) the unsigned 4496 // value will fit fully within the signed type, and thus the result 4497 // of the comparison will be exact. 4498 if (Context.getIntWidth(signedOperand->getType()) > 4499 Context.getIntWidth(unsignedOperand->getType())) 4500 return; 4501 4502 // If the value is a non-negative integer constant, then the 4503 // signed->unsigned conversion won't change it. 4504 llvm::APSInt value; 4505 if (signedOperand->isIntegerConstantExpr(value, Context)) { 4506 assert(value.isSigned() && "result of signed expression not signed"); 4507 4508 if (value.isNonNegative()) 4509 return; 4510 } 4511 4512 if (Equality) { 4513 // For (in)equality comparisons, if the unsigned operand is a 4514 // constant which cannot collide with a overflowed signed operand, 4515 // then reinterpreting the signed operand as unsigned will not 4516 // change the result of the comparison. 4517 if (unsignedOperand->isIntegerConstantExpr(value, Context)) { 4518 assert(!value.isSigned() && "result of unsigned expression is signed"); 4519 4520 // 2's complement: test the top bit. 4521 if (value.isNonNegative()) 4522 return; 4523 } 4524 } 4525 4526 Diag(OpLoc, PD) 4527 << lex->getType() << rex->getType() 4528 << lex->getSourceRange() << rex->getSourceRange(); 4529} 4530 4531// C99 6.5.8, C++ [expr.rel] 4532QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, 4533 unsigned OpaqueOpc, bool isRelational) { 4534 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc; 4535 4536 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 4537 return CheckVectorCompareOperands(lex, rex, Loc, isRelational); 4538 4539 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison, 4540 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE)); 4541 4542 // C99 6.5.8p3 / C99 6.5.9p4 4543 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 4544 UsualArithmeticConversions(lex, rex); 4545 else { 4546 UsualUnaryConversions(lex); 4547 UsualUnaryConversions(rex); 4548 } 4549 QualType lType = lex->getType(); 4550 QualType rType = rex->getType(); 4551 4552 if (!lType->isFloatingType() 4553 && !(lType->isBlockPointerType() && isRelational)) { 4554 // For non-floating point types, check for self-comparisons of the form 4555 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 4556 // often indicate logic errors in the program. 4557 // NOTE: Don't warn about comparisons of enum constants. These can arise 4558 // from macro expansions, and are usually quite deliberate. 4559 Expr *LHSStripped = lex->IgnoreParens(); 4560 Expr *RHSStripped = rex->IgnoreParens(); 4561 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) 4562 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) 4563 if (DRL->getDecl() == DRR->getDecl() && 4564 !isa<EnumConstantDecl>(DRL->getDecl())) 4565 Diag(Loc, diag::warn_selfcomparison); 4566 4567 if (isa<CastExpr>(LHSStripped)) 4568 LHSStripped = LHSStripped->IgnoreParenCasts(); 4569 if (isa<CastExpr>(RHSStripped)) 4570 RHSStripped = RHSStripped->IgnoreParenCasts(); 4571 4572 // Warn about comparisons against a string constant (unless the other 4573 // operand is null), the user probably wants strcmp. 4574 Expr *literalString = 0; 4575 Expr *literalStringStripped = 0; 4576 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 4577 !RHSStripped->isNullPointerConstant(Context, 4578 Expr::NPC_ValueDependentIsNull)) { 4579 literalString = lex; 4580 literalStringStripped = LHSStripped; 4581 } else if ((isa<StringLiteral>(RHSStripped) || 4582 isa<ObjCEncodeExpr>(RHSStripped)) && 4583 !LHSStripped->isNullPointerConstant(Context, 4584 Expr::NPC_ValueDependentIsNull)) { 4585 literalString = rex; 4586 literalStringStripped = RHSStripped; 4587 } 4588 4589 if (literalString) { 4590 std::string resultComparison; 4591 switch (Opc) { 4592 case BinaryOperator::LT: resultComparison = ") < 0"; break; 4593 case BinaryOperator::GT: resultComparison = ") > 0"; break; 4594 case BinaryOperator::LE: resultComparison = ") <= 0"; break; 4595 case BinaryOperator::GE: resultComparison = ") >= 0"; break; 4596 case BinaryOperator::EQ: resultComparison = ") == 0"; break; 4597 case BinaryOperator::NE: resultComparison = ") != 0"; break; 4598 default: assert(false && "Invalid comparison operator"); 4599 } 4600 Diag(Loc, diag::warn_stringcompare) 4601 << isa<ObjCEncodeExpr>(literalStringStripped) 4602 << literalString->getSourceRange() 4603 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ") 4604 << CodeModificationHint::CreateInsertion(lex->getLocStart(), 4605 "strcmp(") 4606 << CodeModificationHint::CreateInsertion( 4607 PP.getLocForEndOfToken(rex->getLocEnd()), 4608 resultComparison); 4609 } 4610 } 4611 4612 // The result of comparisons is 'bool' in C++, 'int' in C. 4613 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy; 4614 4615 if (isRelational) { 4616 if (lType->isRealType() && rType->isRealType()) 4617 return ResultTy; 4618 } else { 4619 // Check for comparisons of floating point operands using != and ==. 4620 if (lType->isFloatingType()) { 4621 assert(rType->isFloatingType()); 4622 CheckFloatComparison(Loc,lex,rex); 4623 } 4624 4625 if (lType->isArithmeticType() && rType->isArithmeticType()) 4626 return ResultTy; 4627 } 4628 4629 bool LHSIsNull = lex->isNullPointerConstant(Context, 4630 Expr::NPC_ValueDependentIsNull); 4631 bool RHSIsNull = rex->isNullPointerConstant(Context, 4632 Expr::NPC_ValueDependentIsNull); 4633 4634 // All of the following pointer related warnings are GCC extensions, except 4635 // when handling null pointer constants. One day, we can consider making them 4636 // errors (when -pedantic-errors is enabled). 4637 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2 4638 QualType LCanPointeeTy = 4639 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType()); 4640 QualType RCanPointeeTy = 4641 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType()); 4642 4643 if (getLangOptions().CPlusPlus) { 4644 if (LCanPointeeTy == RCanPointeeTy) 4645 return ResultTy; 4646 4647 // C++ [expr.rel]p2: 4648 // [...] Pointer conversions (4.10) and qualification 4649 // conversions (4.4) are performed on pointer operands (or on 4650 // a pointer operand and a null pointer constant) to bring 4651 // them to their composite pointer type. [...] 4652 // 4653 // C++ [expr.eq]p1 uses the same notion for (in)equality 4654 // comparisons of pointers. 4655 QualType T = FindCompositePointerType(lex, rex); 4656 if (T.isNull()) { 4657 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers) 4658 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4659 return QualType(); 4660 } 4661 4662 ImpCastExprToType(lex, T, CastExpr::CK_BitCast); 4663 ImpCastExprToType(rex, T, CastExpr::CK_BitCast); 4664 return ResultTy; 4665 } 4666 // C99 6.5.9p2 and C99 6.5.8p2 4667 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 4668 RCanPointeeTy.getUnqualifiedType())) { 4669 // Valid unless a relational comparison of function pointers 4670 if (isRelational && LCanPointeeTy->isFunctionType()) { 4671 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 4672 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4673 } 4674 } else if (!isRelational && 4675 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 4676 // Valid unless comparison between non-null pointer and function pointer 4677 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 4678 && !LHSIsNull && !RHSIsNull) { 4679 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void) 4680 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4681 } 4682 } else { 4683 // Invalid 4684 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 4685 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4686 } 4687 if (LCanPointeeTy != RCanPointeeTy) 4688 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast); 4689 return ResultTy; 4690 } 4691 4692 if (getLangOptions().CPlusPlus) { 4693 // Comparison of pointers with null pointer constants and equality 4694 // comparisons of member pointers to null pointer constants. 4695 if (RHSIsNull && 4696 (lType->isPointerType() || 4697 (!isRelational && lType->isMemberPointerType()))) { 4698 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer); 4699 return ResultTy; 4700 } 4701 if (LHSIsNull && 4702 (rType->isPointerType() || 4703 (!isRelational && rType->isMemberPointerType()))) { 4704 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer); 4705 return ResultTy; 4706 } 4707 4708 // Comparison of member pointers. 4709 if (!isRelational && 4710 lType->isMemberPointerType() && rType->isMemberPointerType()) { 4711 // C++ [expr.eq]p2: 4712 // In addition, pointers to members can be compared, or a pointer to 4713 // member and a null pointer constant. Pointer to member conversions 4714 // (4.11) and qualification conversions (4.4) are performed to bring 4715 // them to a common type. If one operand is a null pointer constant, 4716 // the common type is the type of the other operand. Otherwise, the 4717 // common type is a pointer to member type similar (4.4) to the type 4718 // of one of the operands, with a cv-qualification signature (4.4) 4719 // that is the union of the cv-qualification signatures of the operand 4720 // types. 4721 QualType T = FindCompositePointerType(lex, rex); 4722 if (T.isNull()) { 4723 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers) 4724 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4725 return QualType(); 4726 } 4727 4728 ImpCastExprToType(lex, T, CastExpr::CK_BitCast); 4729 ImpCastExprToType(rex, T, CastExpr::CK_BitCast); 4730 return ResultTy; 4731 } 4732 4733 // Comparison of nullptr_t with itself. 4734 if (lType->isNullPtrType() && rType->isNullPtrType()) 4735 return ResultTy; 4736 } 4737 4738 // Handle block pointer types. 4739 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) { 4740 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType(); 4741 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType(); 4742 4743 if (!LHSIsNull && !RHSIsNull && 4744 !Context.typesAreCompatible(lpointee, rpointee)) { 4745 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 4746 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4747 } 4748 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast); 4749 return ResultTy; 4750 } 4751 // Allow block pointers to be compared with null pointer constants. 4752 if (!isRelational 4753 && ((lType->isBlockPointerType() && rType->isPointerType()) 4754 || (lType->isPointerType() && rType->isBlockPointerType()))) { 4755 if (!LHSIsNull && !RHSIsNull) { 4756 if (!((rType->isPointerType() && rType->getAs<PointerType>() 4757 ->getPointeeType()->isVoidType()) 4758 || (lType->isPointerType() && lType->getAs<PointerType>() 4759 ->getPointeeType()->isVoidType()))) 4760 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 4761 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4762 } 4763 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast); 4764 return ResultTy; 4765 } 4766 4767 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) { 4768 if (lType->isPointerType() || rType->isPointerType()) { 4769 const PointerType *LPT = lType->getAs<PointerType>(); 4770 const PointerType *RPT = rType->getAs<PointerType>(); 4771 bool LPtrToVoid = LPT ? 4772 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false; 4773 bool RPtrToVoid = RPT ? 4774 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false; 4775 4776 if (!LPtrToVoid && !RPtrToVoid && 4777 !Context.typesAreCompatible(lType, rType)) { 4778 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 4779 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4780 } 4781 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast); 4782 return ResultTy; 4783 } 4784 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) { 4785 if (!Context.areComparableObjCPointerTypes(lType, rType)) 4786 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 4787 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4788 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast); 4789 return ResultTy; 4790 } 4791 } 4792 if (lType->isAnyPointerType() && rType->isIntegerType()) { 4793 unsigned DiagID = 0; 4794 if (RHSIsNull) { 4795 if (isRelational) 4796 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 4797 } else if (isRelational) 4798 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 4799 else 4800 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 4801 4802 if (DiagID) { 4803 Diag(Loc, DiagID) 4804 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4805 } 4806 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer); 4807 return ResultTy; 4808 } 4809 if (lType->isIntegerType() && rType->isAnyPointerType()) { 4810 unsigned DiagID = 0; 4811 if (LHSIsNull) { 4812 if (isRelational) 4813 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 4814 } else if (isRelational) 4815 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 4816 else 4817 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 4818 4819 if (DiagID) { 4820 Diag(Loc, DiagID) 4821 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 4822 } 4823 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer); 4824 return ResultTy; 4825 } 4826 // Handle block pointers. 4827 if (!isRelational && RHSIsNull 4828 && lType->isBlockPointerType() && rType->isIntegerType()) { 4829 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer); 4830 return ResultTy; 4831 } 4832 if (!isRelational && LHSIsNull 4833 && lType->isIntegerType() && rType->isBlockPointerType()) { 4834 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer); 4835 return ResultTy; 4836 } 4837 return InvalidOperands(Loc, lex, rex); 4838} 4839 4840/// CheckVectorCompareOperands - vector comparisons are a clang extension that 4841/// operates on extended vector types. Instead of producing an IntTy result, 4842/// like a scalar comparison, a vector comparison produces a vector of integer 4843/// types. 4844QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex, 4845 SourceLocation Loc, 4846 bool isRelational) { 4847 // Check to make sure we're operating on vectors of the same type and width, 4848 // Allowing one side to be a scalar of element type. 4849 QualType vType = CheckVectorOperands(Loc, lex, rex); 4850 if (vType.isNull()) 4851 return vType; 4852 4853 QualType lType = lex->getType(); 4854 QualType rType = rex->getType(); 4855 4856 // For non-floating point types, check for self-comparisons of the form 4857 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 4858 // often indicate logic errors in the program. 4859 if (!lType->isFloatingType()) { 4860 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens())) 4861 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens())) 4862 if (DRL->getDecl() == DRR->getDecl()) 4863 Diag(Loc, diag::warn_selfcomparison); 4864 } 4865 4866 // Check for comparisons of floating point operands using != and ==. 4867 if (!isRelational && lType->isFloatingType()) { 4868 assert (rType->isFloatingType()); 4869 CheckFloatComparison(Loc,lex,rex); 4870 } 4871 4872 // Return the type for the comparison, which is the same as vector type for 4873 // integer vectors, or an integer type of identical size and number of 4874 // elements for floating point vectors. 4875 if (lType->isIntegerType()) 4876 return lType; 4877 4878 const VectorType *VTy = lType->getAs<VectorType>(); 4879 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 4880 if (TypeSize == Context.getTypeSize(Context.IntTy)) 4881 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 4882 if (TypeSize == Context.getTypeSize(Context.LongTy)) 4883 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 4884 4885 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 4886 "Unhandled vector element size in vector compare"); 4887 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 4888} 4889 4890inline QualType Sema::CheckBitwiseOperands( 4891 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) { 4892 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 4893 return CheckVectorOperands(Loc, lex, rex); 4894 4895 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 4896 4897 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 4898 return compType; 4899 return InvalidOperands(Loc, lex, rex); 4900} 4901 4902inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 4903 Expr *&lex, Expr *&rex, SourceLocation Loc) { 4904 if (!Context.getLangOptions().CPlusPlus) { 4905 UsualUnaryConversions(lex); 4906 UsualUnaryConversions(rex); 4907 4908 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType()) 4909 return InvalidOperands(Loc, lex, rex); 4910 4911 return Context.IntTy; 4912 } 4913 4914 // C++ [expr.log.and]p1 4915 // C++ [expr.log.or]p1 4916 // The operands are both implicitly converted to type bool (clause 4). 4917 StandardConversionSequence LHS; 4918 if (!IsStandardConversion(lex, Context.BoolTy, 4919 /*InOverloadResolution=*/false, LHS)) 4920 return InvalidOperands(Loc, lex, rex); 4921 4922 if (PerformImplicitConversion(lex, Context.BoolTy, LHS, 4923 "passing", /*IgnoreBaseAccess=*/false)) 4924 return InvalidOperands(Loc, lex, rex); 4925 4926 StandardConversionSequence RHS; 4927 if (!IsStandardConversion(rex, Context.BoolTy, 4928 /*InOverloadResolution=*/false, RHS)) 4929 return InvalidOperands(Loc, lex, rex); 4930 4931 if (PerformImplicitConversion(rex, Context.BoolTy, RHS, 4932 "passing", /*IgnoreBaseAccess=*/false)) 4933 return InvalidOperands(Loc, lex, rex); 4934 4935 // C++ [expr.log.and]p2 4936 // C++ [expr.log.or]p2 4937 // The result is a bool. 4938 return Context.BoolTy; 4939} 4940 4941/// IsReadonlyProperty - Verify that otherwise a valid l-value expression 4942/// is a read-only property; return true if so. A readonly property expression 4943/// depends on various declarations and thus must be treated specially. 4944/// 4945static bool IsReadonlyProperty(Expr *E, Sema &S) { 4946 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) { 4947 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E); 4948 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) { 4949 QualType BaseType = PropExpr->getBase()->getType(); 4950 if (const ObjCObjectPointerType *OPT = 4951 BaseType->getAsObjCInterfacePointerType()) 4952 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl()) 4953 if (S.isPropertyReadonly(PDecl, IFace)) 4954 return true; 4955 } 4956 } 4957 return false; 4958} 4959 4960/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 4961/// emit an error and return true. If so, return false. 4962static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 4963 SourceLocation OrigLoc = Loc; 4964 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 4965 &Loc); 4966 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S)) 4967 IsLV = Expr::MLV_ReadonlyProperty; 4968 if (IsLV == Expr::MLV_Valid) 4969 return false; 4970 4971 unsigned Diag = 0; 4972 bool NeedType = false; 4973 switch (IsLV) { // C99 6.5.16p2 4974 default: assert(0 && "Unknown result from isModifiableLvalue!"); 4975 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break; 4976 case Expr::MLV_ArrayType: 4977 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 4978 NeedType = true; 4979 break; 4980 case Expr::MLV_NotObjectType: 4981 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 4982 NeedType = true; 4983 break; 4984 case Expr::MLV_LValueCast: 4985 Diag = diag::err_typecheck_lvalue_casts_not_supported; 4986 break; 4987 case Expr::MLV_InvalidExpression: 4988 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 4989 break; 4990 case Expr::MLV_IncompleteType: 4991 case Expr::MLV_IncompleteVoidType: 4992 return S.RequireCompleteType(Loc, E->getType(), 4993 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue) 4994 << E->getSourceRange()); 4995 case Expr::MLV_DuplicateVectorComponents: 4996 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 4997 break; 4998 case Expr::MLV_NotBlockQualified: 4999 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 5000 break; 5001 case Expr::MLV_ReadonlyProperty: 5002 Diag = diag::error_readonly_property_assignment; 5003 break; 5004 case Expr::MLV_NoSetterProperty: 5005 Diag = diag::error_nosetter_property_assignment; 5006 break; 5007 } 5008 5009 SourceRange Assign; 5010 if (Loc != OrigLoc) 5011 Assign = SourceRange(OrigLoc, OrigLoc); 5012 if (NeedType) 5013 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 5014 else 5015 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 5016 return true; 5017} 5018 5019 5020 5021// C99 6.5.16.1 5022QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS, 5023 SourceLocation Loc, 5024 QualType CompoundType) { 5025 // Verify that LHS is a modifiable lvalue, and emit error if not. 5026 if (CheckForModifiableLvalue(LHS, Loc, *this)) 5027 return QualType(); 5028 5029 QualType LHSType = LHS->getType(); 5030 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType; 5031 5032 AssignConvertType ConvTy; 5033 if (CompoundType.isNull()) { 5034 // Simple assignment "x = y". 5035 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS); 5036 // Special case of NSObject attributes on c-style pointer types. 5037 if (ConvTy == IncompatiblePointer && 5038 ((Context.isObjCNSObjectType(LHSType) && 5039 RHSType->isObjCObjectPointerType()) || 5040 (Context.isObjCNSObjectType(RHSType) && 5041 LHSType->isObjCObjectPointerType()))) 5042 ConvTy = Compatible; 5043 5044 // If the RHS is a unary plus or minus, check to see if they = and + are 5045 // right next to each other. If so, the user may have typo'd "x =+ 4" 5046 // instead of "x += 4". 5047 Expr *RHSCheck = RHS; 5048 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 5049 RHSCheck = ICE->getSubExpr(); 5050 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 5051 if ((UO->getOpcode() == UnaryOperator::Plus || 5052 UO->getOpcode() == UnaryOperator::Minus) && 5053 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 5054 // Only if the two operators are exactly adjacent. 5055 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() && 5056 // And there is a space or other character before the subexpr of the 5057 // unary +/-. We don't want to warn on "x=-1". 5058 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 5059 UO->getSubExpr()->getLocStart().isFileID()) { 5060 Diag(Loc, diag::warn_not_compound_assign) 5061 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-") 5062 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 5063 } 5064 } 5065 } else { 5066 // Compound assignment "x += y" 5067 ConvTy = CheckAssignmentConstraints(LHSType, RHSType); 5068 } 5069 5070 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 5071 RHS, "assigning")) 5072 return QualType(); 5073 5074 // C99 6.5.16p3: The type of an assignment expression is the type of the 5075 // left operand unless the left operand has qualified type, in which case 5076 // it is the unqualified version of the type of the left operand. 5077 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 5078 // is converted to the type of the assignment expression (above). 5079 // C++ 5.17p1: the type of the assignment expression is that of its left 5080 // operand. 5081 return LHSType.getUnqualifiedType(); 5082} 5083 5084// C99 6.5.17 5085QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) { 5086 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions. 5087 DefaultFunctionArrayConversion(RHS); 5088 5089 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be 5090 // incomplete in C++). 5091 5092 return RHS->getType(); 5093} 5094 5095/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 5096/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 5097QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc, 5098 bool isInc) { 5099 if (Op->isTypeDependent()) 5100 return Context.DependentTy; 5101 5102 QualType ResType = Op->getType(); 5103 assert(!ResType.isNull() && "no type for increment/decrement expression"); 5104 5105 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) { 5106 // Decrement of bool is not allowed. 5107 if (!isInc) { 5108 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 5109 return QualType(); 5110 } 5111 // Increment of bool sets it to true, but is deprecated. 5112 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 5113 } else if (ResType->isRealType()) { 5114 // OK! 5115 } else if (ResType->isAnyPointerType()) { 5116 QualType PointeeTy = ResType->getPointeeType(); 5117 5118 // C99 6.5.2.4p2, 6.5.6p2 5119 if (PointeeTy->isVoidType()) { 5120 if (getLangOptions().CPlusPlus) { 5121 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type) 5122 << Op->getSourceRange(); 5123 return QualType(); 5124 } 5125 5126 // Pointer to void is a GNU extension in C. 5127 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange(); 5128 } else if (PointeeTy->isFunctionType()) { 5129 if (getLangOptions().CPlusPlus) { 5130 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type) 5131 << Op->getType() << Op->getSourceRange(); 5132 return QualType(); 5133 } 5134 5135 Diag(OpLoc, diag::ext_gnu_ptr_func_arith) 5136 << ResType << Op->getSourceRange(); 5137 } else if (RequireCompleteType(OpLoc, PointeeTy, 5138 PDiag(diag::err_typecheck_arithmetic_incomplete_type) 5139 << Op->getSourceRange() 5140 << ResType)) 5141 return QualType(); 5142 // Diagnose bad cases where we step over interface counts. 5143 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) { 5144 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface) 5145 << PointeeTy << Op->getSourceRange(); 5146 return QualType(); 5147 } 5148 } else if (ResType->isComplexType()) { 5149 // C99 does not support ++/-- on complex types, we allow as an extension. 5150 Diag(OpLoc, diag::ext_integer_increment_complex) 5151 << ResType << Op->getSourceRange(); 5152 } else { 5153 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 5154 << ResType << Op->getSourceRange(); 5155 return QualType(); 5156 } 5157 // At this point, we know we have a real, complex or pointer type. 5158 // Now make sure the operand is a modifiable lvalue. 5159 if (CheckForModifiableLvalue(Op, OpLoc, *this)) 5160 return QualType(); 5161 return ResType; 5162} 5163 5164/// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 5165/// This routine allows us to typecheck complex/recursive expressions 5166/// where the declaration is needed for type checking. We only need to 5167/// handle cases when the expression references a function designator 5168/// or is an lvalue. Here are some examples: 5169/// - &(x) => x 5170/// - &*****f => f for f a function designator. 5171/// - &s.xx => s 5172/// - &s.zz[1].yy -> s, if zz is an array 5173/// - *(x + 1) -> x, if x is an array 5174/// - &"123"[2] -> 0 5175/// - & __real__ x -> x 5176static NamedDecl *getPrimaryDecl(Expr *E) { 5177 switch (E->getStmtClass()) { 5178 case Stmt::DeclRefExprClass: 5179 return cast<DeclRefExpr>(E)->getDecl(); 5180 case Stmt::MemberExprClass: 5181 // If this is an arrow operator, the address is an offset from 5182 // the base's value, so the object the base refers to is 5183 // irrelevant. 5184 if (cast<MemberExpr>(E)->isArrow()) 5185 return 0; 5186 // Otherwise, the expression refers to a part of the base 5187 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 5188 case Stmt::ArraySubscriptExprClass: { 5189 // FIXME: This code shouldn't be necessary! We should catch the implicit 5190 // promotion of register arrays earlier. 5191 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 5192 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 5193 if (ICE->getSubExpr()->getType()->isArrayType()) 5194 return getPrimaryDecl(ICE->getSubExpr()); 5195 } 5196 return 0; 5197 } 5198 case Stmt::UnaryOperatorClass: { 5199 UnaryOperator *UO = cast<UnaryOperator>(E); 5200 5201 switch(UO->getOpcode()) { 5202 case UnaryOperator::Real: 5203 case UnaryOperator::Imag: 5204 case UnaryOperator::Extension: 5205 return getPrimaryDecl(UO->getSubExpr()); 5206 default: 5207 return 0; 5208 } 5209 } 5210 case Stmt::ParenExprClass: 5211 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 5212 case Stmt::ImplicitCastExprClass: 5213 // If the result of an implicit cast is an l-value, we care about 5214 // the sub-expression; otherwise, the result here doesn't matter. 5215 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 5216 default: 5217 return 0; 5218 } 5219} 5220 5221/// CheckAddressOfOperand - The operand of & must be either a function 5222/// designator or an lvalue designating an object. If it is an lvalue, the 5223/// object cannot be declared with storage class register or be a bit field. 5224/// Note: The usual conversions are *not* applied to the operand of the & 5225/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 5226/// In C++, the operand might be an overloaded function name, in which case 5227/// we allow the '&' but retain the overloaded-function type. 5228QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) { 5229 // Make sure to ignore parentheses in subsequent checks 5230 op = op->IgnoreParens(); 5231 5232 if (op->isTypeDependent()) 5233 return Context.DependentTy; 5234 5235 if (getLangOptions().C99) { 5236 // Implement C99-only parts of addressof rules. 5237 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 5238 if (uOp->getOpcode() == UnaryOperator::Deref) 5239 // Per C99 6.5.3.2, the address of a deref always returns a valid result 5240 // (assuming the deref expression is valid). 5241 return uOp->getSubExpr()->getType(); 5242 } 5243 // Technically, there should be a check for array subscript 5244 // expressions here, but the result of one is always an lvalue anyway. 5245 } 5246 NamedDecl *dcl = getPrimaryDecl(op); 5247 Expr::isLvalueResult lval = op->isLvalue(Context); 5248 5249 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 5250 // C99 6.5.3.2p1 5251 // The operand must be either an l-value or a function designator 5252 if (!op->getType()->isFunctionType()) { 5253 // FIXME: emit more specific diag... 5254 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 5255 << op->getSourceRange(); 5256 return QualType(); 5257 } 5258 } else if (op->getBitField()) { // C99 6.5.3.2p1 5259 // The operand cannot be a bit-field 5260 Diag(OpLoc, diag::err_typecheck_address_of) 5261 << "bit-field" << op->getSourceRange(); 5262 return QualType(); 5263 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) && 5264 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){ 5265 // The operand cannot be an element of a vector 5266 Diag(OpLoc, diag::err_typecheck_address_of) 5267 << "vector element" << op->getSourceRange(); 5268 return QualType(); 5269 } else if (isa<ObjCPropertyRefExpr>(op)) { 5270 // cannot take address of a property expression. 5271 Diag(OpLoc, diag::err_typecheck_address_of) 5272 << "property expression" << op->getSourceRange(); 5273 return QualType(); 5274 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) { 5275 // FIXME: Can LHS ever be null here? 5276 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull()) 5277 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc); 5278 } else if (isa<UnresolvedLookupExpr>(op)) { 5279 return Context.OverloadTy; 5280 } else if (dcl) { // C99 6.5.3.2p1 5281 // We have an lvalue with a decl. Make sure the decl is not declared 5282 // with the register storage-class specifier. 5283 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 5284 if (vd->getStorageClass() == VarDecl::Register) { 5285 Diag(OpLoc, diag::err_typecheck_address_of) 5286 << "register variable" << op->getSourceRange(); 5287 return QualType(); 5288 } 5289 } else if (isa<FunctionTemplateDecl>(dcl)) { 5290 return Context.OverloadTy; 5291 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) { 5292 // Okay: we can take the address of a field. 5293 // Could be a pointer to member, though, if there is an explicit 5294 // scope qualifier for the class. 5295 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 5296 DeclContext *Ctx = dcl->getDeclContext(); 5297 if (Ctx && Ctx->isRecord()) { 5298 if (FD->getType()->isReferenceType()) { 5299 Diag(OpLoc, 5300 diag::err_cannot_form_pointer_to_member_of_reference_type) 5301 << FD->getDeclName() << FD->getType(); 5302 return QualType(); 5303 } 5304 5305 return Context.getMemberPointerType(op->getType(), 5306 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 5307 } 5308 } 5309 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) { 5310 // Okay: we can take the address of a function. 5311 // As above. 5312 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() && 5313 MD->isInstance()) 5314 return Context.getMemberPointerType(op->getType(), 5315 Context.getTypeDeclType(MD->getParent()).getTypePtr()); 5316 } else if (!isa<FunctionDecl>(dcl)) 5317 assert(0 && "Unknown/unexpected decl type"); 5318 } 5319 5320 if (lval == Expr::LV_IncompleteVoidType) { 5321 // Taking the address of a void variable is technically illegal, but we 5322 // allow it in cases which are otherwise valid. 5323 // Example: "extern void x; void* y = &x;". 5324 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 5325 } 5326 5327 // If the operand has type "type", the result has type "pointer to type". 5328 return Context.getPointerType(op->getType()); 5329} 5330 5331QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) { 5332 if (Op->isTypeDependent()) 5333 return Context.DependentTy; 5334 5335 UsualUnaryConversions(Op); 5336 QualType Ty = Op->getType(); 5337 5338 // Note that per both C89 and C99, this is always legal, even if ptype is an 5339 // incomplete type or void. It would be possible to warn about dereferencing 5340 // a void pointer, but it's completely well-defined, and such a warning is 5341 // unlikely to catch any mistakes. 5342 if (const PointerType *PT = Ty->getAs<PointerType>()) 5343 return PT->getPointeeType(); 5344 5345 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>()) 5346 return OPT->getPointeeType(); 5347 5348 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 5349 << Ty << Op->getSourceRange(); 5350 return QualType(); 5351} 5352 5353static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode( 5354 tok::TokenKind Kind) { 5355 BinaryOperator::Opcode Opc; 5356 switch (Kind) { 5357 default: assert(0 && "Unknown binop!"); 5358 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break; 5359 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break; 5360 case tok::star: Opc = BinaryOperator::Mul; break; 5361 case tok::slash: Opc = BinaryOperator::Div; break; 5362 case tok::percent: Opc = BinaryOperator::Rem; break; 5363 case tok::plus: Opc = BinaryOperator::Add; break; 5364 case tok::minus: Opc = BinaryOperator::Sub; break; 5365 case tok::lessless: Opc = BinaryOperator::Shl; break; 5366 case tok::greatergreater: Opc = BinaryOperator::Shr; break; 5367 case tok::lessequal: Opc = BinaryOperator::LE; break; 5368 case tok::less: Opc = BinaryOperator::LT; break; 5369 case tok::greaterequal: Opc = BinaryOperator::GE; break; 5370 case tok::greater: Opc = BinaryOperator::GT; break; 5371 case tok::exclaimequal: Opc = BinaryOperator::NE; break; 5372 case tok::equalequal: Opc = BinaryOperator::EQ; break; 5373 case tok::amp: Opc = BinaryOperator::And; break; 5374 case tok::caret: Opc = BinaryOperator::Xor; break; 5375 case tok::pipe: Opc = BinaryOperator::Or; break; 5376 case tok::ampamp: Opc = BinaryOperator::LAnd; break; 5377 case tok::pipepipe: Opc = BinaryOperator::LOr; break; 5378 case tok::equal: Opc = BinaryOperator::Assign; break; 5379 case tok::starequal: Opc = BinaryOperator::MulAssign; break; 5380 case tok::slashequal: Opc = BinaryOperator::DivAssign; break; 5381 case tok::percentequal: Opc = BinaryOperator::RemAssign; break; 5382 case tok::plusequal: Opc = BinaryOperator::AddAssign; break; 5383 case tok::minusequal: Opc = BinaryOperator::SubAssign; break; 5384 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break; 5385 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break; 5386 case tok::ampequal: Opc = BinaryOperator::AndAssign; break; 5387 case tok::caretequal: Opc = BinaryOperator::XorAssign; break; 5388 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break; 5389 case tok::comma: Opc = BinaryOperator::Comma; break; 5390 } 5391 return Opc; 5392} 5393 5394static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode( 5395 tok::TokenKind Kind) { 5396 UnaryOperator::Opcode Opc; 5397 switch (Kind) { 5398 default: assert(0 && "Unknown unary op!"); 5399 case tok::plusplus: Opc = UnaryOperator::PreInc; break; 5400 case tok::minusminus: Opc = UnaryOperator::PreDec; break; 5401 case tok::amp: Opc = UnaryOperator::AddrOf; break; 5402 case tok::star: Opc = UnaryOperator::Deref; break; 5403 case tok::plus: Opc = UnaryOperator::Plus; break; 5404 case tok::minus: Opc = UnaryOperator::Minus; break; 5405 case tok::tilde: Opc = UnaryOperator::Not; break; 5406 case tok::exclaim: Opc = UnaryOperator::LNot; break; 5407 case tok::kw___real: Opc = UnaryOperator::Real; break; 5408 case tok::kw___imag: Opc = UnaryOperator::Imag; break; 5409 case tok::kw___extension__: Opc = UnaryOperator::Extension; break; 5410 } 5411 return Opc; 5412} 5413 5414/// CreateBuiltinBinOp - Creates a new built-in binary operation with 5415/// operator @p Opc at location @c TokLoc. This routine only supports 5416/// built-in operations; ActOnBinOp handles overloaded operators. 5417Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 5418 unsigned Op, 5419 Expr *lhs, Expr *rhs) { 5420 QualType ResultTy; // Result type of the binary operator. 5421 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op; 5422 // The following two variables are used for compound assignment operators 5423 QualType CompLHSTy; // Type of LHS after promotions for computation 5424 QualType CompResultTy; // Type of computation result 5425 5426 switch (Opc) { 5427 case BinaryOperator::Assign: 5428 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType()); 5429 break; 5430 case BinaryOperator::PtrMemD: 5431 case BinaryOperator::PtrMemI: 5432 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc, 5433 Opc == BinaryOperator::PtrMemI); 5434 break; 5435 case BinaryOperator::Mul: 5436 case BinaryOperator::Div: 5437 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc); 5438 break; 5439 case BinaryOperator::Rem: 5440 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc); 5441 break; 5442 case BinaryOperator::Add: 5443 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc); 5444 break; 5445 case BinaryOperator::Sub: 5446 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc); 5447 break; 5448 case BinaryOperator::Shl: 5449 case BinaryOperator::Shr: 5450 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc); 5451 break; 5452 case BinaryOperator::LE: 5453 case BinaryOperator::LT: 5454 case BinaryOperator::GE: 5455 case BinaryOperator::GT: 5456 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true); 5457 break; 5458 case BinaryOperator::EQ: 5459 case BinaryOperator::NE: 5460 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false); 5461 break; 5462 case BinaryOperator::And: 5463 case BinaryOperator::Xor: 5464 case BinaryOperator::Or: 5465 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc); 5466 break; 5467 case BinaryOperator::LAnd: 5468 case BinaryOperator::LOr: 5469 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc); 5470 break; 5471 case BinaryOperator::MulAssign: 5472 case BinaryOperator::DivAssign: 5473 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true); 5474 CompLHSTy = CompResultTy; 5475 if (!CompResultTy.isNull()) 5476 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 5477 break; 5478 case BinaryOperator::RemAssign: 5479 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true); 5480 CompLHSTy = CompResultTy; 5481 if (!CompResultTy.isNull()) 5482 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 5483 break; 5484 case BinaryOperator::AddAssign: 5485 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy); 5486 if (!CompResultTy.isNull()) 5487 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 5488 break; 5489 case BinaryOperator::SubAssign: 5490 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy); 5491 if (!CompResultTy.isNull()) 5492 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 5493 break; 5494 case BinaryOperator::ShlAssign: 5495 case BinaryOperator::ShrAssign: 5496 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true); 5497 CompLHSTy = CompResultTy; 5498 if (!CompResultTy.isNull()) 5499 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 5500 break; 5501 case BinaryOperator::AndAssign: 5502 case BinaryOperator::XorAssign: 5503 case BinaryOperator::OrAssign: 5504 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true); 5505 CompLHSTy = CompResultTy; 5506 if (!CompResultTy.isNull()) 5507 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 5508 break; 5509 case BinaryOperator::Comma: 5510 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc); 5511 break; 5512 } 5513 if (ResultTy.isNull()) 5514 return ExprError(); 5515 if (CompResultTy.isNull()) 5516 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc)); 5517 else 5518 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy, 5519 CompLHSTy, CompResultTy, 5520 OpLoc)); 5521} 5522 5523/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps 5524/// ParenRange in parentheses. 5525static void SuggestParentheses(Sema &Self, SourceLocation Loc, 5526 const PartialDiagnostic &PD, 5527 SourceRange ParenRange) 5528{ 5529 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 5530 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) { 5531 // We can't display the parentheses, so just dig the 5532 // warning/error and return. 5533 Self.Diag(Loc, PD); 5534 return; 5535 } 5536 5537 Self.Diag(Loc, PD) 5538 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(") 5539 << CodeModificationHint::CreateInsertion(EndLoc, ")"); 5540} 5541 5542/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 5543/// operators are mixed in a way that suggests that the programmer forgot that 5544/// comparison operators have higher precedence. The most typical example of 5545/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 5546static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc, 5547 SourceLocation OpLoc,Expr *lhs,Expr *rhs){ 5548 typedef BinaryOperator BinOp; 5549 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1), 5550 rhsopc = static_cast<BinOp::Opcode>(-1); 5551 if (BinOp *BO = dyn_cast<BinOp>(lhs)) 5552 lhsopc = BO->getOpcode(); 5553 if (BinOp *BO = dyn_cast<BinOp>(rhs)) 5554 rhsopc = BO->getOpcode(); 5555 5556 // Subs are not binary operators. 5557 if (lhsopc == -1 && rhsopc == -1) 5558 return; 5559 5560 // Bitwise operations are sometimes used as eager logical ops. 5561 // Don't diagnose this. 5562 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) && 5563 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc))) 5564 return; 5565 5566 if (BinOp::isComparisonOp(lhsopc)) 5567 SuggestParentheses(Self, OpLoc, 5568 PDiag(diag::warn_precedence_bitwise_rel) 5569 << SourceRange(lhs->getLocStart(), OpLoc) 5570 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc), 5571 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd())); 5572 else if (BinOp::isComparisonOp(rhsopc)) 5573 SuggestParentheses(Self, OpLoc, 5574 PDiag(diag::warn_precedence_bitwise_rel) 5575 << SourceRange(OpLoc, rhs->getLocEnd()) 5576 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc), 5577 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart())); 5578} 5579 5580/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 5581/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3". 5582/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does. 5583static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc, 5584 SourceLocation OpLoc, Expr *lhs, Expr *rhs){ 5585 if (BinaryOperator::isBitwiseOp(Opc)) 5586 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs); 5587} 5588 5589// Binary Operators. 'Tok' is the token for the operator. 5590Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 5591 tok::TokenKind Kind, 5592 ExprArg LHS, ExprArg RHS) { 5593 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind); 5594 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>(); 5595 5596 assert((lhs != 0) && "ActOnBinOp(): missing left expression"); 5597 assert((rhs != 0) && "ActOnBinOp(): missing right expression"); 5598 5599 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 5600 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs); 5601 5602 return BuildBinOp(S, TokLoc, Opc, lhs, rhs); 5603} 5604 5605Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 5606 BinaryOperator::Opcode Opc, 5607 Expr *lhs, Expr *rhs) { 5608 if (getLangOptions().CPlusPlus && 5609 (lhs->getType()->isOverloadableType() || 5610 rhs->getType()->isOverloadableType())) { 5611 // Find all of the overloaded operators visible from this 5612 // point. We perform both an operator-name lookup from the local 5613 // scope and an argument-dependent lookup based on the types of 5614 // the arguments. 5615 FunctionSet Functions; 5616 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 5617 if (OverOp != OO_None) { 5618 if (S) 5619 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(), 5620 Functions); 5621 Expr *Args[2] = { lhs, rhs }; 5622 DeclarationName OpName 5623 = Context.DeclarationNames.getCXXOperatorName(OverOp); 5624 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions); 5625 } 5626 5627 // Build the (potentially-overloaded, potentially-dependent) 5628 // binary operation. 5629 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs); 5630 } 5631 5632 // Build a built-in binary operation. 5633 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs); 5634} 5635 5636Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 5637 unsigned OpcIn, 5638 ExprArg InputArg) { 5639 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 5640 5641 // FIXME: Input is modified below, but InputArg is not updated appropriately. 5642 Expr *Input = (Expr *)InputArg.get(); 5643 QualType resultType; 5644 switch (Opc) { 5645 case UnaryOperator::OffsetOf: 5646 assert(false && "Invalid unary operator"); 5647 break; 5648 5649 case UnaryOperator::PreInc: 5650 case UnaryOperator::PreDec: 5651 case UnaryOperator::PostInc: 5652 case UnaryOperator::PostDec: 5653 resultType = CheckIncrementDecrementOperand(Input, OpLoc, 5654 Opc == UnaryOperator::PreInc || 5655 Opc == UnaryOperator::PostInc); 5656 break; 5657 case UnaryOperator::AddrOf: 5658 resultType = CheckAddressOfOperand(Input, OpLoc); 5659 break; 5660 case UnaryOperator::Deref: 5661 DefaultFunctionArrayConversion(Input); 5662 resultType = CheckIndirectionOperand(Input, OpLoc); 5663 break; 5664 case UnaryOperator::Plus: 5665 case UnaryOperator::Minus: 5666 UsualUnaryConversions(Input); 5667 resultType = Input->getType(); 5668 if (resultType->isDependentType()) 5669 break; 5670 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 5671 break; 5672 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7 5673 resultType->isEnumeralType()) 5674 break; 5675 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6 5676 Opc == UnaryOperator::Plus && 5677 resultType->isPointerType()) 5678 break; 5679 5680 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 5681 << resultType << Input->getSourceRange()); 5682 case UnaryOperator::Not: // bitwise complement 5683 UsualUnaryConversions(Input); 5684 resultType = Input->getType(); 5685 if (resultType->isDependentType()) 5686 break; 5687 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 5688 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 5689 // C99 does not support '~' for complex conjugation. 5690 Diag(OpLoc, diag::ext_integer_complement_complex) 5691 << resultType << Input->getSourceRange(); 5692 else if (!resultType->isIntegerType()) 5693 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 5694 << resultType << Input->getSourceRange()); 5695 break; 5696 case UnaryOperator::LNot: // logical negation 5697 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 5698 DefaultFunctionArrayConversion(Input); 5699 resultType = Input->getType(); 5700 if (resultType->isDependentType()) 5701 break; 5702 if (!resultType->isScalarType()) // C99 6.5.3.3p1 5703 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 5704 << resultType << Input->getSourceRange()); 5705 // LNot always has type int. C99 6.5.3.3p5. 5706 // In C++, it's bool. C++ 5.3.1p8 5707 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy; 5708 break; 5709 case UnaryOperator::Real: 5710 case UnaryOperator::Imag: 5711 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real); 5712 break; 5713 case UnaryOperator::Extension: 5714 resultType = Input->getType(); 5715 break; 5716 } 5717 if (resultType.isNull()) 5718 return ExprError(); 5719 5720 InputArg.release(); 5721 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc)); 5722} 5723 5724Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 5725 UnaryOperator::Opcode Opc, 5726 ExprArg input) { 5727 Expr *Input = (Expr*)input.get(); 5728 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() && 5729 Opc != UnaryOperator::Extension) { 5730 // Find all of the overloaded operators visible from this 5731 // point. We perform both an operator-name lookup from the local 5732 // scope and an argument-dependent lookup based on the types of 5733 // the arguments. 5734 FunctionSet Functions; 5735 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 5736 if (OverOp != OO_None) { 5737 if (S) 5738 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 5739 Functions); 5740 DeclarationName OpName 5741 = Context.DeclarationNames.getCXXOperatorName(OverOp); 5742 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions); 5743 } 5744 5745 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input)); 5746 } 5747 5748 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input)); 5749} 5750 5751// Unary Operators. 'Tok' is the token for the operator. 5752Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 5753 tok::TokenKind Op, ExprArg input) { 5754 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input)); 5755} 5756 5757/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 5758Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, 5759 SourceLocation LabLoc, 5760 IdentifierInfo *LabelII) { 5761 // Look up the record for this label identifier. 5762 LabelStmt *&LabelDecl = getLabelMap()[LabelII]; 5763 5764 // If we haven't seen this label yet, create a forward reference. It 5765 // will be validated and/or cleaned up in ActOnFinishFunctionBody. 5766 if (LabelDecl == 0) 5767 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0); 5768 5769 // Create the AST node. The address of a label always has type 'void*'. 5770 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl, 5771 Context.getPointerType(Context.VoidTy))); 5772} 5773 5774Sema::OwningExprResult 5775Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt, 5776 SourceLocation RPLoc) { // "({..})" 5777 Stmt *SubStmt = static_cast<Stmt*>(substmt.get()); 5778 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 5779 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 5780 5781 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 5782 if (isFileScope) 5783 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 5784 5785 // FIXME: there are a variety of strange constraints to enforce here, for 5786 // example, it is not possible to goto into a stmt expression apparently. 5787 // More semantic analysis is needed. 5788 5789 // If there are sub stmts in the compound stmt, take the type of the last one 5790 // as the type of the stmtexpr. 5791 QualType Ty = Context.VoidTy; 5792 5793 if (!Compound->body_empty()) { 5794 Stmt *LastStmt = Compound->body_back(); 5795 // If LastStmt is a label, skip down through into the body. 5796 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) 5797 LastStmt = Label->getSubStmt(); 5798 5799 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) 5800 Ty = LastExpr->getType(); 5801 } 5802 5803 // FIXME: Check that expression type is complete/non-abstract; statement 5804 // expressions are not lvalues. 5805 5806 substmt.release(); 5807 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc)); 5808} 5809 5810Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 5811 SourceLocation BuiltinLoc, 5812 SourceLocation TypeLoc, 5813 TypeTy *argty, 5814 OffsetOfComponent *CompPtr, 5815 unsigned NumComponents, 5816 SourceLocation RPLoc) { 5817 // FIXME: This function leaks all expressions in the offset components on 5818 // error. 5819 // FIXME: Preserve type source info. 5820 QualType ArgTy = GetTypeFromParser(argty); 5821 assert(!ArgTy.isNull() && "Missing type argument!"); 5822 5823 bool Dependent = ArgTy->isDependentType(); 5824 5825 // We must have at least one component that refers to the type, and the first 5826 // one is known to be a field designator. Verify that the ArgTy represents 5827 // a struct/union/class. 5828 if (!Dependent && !ArgTy->isRecordType()) 5829 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy); 5830 5831 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable 5832 // with an incomplete type would be illegal. 5833 5834 // Otherwise, create a null pointer as the base, and iteratively process 5835 // the offsetof designators. 5836 QualType ArgTyPtr = Context.getPointerType(ArgTy); 5837 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr); 5838 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref, 5839 ArgTy, SourceLocation()); 5840 5841 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 5842 // GCC extension, diagnose them. 5843 // FIXME: This diagnostic isn't actually visible because the location is in 5844 // a system header! 5845 if (NumComponents != 1) 5846 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 5847 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 5848 5849 if (!Dependent) { 5850 bool DidWarnAboutNonPOD = false; 5851 5852 if (RequireCompleteType(TypeLoc, Res->getType(), 5853 diag::err_offsetof_incomplete_type)) 5854 return ExprError(); 5855 5856 // FIXME: Dependent case loses a lot of information here. And probably 5857 // leaks like a sieve. 5858 for (unsigned i = 0; i != NumComponents; ++i) { 5859 const OffsetOfComponent &OC = CompPtr[i]; 5860 if (OC.isBrackets) { 5861 // Offset of an array sub-field. TODO: Should we allow vector elements? 5862 const ArrayType *AT = Context.getAsArrayType(Res->getType()); 5863 if (!AT) { 5864 Res->Destroy(Context); 5865 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 5866 << Res->getType()); 5867 } 5868 5869 // FIXME: C++: Verify that operator[] isn't overloaded. 5870 5871 // Promote the array so it looks more like a normal array subscript 5872 // expression. 5873 DefaultFunctionArrayConversion(Res); 5874 5875 // C99 6.5.2.1p1 5876 Expr *Idx = static_cast<Expr*>(OC.U.E); 5877 // FIXME: Leaks Res 5878 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType()) 5879 return ExprError(Diag(Idx->getLocStart(), 5880 diag::err_typecheck_subscript_not_integer) 5881 << Idx->getSourceRange()); 5882 5883 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(), 5884 OC.LocEnd); 5885 continue; 5886 } 5887 5888 const RecordType *RC = Res->getType()->getAs<RecordType>(); 5889 if (!RC) { 5890 Res->Destroy(Context); 5891 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 5892 << Res->getType()); 5893 } 5894 5895 // Get the decl corresponding to this. 5896 RecordDecl *RD = RC->getDecl(); 5897 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 5898 if (!CRD->isPOD() && !DidWarnAboutNonPOD) { 5899 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type) 5900 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 5901 << Res->getType()); 5902 DidWarnAboutNonPOD = true; 5903 } 5904 } 5905 5906 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 5907 LookupQualifiedName(R, RD); 5908 5909 FieldDecl *MemberDecl 5910 = dyn_cast_or_null<FieldDecl>(R.getAsSingleDecl(Context)); 5911 // FIXME: Leaks Res 5912 if (!MemberDecl) 5913 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 5914 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd)); 5915 5916 // FIXME: C++: Verify that MemberDecl isn't a static field. 5917 // FIXME: Verify that MemberDecl isn't a bitfield. 5918 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) { 5919 Res = BuildAnonymousStructUnionMemberReference( 5920 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>(); 5921 } else { 5922 // MemberDecl->getType() doesn't get the right qualifiers, but it 5923 // doesn't matter here. 5924 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd, 5925 MemberDecl->getType().getNonReferenceType()); 5926 } 5927 } 5928 } 5929 5930 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf, 5931 Context.getSizeType(), BuiltinLoc)); 5932} 5933 5934 5935Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc, 5936 TypeTy *arg1,TypeTy *arg2, 5937 SourceLocation RPLoc) { 5938 // FIXME: Preserve type source info. 5939 QualType argT1 = GetTypeFromParser(arg1); 5940 QualType argT2 = GetTypeFromParser(arg2); 5941 5942 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)"); 5943 5944 if (getLangOptions().CPlusPlus) { 5945 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus) 5946 << SourceRange(BuiltinLoc, RPLoc); 5947 return ExprError(); 5948 } 5949 5950 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, 5951 argT1, argT2, RPLoc)); 5952} 5953 5954Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 5955 ExprArg cond, 5956 ExprArg expr1, ExprArg expr2, 5957 SourceLocation RPLoc) { 5958 Expr *CondExpr = static_cast<Expr*>(cond.get()); 5959 Expr *LHSExpr = static_cast<Expr*>(expr1.get()); 5960 Expr *RHSExpr = static_cast<Expr*>(expr2.get()); 5961 5962 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 5963 5964 QualType resType; 5965 bool ValueDependent = false; 5966 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 5967 resType = Context.DependentTy; 5968 ValueDependent = true; 5969 } else { 5970 // The conditional expression is required to be a constant expression. 5971 llvm::APSInt condEval(32); 5972 SourceLocation ExpLoc; 5973 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc)) 5974 return ExprError(Diag(ExpLoc, 5975 diag::err_typecheck_choose_expr_requires_constant) 5976 << CondExpr->getSourceRange()); 5977 5978 // If the condition is > zero, then the AST type is the same as the LSHExpr. 5979 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType(); 5980 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent() 5981 : RHSExpr->isValueDependent(); 5982 } 5983 5984 cond.release(); expr1.release(); expr2.release(); 5985 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 5986 resType, RPLoc, 5987 resType->isDependentType(), 5988 ValueDependent)); 5989} 5990 5991//===----------------------------------------------------------------------===// 5992// Clang Extensions. 5993//===----------------------------------------------------------------------===// 5994 5995/// ActOnBlockStart - This callback is invoked when a block literal is started. 5996void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) { 5997 // Analyze block parameters. 5998 BlockSemaInfo *BSI = new BlockSemaInfo(); 5999 6000 // Add BSI to CurBlock. 6001 BSI->PrevBlockInfo = CurBlock; 6002 CurBlock = BSI; 6003 6004 BSI->ReturnType = QualType(); 6005 BSI->TheScope = BlockScope; 6006 BSI->hasBlockDeclRefExprs = false; 6007 BSI->hasPrototype = false; 6008 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking; 6009 CurFunctionNeedsScopeChecking = false; 6010 6011 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc); 6012 PushDeclContext(BlockScope, BSI->TheDecl); 6013} 6014 6015void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) { 6016 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!"); 6017 6018 if (ParamInfo.getNumTypeObjects() == 0 6019 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) { 6020 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 6021 QualType T = GetTypeForDeclarator(ParamInfo, CurScope); 6022 6023 if (T->isArrayType()) { 6024 Diag(ParamInfo.getSourceRange().getBegin(), 6025 diag::err_block_returns_array); 6026 return; 6027 } 6028 6029 // The parameter list is optional, if there was none, assume (). 6030 if (!T->isFunctionType()) 6031 T = Context.getFunctionType(T, NULL, 0, 0, 0); 6032 6033 CurBlock->hasPrototype = true; 6034 CurBlock->isVariadic = false; 6035 // Check for a valid sentinel attribute on this block. 6036 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) { 6037 Diag(ParamInfo.getAttributes()->getLoc(), 6038 diag::warn_attribute_sentinel_not_variadic) << 1; 6039 // FIXME: remove the attribute. 6040 } 6041 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType(); 6042 6043 // Do not allow returning a objc interface by-value. 6044 if (RetTy->isObjCInterfaceType()) { 6045 Diag(ParamInfo.getSourceRange().getBegin(), 6046 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy; 6047 return; 6048 } 6049 return; 6050 } 6051 6052 // Analyze arguments to block. 6053 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function && 6054 "Not a function declarator!"); 6055 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun; 6056 6057 CurBlock->hasPrototype = FTI.hasPrototype; 6058 CurBlock->isVariadic = true; 6059 6060 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes 6061 // no arguments, not a function that takes a single void argument. 6062 if (FTI.hasPrototype && 6063 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 6064 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&& 6065 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) { 6066 // empty arg list, don't push any params. 6067 CurBlock->isVariadic = false; 6068 } else if (FTI.hasPrototype) { 6069 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) 6070 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>()); 6071 CurBlock->isVariadic = FTI.isVariadic; 6072 } 6073 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(), 6074 CurBlock->Params.size()); 6075 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic); 6076 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 6077 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 6078 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) 6079 // If this has an identifier, add it to the scope stack. 6080 if ((*AI)->getIdentifier()) 6081 PushOnScopeChains(*AI, CurBlock->TheScope); 6082 6083 // Check for a valid sentinel attribute on this block. 6084 if (!CurBlock->isVariadic && 6085 CurBlock->TheDecl->getAttr<SentinelAttr>()) { 6086 Diag(ParamInfo.getAttributes()->getLoc(), 6087 diag::warn_attribute_sentinel_not_variadic) << 1; 6088 // FIXME: remove the attribute. 6089 } 6090 6091 // Analyze the return type. 6092 QualType T = GetTypeForDeclarator(ParamInfo, CurScope); 6093 QualType RetTy = T->getAs<FunctionType>()->getResultType(); 6094 6095 // Do not allow returning a objc interface by-value. 6096 if (RetTy->isObjCInterfaceType()) { 6097 Diag(ParamInfo.getSourceRange().getBegin(), 6098 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy; 6099 } else if (!RetTy->isDependentType()) 6100 CurBlock->ReturnType = RetTy; 6101} 6102 6103/// ActOnBlockError - If there is an error parsing a block, this callback 6104/// is invoked to pop the information about the block from the action impl. 6105void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 6106 // Ensure that CurBlock is deleted. 6107 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock); 6108 6109 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking; 6110 6111 // Pop off CurBlock, handle nested blocks. 6112 PopDeclContext(); 6113 CurBlock = CurBlock->PrevBlockInfo; 6114 // FIXME: Delete the ParmVarDecl objects as well??? 6115} 6116 6117/// ActOnBlockStmtExpr - This is called when the body of a block statement 6118/// literal was successfully completed. ^(int x){...} 6119Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 6120 StmtArg body, Scope *CurScope) { 6121 // If blocks are disabled, emit an error. 6122 if (!LangOpts.Blocks) 6123 Diag(CaretLoc, diag::err_blocks_disable); 6124 6125 // Ensure that CurBlock is deleted. 6126 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock); 6127 6128 PopDeclContext(); 6129 6130 // Pop off CurBlock, handle nested blocks. 6131 CurBlock = CurBlock->PrevBlockInfo; 6132 6133 QualType RetTy = Context.VoidTy; 6134 if (!BSI->ReturnType.isNull()) 6135 RetTy = BSI->ReturnType; 6136 6137 llvm::SmallVector<QualType, 8> ArgTypes; 6138 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i) 6139 ArgTypes.push_back(BSI->Params[i]->getType()); 6140 6141 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>(); 6142 QualType BlockTy; 6143 if (!BSI->hasPrototype) 6144 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0, 6145 NoReturn); 6146 else 6147 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(), 6148 BSI->isVariadic, 0, false, false, 0, 0, 6149 NoReturn); 6150 6151 // FIXME: Check that return/parameter types are complete/non-abstract 6152 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end()); 6153 BlockTy = Context.getBlockPointerType(BlockTy); 6154 6155 // If needed, diagnose invalid gotos and switches in the block. 6156 if (CurFunctionNeedsScopeChecking) 6157 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get())); 6158 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking; 6159 6160 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>()); 6161 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody()); 6162 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy, 6163 BSI->hasBlockDeclRefExprs)); 6164} 6165 6166Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 6167 ExprArg expr, TypeTy *type, 6168 SourceLocation RPLoc) { 6169 QualType T = GetTypeFromParser(type); 6170 Expr *E = static_cast<Expr*>(expr.get()); 6171 Expr *OrigExpr = E; 6172 6173 InitBuiltinVaListType(); 6174 6175 // Get the va_list type 6176 QualType VaListType = Context.getBuiltinVaListType(); 6177 if (VaListType->isArrayType()) { 6178 // Deal with implicit array decay; for example, on x86-64, 6179 // va_list is an array, but it's supposed to decay to 6180 // a pointer for va_arg. 6181 VaListType = Context.getArrayDecayedType(VaListType); 6182 // Make sure the input expression also decays appropriately. 6183 UsualUnaryConversions(E); 6184 } else { 6185 // Otherwise, the va_list argument must be an l-value because 6186 // it is modified by va_arg. 6187 if (!E->isTypeDependent() && 6188 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 6189 return ExprError(); 6190 } 6191 6192 if (!E->isTypeDependent() && 6193 !Context.hasSameType(VaListType, E->getType())) { 6194 return ExprError(Diag(E->getLocStart(), 6195 diag::err_first_argument_to_va_arg_not_of_type_va_list) 6196 << OrigExpr->getType() << E->getSourceRange()); 6197 } 6198 6199 // FIXME: Check that type is complete/non-abstract 6200 // FIXME: Warn if a non-POD type is passed in. 6201 6202 expr.release(); 6203 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), 6204 RPLoc)); 6205} 6206 6207Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 6208 // The type of __null will be int or long, depending on the size of 6209 // pointers on the target. 6210 QualType Ty; 6211 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth()) 6212 Ty = Context.IntTy; 6213 else 6214 Ty = Context.LongTy; 6215 6216 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); 6217} 6218 6219static void 6220MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef, 6221 QualType DstType, 6222 Expr *SrcExpr, 6223 CodeModificationHint &Hint) { 6224 if (!SemaRef.getLangOptions().ObjC1) 6225 return; 6226 6227 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 6228 if (!PT) 6229 return; 6230 6231 // Check if the destination is of type 'id'. 6232 if (!PT->isObjCIdType()) { 6233 // Check if the destination is the 'NSString' interface. 6234 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 6235 if (!ID || !ID->getIdentifier()->isStr("NSString")) 6236 return; 6237 } 6238 6239 // Strip off any parens and casts. 6240 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts()); 6241 if (!SL || SL->isWide()) 6242 return; 6243 6244 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@"); 6245} 6246 6247bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 6248 SourceLocation Loc, 6249 QualType DstType, QualType SrcType, 6250 Expr *SrcExpr, const char *Flavor) { 6251 // Decode the result (notice that AST's are still created for extensions). 6252 bool isInvalid = false; 6253 unsigned DiagKind; 6254 CodeModificationHint Hint; 6255 6256 switch (ConvTy) { 6257 default: assert(0 && "Unknown conversion type"); 6258 case Compatible: return false; 6259 case PointerToInt: 6260 DiagKind = diag::ext_typecheck_convert_pointer_int; 6261 break; 6262 case IntToPointer: 6263 DiagKind = diag::ext_typecheck_convert_int_pointer; 6264 break; 6265 case IncompatiblePointer: 6266 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint); 6267 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 6268 break; 6269 case IncompatiblePointerSign: 6270 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 6271 break; 6272 case FunctionVoidPointer: 6273 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 6274 break; 6275 case CompatiblePointerDiscardsQualifiers: 6276 // If the qualifiers lost were because we were applying the 6277 // (deprecated) C++ conversion from a string literal to a char* 6278 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 6279 // Ideally, this check would be performed in 6280 // CheckPointerTypesForAssignment. However, that would require a 6281 // bit of refactoring (so that the second argument is an 6282 // expression, rather than a type), which should be done as part 6283 // of a larger effort to fix CheckPointerTypesForAssignment for 6284 // C++ semantics. 6285 if (getLangOptions().CPlusPlus && 6286 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 6287 return false; 6288 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 6289 break; 6290 case IncompatibleNestedPointerQualifiers: 6291 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 6292 break; 6293 case IntToBlockPointer: 6294 DiagKind = diag::err_int_to_block_pointer; 6295 break; 6296 case IncompatibleBlockPointer: 6297 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 6298 break; 6299 case IncompatibleObjCQualifiedId: 6300 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 6301 // it can give a more specific diagnostic. 6302 DiagKind = diag::warn_incompatible_qualified_id; 6303 break; 6304 case IncompatibleVectors: 6305 DiagKind = diag::warn_incompatible_vectors; 6306 break; 6307 case Incompatible: 6308 DiagKind = diag::err_typecheck_convert_incompatible; 6309 isInvalid = true; 6310 break; 6311 } 6312 6313 Diag(Loc, DiagKind) << DstType << SrcType << Flavor 6314 << SrcExpr->getSourceRange() << Hint; 6315 return isInvalid; 6316} 6317 6318bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){ 6319 llvm::APSInt ICEResult; 6320 if (E->isIntegerConstantExpr(ICEResult, Context)) { 6321 if (Result) 6322 *Result = ICEResult; 6323 return false; 6324 } 6325 6326 Expr::EvalResult EvalResult; 6327 6328 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() || 6329 EvalResult.HasSideEffects) { 6330 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange(); 6331 6332 if (EvalResult.Diag) { 6333 // We only show the note if it's not the usual "invalid subexpression" 6334 // or if it's actually in a subexpression. 6335 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice || 6336 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens()) 6337 Diag(EvalResult.DiagLoc, EvalResult.Diag); 6338 } 6339 6340 return true; 6341 } 6342 6343 Diag(E->getExprLoc(), diag::ext_expr_not_ice) << 6344 E->getSourceRange(); 6345 6346 if (EvalResult.Diag && 6347 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored) 6348 Diag(EvalResult.DiagLoc, EvalResult.Diag); 6349 6350 if (Result) 6351 *Result = EvalResult.Val.getInt(); 6352 return false; 6353} 6354 6355Sema::ExpressionEvaluationContext 6356Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) { 6357 // Introduce a new set of potentially referenced declarations to the stack. 6358 if (NewContext == PotentiallyPotentiallyEvaluated) 6359 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls()); 6360 6361 std::swap(ExprEvalContext, NewContext); 6362 return NewContext; 6363} 6364 6365void 6366Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext, 6367 ExpressionEvaluationContext NewContext) { 6368 ExprEvalContext = NewContext; 6369 6370 if (OldContext == PotentiallyPotentiallyEvaluated) { 6371 // Mark any remaining declarations in the current position of the stack 6372 // as "referenced". If they were not meant to be referenced, semantic 6373 // analysis would have eliminated them (e.g., in ActOnCXXTypeId). 6374 PotentiallyReferencedDecls RemainingDecls; 6375 RemainingDecls.swap(PotentiallyReferencedDeclStack.back()); 6376 PotentiallyReferencedDeclStack.pop_back(); 6377 6378 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(), 6379 IEnd = RemainingDecls.end(); 6380 I != IEnd; ++I) 6381 MarkDeclarationReferenced(I->first, I->second); 6382 } 6383} 6384 6385/// \brief Note that the given declaration was referenced in the source code. 6386/// 6387/// This routine should be invoke whenever a given declaration is referenced 6388/// in the source code, and where that reference occurred. If this declaration 6389/// reference means that the the declaration is used (C++ [basic.def.odr]p2, 6390/// C99 6.9p3), then the declaration will be marked as used. 6391/// 6392/// \param Loc the location where the declaration was referenced. 6393/// 6394/// \param D the declaration that has been referenced by the source code. 6395void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) { 6396 assert(D && "No declaration?"); 6397 6398 if (D->isUsed()) 6399 return; 6400 6401 // Mark a parameter or variable declaration "used", regardless of whether we're in a 6402 // template or not. The reason for this is that unevaluated expressions 6403 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and 6404 // -Wunused-parameters) 6405 if (isa<ParmVarDecl>(D) || 6406 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) 6407 D->setUsed(true); 6408 6409 // Do not mark anything as "used" within a dependent context; wait for 6410 // an instantiation. 6411 if (CurContext->isDependentContext()) 6412 return; 6413 6414 switch (ExprEvalContext) { 6415 case Unevaluated: 6416 // We are in an expression that is not potentially evaluated; do nothing. 6417 return; 6418 6419 case PotentiallyEvaluated: 6420 // We are in a potentially-evaluated expression, so this declaration is 6421 // "used"; handle this below. 6422 break; 6423 6424 case PotentiallyPotentiallyEvaluated: 6425 // We are in an expression that may be potentially evaluated; queue this 6426 // declaration reference until we know whether the expression is 6427 // potentially evaluated. 6428 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D)); 6429 return; 6430 } 6431 6432 // Note that this declaration has been used. 6433 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 6434 unsigned TypeQuals; 6435 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) { 6436 if (!Constructor->isUsed()) 6437 DefineImplicitDefaultConstructor(Loc, Constructor); 6438 } else if (Constructor->isImplicit() && 6439 Constructor->isCopyConstructor(Context, TypeQuals)) { 6440 if (!Constructor->isUsed()) 6441 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals); 6442 } 6443 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 6444 if (Destructor->isImplicit() && !Destructor->isUsed()) 6445 DefineImplicitDestructor(Loc, Destructor); 6446 6447 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) { 6448 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() && 6449 MethodDecl->getOverloadedOperator() == OO_Equal) { 6450 if (!MethodDecl->isUsed()) 6451 DefineImplicitOverloadedAssign(Loc, MethodDecl); 6452 } 6453 } 6454 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 6455 // Implicit instantiation of function templates and member functions of 6456 // class templates. 6457 if (!Function->getBody() && Function->isImplicitlyInstantiable()) { 6458 bool AlreadyInstantiated = false; 6459 if (FunctionTemplateSpecializationInfo *SpecInfo 6460 = Function->getTemplateSpecializationInfo()) { 6461 if (SpecInfo->getPointOfInstantiation().isInvalid()) 6462 SpecInfo->setPointOfInstantiation(Loc); 6463 else if (SpecInfo->getTemplateSpecializationKind() 6464 == TSK_ImplicitInstantiation) 6465 AlreadyInstantiated = true; 6466 } else if (MemberSpecializationInfo *MSInfo 6467 = Function->getMemberSpecializationInfo()) { 6468 if (MSInfo->getPointOfInstantiation().isInvalid()) 6469 MSInfo->setPointOfInstantiation(Loc); 6470 else if (MSInfo->getTemplateSpecializationKind() 6471 == TSK_ImplicitInstantiation) 6472 AlreadyInstantiated = true; 6473 } 6474 6475 if (!AlreadyInstantiated) 6476 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc)); 6477 } 6478 6479 // FIXME: keep track of references to static functions 6480 Function->setUsed(true); 6481 return; 6482 } 6483 6484 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 6485 // Implicit instantiation of static data members of class templates. 6486 if (Var->isStaticDataMember() && 6487 Var->getInstantiatedFromStaticDataMember()) { 6488 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 6489 assert(MSInfo && "Missing member specialization information?"); 6490 if (MSInfo->getPointOfInstantiation().isInvalid() && 6491 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) { 6492 MSInfo->setPointOfInstantiation(Loc); 6493 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc)); 6494 } 6495 } 6496 6497 // FIXME: keep track of references to static data? 6498 6499 D->setUsed(true); 6500 return; 6501 } 6502} 6503 6504bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 6505 CallExpr *CE, FunctionDecl *FD) { 6506 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 6507 return false; 6508 6509 PartialDiagnostic Note = 6510 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here) 6511 << FD->getDeclName() : PDiag(); 6512 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation(); 6513 6514 if (RequireCompleteType(Loc, ReturnType, 6515 FD ? 6516 PDiag(diag::err_call_function_incomplete_return) 6517 << CE->getSourceRange() << FD->getDeclName() : 6518 PDiag(diag::err_call_incomplete_return) 6519 << CE->getSourceRange(), 6520 std::make_pair(NoteLoc, Note))) 6521 return true; 6522 6523 return false; 6524} 6525 6526// Diagnose the common s/=/==/ typo. Note that adding parentheses 6527// will prevent this condition from triggering, which is what we want. 6528void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 6529 SourceLocation Loc; 6530 6531 unsigned diagnostic = diag::warn_condition_is_assignment; 6532 6533 if (isa<BinaryOperator>(E)) { 6534 BinaryOperator *Op = cast<BinaryOperator>(E); 6535 if (Op->getOpcode() != BinaryOperator::Assign) 6536 return; 6537 6538 // Greylist some idioms by putting them into a warning subcategory. 6539 if (ObjCMessageExpr *ME 6540 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 6541 Selector Sel = ME->getSelector(); 6542 6543 // self = [<foo> init...] 6544 if (isSelfExpr(Op->getLHS()) 6545 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init")) 6546 diagnostic = diag::warn_condition_is_idiomatic_assignment; 6547 6548 // <foo> = [<bar> nextObject] 6549 else if (Sel.isUnarySelector() && 6550 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject") 6551 diagnostic = diag::warn_condition_is_idiomatic_assignment; 6552 } 6553 6554 Loc = Op->getOperatorLoc(); 6555 } else if (isa<CXXOperatorCallExpr>(E)) { 6556 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E); 6557 if (Op->getOperator() != OO_Equal) 6558 return; 6559 6560 Loc = Op->getOperatorLoc(); 6561 } else { 6562 // Not an assignment. 6563 return; 6564 } 6565 6566 SourceLocation Open = E->getSourceRange().getBegin(); 6567 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 6568 6569 Diag(Loc, diagnostic) 6570 << E->getSourceRange() 6571 << CodeModificationHint::CreateInsertion(Open, "(") 6572 << CodeModificationHint::CreateInsertion(Close, ")"); 6573} 6574 6575bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) { 6576 DiagnoseAssignmentAsCondition(E); 6577 6578 if (!E->isTypeDependent()) { 6579 DefaultFunctionArrayConversion(E); 6580 6581 QualType T = E->getType(); 6582 6583 if (getLangOptions().CPlusPlus) { 6584 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4 6585 return true; 6586 } else if (!T->isScalarType()) { // C99 6.8.4.1p1 6587 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 6588 << T << E->getSourceRange(); 6589 return true; 6590 } 6591 } 6592 6593 return false; 6594} 6595