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