SemaExpr.cpp revision 988d1193697ec42b2e8d2d49516f6215d73c9eef
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 "clang/Sema/SemaInternal.h" 15#include "clang/Sema/Initialization.h" 16#include "clang/Sema/Lookup.h" 17#include "clang/Sema/AnalysisBasedWarnings.h" 18#include "clang/AST/ASTContext.h" 19#include "clang/AST/CXXInheritance.h" 20#include "clang/AST/DeclObjC.h" 21#include "clang/AST/DeclTemplate.h" 22#include "clang/AST/EvaluatedExprVisitor.h" 23#include "clang/AST/Expr.h" 24#include "clang/AST/ExprCXX.h" 25#include "clang/AST/ExprObjC.h" 26#include "clang/AST/RecursiveASTVisitor.h" 27#include "clang/AST/TypeLoc.h" 28#include "clang/Basic/PartialDiagnostic.h" 29#include "clang/Basic/SourceManager.h" 30#include "clang/Basic/TargetInfo.h" 31#include "clang/Lex/LiteralSupport.h" 32#include "clang/Lex/Preprocessor.h" 33#include "clang/Sema/DeclSpec.h" 34#include "clang/Sema/Designator.h" 35#include "clang/Sema/Scope.h" 36#include "clang/Sema/ScopeInfo.h" 37#include "clang/Sema/ParsedTemplate.h" 38#include "clang/Sema/Template.h" 39using namespace clang; 40using namespace sema; 41 42 43/// \brief Determine whether the use of this declaration is valid, and 44/// emit any corresponding diagnostics. 45/// 46/// This routine diagnoses various problems with referencing 47/// declarations that can occur when using a declaration. For example, 48/// it might warn if a deprecated or unavailable declaration is being 49/// used, or produce an error (and return true) if a C++0x deleted 50/// function is being used. 51/// 52/// If IgnoreDeprecated is set to true, this should not want about deprecated 53/// decls. 54/// 55/// \returns true if there was an error (this declaration cannot be 56/// referenced), false otherwise. 57/// 58bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) { 59 // See if the decl is deprecated. 60 if (const DeprecatedAttr *DA = D->getAttr<DeprecatedAttr>()) 61 EmitDeprecationWarning(D, DA->getMessage(), Loc); 62 63 // See if the decl is unavailable 64 if (const UnavailableAttr *UA = D->getAttr<UnavailableAttr>()) { 65 if (UA->getMessage().empty()) 66 Diag(Loc, diag::err_unavailable) << D->getDeclName(); 67 else 68 Diag(Loc, diag::err_unavailable_message) 69 << D->getDeclName() << UA->getMessage(); 70 Diag(D->getLocation(), diag::note_unavailable_here) << 0; 71 } 72 73 // See if this is a deleted function. 74 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 75 if (FD->isDeleted()) { 76 Diag(Loc, diag::err_deleted_function_use); 77 Diag(D->getLocation(), diag::note_unavailable_here) << true; 78 return true; 79 } 80 } 81 82 return false; 83} 84 85/// DiagnoseSentinelCalls - This routine checks on method dispatch calls 86/// (and other functions in future), which have been declared with sentinel 87/// attribute. It warns if call does not have the sentinel argument. 88/// 89void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 90 Expr **Args, unsigned NumArgs) { 91 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 92 if (!attr) 93 return; 94 95 // FIXME: In C++0x, if any of the arguments are parameter pack 96 // expansions, we can't check for the sentinel now. 97 int sentinelPos = attr->getSentinel(); 98 int nullPos = attr->getNullPos(); 99 100 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common 101 // base class. Then we won't be needing two versions of the same code. 102 unsigned int i = 0; 103 bool warnNotEnoughArgs = false; 104 int isMethod = 0; 105 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 106 // skip over named parameters. 107 ObjCMethodDecl::param_iterator P, E = MD->param_end(); 108 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) { 109 if (nullPos) 110 --nullPos; 111 else 112 ++i; 113 } 114 warnNotEnoughArgs = (P != E || i >= NumArgs); 115 isMethod = 1; 116 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 117 // skip over named parameters. 118 ObjCMethodDecl::param_iterator P, E = FD->param_end(); 119 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) { 120 if (nullPos) 121 --nullPos; 122 else 123 ++i; 124 } 125 warnNotEnoughArgs = (P != E || i >= NumArgs); 126 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) { 127 // block or function pointer call. 128 QualType Ty = V->getType(); 129 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) { 130 const FunctionType *FT = Ty->isFunctionPointerType() 131 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>() 132 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>(); 133 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) { 134 unsigned NumArgsInProto = Proto->getNumArgs(); 135 unsigned k; 136 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) { 137 if (nullPos) 138 --nullPos; 139 else 140 ++i; 141 } 142 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs); 143 } 144 if (Ty->isBlockPointerType()) 145 isMethod = 2; 146 } else 147 return; 148 } else 149 return; 150 151 if (warnNotEnoughArgs) { 152 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 153 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod; 154 return; 155 } 156 int sentinel = i; 157 while (sentinelPos > 0 && i < NumArgs-1) { 158 --sentinelPos; 159 ++i; 160 } 161 if (sentinelPos > 0) { 162 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 163 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod; 164 return; 165 } 166 while (i < NumArgs-1) { 167 ++i; 168 ++sentinel; 169 } 170 Expr *sentinelExpr = Args[sentinel]; 171 if (!sentinelExpr) return; 172 if (sentinelExpr->isTypeDependent()) return; 173 if (sentinelExpr->isValueDependent()) return; 174 if (sentinelExpr->getType()->isAnyPointerType() && 175 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context, 176 Expr::NPC_ValueDependentIsNull)) 177 return; 178 179 // Unfortunately, __null has type 'int'. 180 if (isa<GNUNullExpr>(sentinelExpr)) return; 181 182 Diag(Loc, diag::warn_missing_sentinel) << isMethod; 183 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod; 184} 185 186SourceRange Sema::getExprRange(ExprTy *E) const { 187 Expr *Ex = (Expr *)E; 188 return Ex? Ex->getSourceRange() : SourceRange(); 189} 190 191//===----------------------------------------------------------------------===// 192// Standard Promotions and Conversions 193//===----------------------------------------------------------------------===// 194 195/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 196void Sema::DefaultFunctionArrayConversion(Expr *&E) { 197 QualType Ty = E->getType(); 198 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 199 200 if (Ty->isFunctionType()) 201 ImpCastExprToType(E, Context.getPointerType(Ty), 202 CK_FunctionToPointerDecay); 203 else if (Ty->isArrayType()) { 204 // In C90 mode, arrays only promote to pointers if the array expression is 205 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 206 // type 'array of type' is converted to an expression that has type 'pointer 207 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 208 // that has type 'array of type' ...". The relevant change is "an lvalue" 209 // (C90) to "an expression" (C99). 210 // 211 // C++ 4.2p1: 212 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 213 // T" can be converted to an rvalue of type "pointer to T". 214 // 215 if (getLangOptions().C99 || getLangOptions().CPlusPlus || 216 E->isLvalue(Context) == Expr::LV_Valid) 217 ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 218 CK_ArrayToPointerDecay); 219 } 220} 221 222void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) { 223 DefaultFunctionArrayConversion(E); 224 225 QualType Ty = E->getType(); 226 assert(!Ty.isNull() && "DefaultFunctionArrayLvalueConversion - missing type"); 227 if (!Ty->isDependentType() && Ty.hasQualifiers() && 228 (!getLangOptions().CPlusPlus || !Ty->isRecordType()) && 229 E->isLvalue(Context) == Expr::LV_Valid) { 230 // C++ [conv.lval]p1: 231 // [...] If T is a non-class type, the type of the rvalue is the 232 // cv-unqualified version of T. Otherwise, the type of the 233 // rvalue is T 234 // 235 // C99 6.3.2.1p2: 236 // If the lvalue has qualified type, the value has the unqualified 237 // version of the type of the lvalue; otherwise, the value has the 238 // type of the lvalue. 239 ImpCastExprToType(E, Ty.getUnqualifiedType(), CK_NoOp); 240 } 241} 242 243 244/// UsualUnaryConversions - Performs various conversions that are common to most 245/// operators (C99 6.3). The conversions of array and function types are 246/// sometimes surpressed. For example, the array->pointer conversion doesn't 247/// apply if the array is an argument to the sizeof or address (&) operators. 248/// In these instances, this routine should *not* be called. 249Expr *Sema::UsualUnaryConversions(Expr *&Expr) { 250 QualType Ty = Expr->getType(); 251 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 252 253 // C99 6.3.1.1p2: 254 // 255 // The following may be used in an expression wherever an int or 256 // unsigned int may be used: 257 // - an object or expression with an integer type whose integer 258 // conversion rank is less than or equal to the rank of int 259 // and unsigned int. 260 // - A bit-field of type _Bool, int, signed int, or unsigned int. 261 // 262 // If an int can represent all values of the original type, the 263 // value is converted to an int; otherwise, it is converted to an 264 // unsigned int. These are called the integer promotions. All 265 // other types are unchanged by the integer promotions. 266 QualType PTy = Context.isPromotableBitField(Expr); 267 if (!PTy.isNull()) { 268 ImpCastExprToType(Expr, PTy, CK_IntegralCast); 269 return Expr; 270 } 271 if (Ty->isPromotableIntegerType()) { 272 QualType PT = Context.getPromotedIntegerType(Ty); 273 ImpCastExprToType(Expr, PT, CK_IntegralCast); 274 return Expr; 275 } 276 277 DefaultFunctionArrayLvalueConversion(Expr); 278 return Expr; 279} 280 281/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 282/// do not have a prototype. Arguments that have type float are promoted to 283/// double. All other argument types are converted by UsualUnaryConversions(). 284void Sema::DefaultArgumentPromotion(Expr *&Expr) { 285 QualType Ty = Expr->getType(); 286 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 287 288 // If this is a 'float' (CVR qualified or typedef) promote to double. 289 if (Ty->isSpecificBuiltinType(BuiltinType::Float)) 290 return ImpCastExprToType(Expr, Context.DoubleTy, 291 CK_FloatingCast); 292 293 UsualUnaryConversions(Expr); 294} 295 296/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 297/// will warn if the resulting type is not a POD type, and rejects ObjC 298/// interfaces passed by value. This returns true if the argument type is 299/// completely illegal. 300bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT, 301 FunctionDecl *FDecl) { 302 DefaultArgumentPromotion(Expr); 303 304 // __builtin_va_start takes the second argument as a "varargs" argument, but 305 // it doesn't actually do anything with it. It doesn't need to be non-pod 306 // etc. 307 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start) 308 return false; 309 310 if (Expr->getType()->isObjCObjectType() && 311 DiagRuntimeBehavior(Expr->getLocStart(), 312 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 313 << Expr->getType() << CT)) 314 return true; 315 316 if (!Expr->getType()->isPODType() && 317 DiagRuntimeBehavior(Expr->getLocStart(), 318 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 319 << Expr->getType() << CT)) 320 return true; 321 322 return false; 323} 324 325 326/// UsualArithmeticConversions - Performs various conversions that are common to 327/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 328/// routine returns the first non-arithmetic type found. The client is 329/// responsible for emitting appropriate error diagnostics. 330/// FIXME: verify the conversion rules for "complex int" are consistent with 331/// GCC. 332QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr, 333 bool isCompAssign) { 334 if (!isCompAssign) 335 UsualUnaryConversions(lhsExpr); 336 337 UsualUnaryConversions(rhsExpr); 338 339 // For conversion purposes, we ignore any qualifiers. 340 // For example, "const float" and "float" are equivalent. 341 QualType lhs = 342 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType(); 343 QualType rhs = 344 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType(); 345 346 // If both types are identical, no conversion is needed. 347 if (lhs == rhs) 348 return lhs; 349 350 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 351 // The caller can deal with this (e.g. pointer + int). 352 if (!lhs->isArithmeticType() || !rhs->isArithmeticType()) 353 return lhs; 354 355 // Perform bitfield promotions. 356 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr); 357 if (!LHSBitfieldPromoteTy.isNull()) 358 lhs = LHSBitfieldPromoteTy; 359 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr); 360 if (!RHSBitfieldPromoteTy.isNull()) 361 rhs = RHSBitfieldPromoteTy; 362 363 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs); 364 if (!isCompAssign) 365 ImpCastExprToType(lhsExpr, destType, CK_Unknown); 366 ImpCastExprToType(rhsExpr, destType, CK_Unknown); 367 return destType; 368} 369 370//===----------------------------------------------------------------------===// 371// Semantic Analysis for various Expression Types 372//===----------------------------------------------------------------------===// 373 374 375/// ActOnStringLiteral - The specified tokens were lexed as pasted string 376/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 377/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 378/// multiple tokens. However, the common case is that StringToks points to one 379/// string. 380/// 381ExprResult 382Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) { 383 assert(NumStringToks && "Must have at least one string!"); 384 385 StringLiteralParser Literal(StringToks, NumStringToks, PP); 386 if (Literal.hadError) 387 return ExprError(); 388 389 llvm::SmallVector<SourceLocation, 4> StringTokLocs; 390 for (unsigned i = 0; i != NumStringToks; ++i) 391 StringTokLocs.push_back(StringToks[i].getLocation()); 392 393 QualType StrTy = Context.CharTy; 394 if (Literal.AnyWide) StrTy = Context.getWCharType(); 395 if (Literal.Pascal) StrTy = Context.UnsignedCharTy; 396 397 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 398 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings) 399 StrTy.addConst(); 400 401 // Get an array type for the string, according to C99 6.4.5. This includes 402 // the nul terminator character as well as the string length for pascal 403 // strings. 404 StrTy = Context.getConstantArrayType(StrTy, 405 llvm::APInt(32, Literal.GetNumStringChars()+1), 406 ArrayType::Normal, 0); 407 408 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 409 return Owned(StringLiteral::Create(Context, Literal.GetString(), 410 Literal.GetStringLength(), 411 Literal.AnyWide, StrTy, 412 &StringTokLocs[0], 413 StringTokLocs.size())); 414} 415 416/// ShouldSnapshotBlockValueReference - Return true if a reference inside of 417/// CurBlock to VD should cause it to be snapshotted (as we do for auto 418/// variables defined outside the block) or false if this is not needed (e.g. 419/// for values inside the block or for globals). 420/// 421/// This also keeps the 'hasBlockDeclRefExprs' in the BlockScopeInfo records 422/// up-to-date. 423/// 424static bool ShouldSnapshotBlockValueReference(Sema &S, BlockScopeInfo *CurBlock, 425 ValueDecl *VD) { 426 // If the value is defined inside the block, we couldn't snapshot it even if 427 // we wanted to. 428 if (CurBlock->TheDecl == VD->getDeclContext()) 429 return false; 430 431 // If this is an enum constant or function, it is constant, don't snapshot. 432 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD)) 433 return false; 434 435 // If this is a reference to an extern, static, or global variable, no need to 436 // snapshot it. 437 // FIXME: What about 'const' variables in C++? 438 if (const VarDecl *Var = dyn_cast<VarDecl>(VD)) 439 if (!Var->hasLocalStorage()) 440 return false; 441 442 // Blocks that have these can't be constant. 443 CurBlock->hasBlockDeclRefExprs = true; 444 445 // If we have nested blocks, the decl may be declared in an outer block (in 446 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may 447 // be defined outside all of the current blocks (in which case the blocks do 448 // all get the bit). Walk the nesting chain. 449 for (unsigned I = S.FunctionScopes.size() - 1; I; --I) { 450 BlockScopeInfo *NextBlock = dyn_cast<BlockScopeInfo>(S.FunctionScopes[I]); 451 452 if (!NextBlock) 453 continue; 454 455 // If we found the defining block for the variable, don't mark the block as 456 // having a reference outside it. 457 if (NextBlock->TheDecl == VD->getDeclContext()) 458 break; 459 460 // Otherwise, the DeclRef from the inner block causes the outer one to need 461 // a snapshot as well. 462 NextBlock->hasBlockDeclRefExprs = true; 463 } 464 465 return true; 466} 467 468 469ExprResult 470Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc, 471 const CXXScopeSpec *SS) { 472 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 473 return BuildDeclRefExpr(D, Ty, NameInfo, SS); 474} 475 476/// BuildDeclRefExpr - Build a DeclRefExpr. 477ExprResult 478Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, 479 const DeclarationNameInfo &NameInfo, 480 const CXXScopeSpec *SS) { 481 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) { 482 Diag(NameInfo.getLoc(), 483 diag::err_auto_variable_cannot_appear_in_own_initializer) 484 << D->getDeclName(); 485 return ExprError(); 486 } 487 488 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 489 if (isa<NonTypeTemplateParmDecl>(VD)) { 490 // Non-type template parameters can be referenced anywhere they are 491 // visible. 492 Ty = Ty.getNonLValueExprType(Context); 493 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { 494 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) { 495 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) { 496 Diag(NameInfo.getLoc(), 497 diag::err_reference_to_local_var_in_enclosing_function) 498 << D->getIdentifier() << FD->getDeclName(); 499 Diag(D->getLocation(), diag::note_local_variable_declared_here) 500 << D->getIdentifier(); 501 return ExprError(); 502 } 503 } 504 } 505 } 506 507 MarkDeclarationReferenced(NameInfo.getLoc(), D); 508 509 return Owned(DeclRefExpr::Create(Context, 510 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0, 511 SS? SS->getRange() : SourceRange(), 512 D, NameInfo, Ty)); 513} 514 515/// \brief Given a field that represents a member of an anonymous 516/// struct/union, build the path from that field's context to the 517/// actual member. 518/// 519/// Construct the sequence of field member references we'll have to 520/// perform to get to the field in the anonymous union/struct. The 521/// list of members is built from the field outward, so traverse it 522/// backwards to go from an object in the current context to the field 523/// we found. 524/// 525/// \returns The variable from which the field access should begin, 526/// for an anonymous struct/union that is not a member of another 527/// class. Otherwise, returns NULL. 528VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field, 529 llvm::SmallVectorImpl<FieldDecl *> &Path) { 530 assert(Field->getDeclContext()->isRecord() && 531 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion() 532 && "Field must be stored inside an anonymous struct or union"); 533 534 Path.push_back(Field); 535 VarDecl *BaseObject = 0; 536 DeclContext *Ctx = Field->getDeclContext(); 537 do { 538 RecordDecl *Record = cast<RecordDecl>(Ctx); 539 ValueDecl *AnonObject = Record->getAnonymousStructOrUnionObject(); 540 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject)) 541 Path.push_back(AnonField); 542 else { 543 BaseObject = cast<VarDecl>(AnonObject); 544 break; 545 } 546 Ctx = Ctx->getParent(); 547 } while (Ctx->isRecord() && 548 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()); 549 550 return BaseObject; 551} 552 553ExprResult 554Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc, 555 FieldDecl *Field, 556 Expr *BaseObjectExpr, 557 SourceLocation OpLoc) { 558 llvm::SmallVector<FieldDecl *, 4> AnonFields; 559 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field, 560 AnonFields); 561 562 // Build the expression that refers to the base object, from 563 // which we will build a sequence of member references to each 564 // of the anonymous union objects and, eventually, the field we 565 // found via name lookup. 566 bool BaseObjectIsPointer = false; 567 Qualifiers BaseQuals; 568 if (BaseObject) { 569 // BaseObject is an anonymous struct/union variable (and is, 570 // therefore, not part of another non-anonymous record). 571 MarkDeclarationReferenced(Loc, BaseObject); 572 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(), 573 Loc); 574 BaseQuals 575 = Context.getCanonicalType(BaseObject->getType()).getQualifiers(); 576 } else if (BaseObjectExpr) { 577 // The caller provided the base object expression. Determine 578 // whether its a pointer and whether it adds any qualifiers to the 579 // anonymous struct/union fields we're looking into. 580 QualType ObjectType = BaseObjectExpr->getType(); 581 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) { 582 BaseObjectIsPointer = true; 583 ObjectType = ObjectPtr->getPointeeType(); 584 } 585 BaseQuals 586 = Context.getCanonicalType(ObjectType).getQualifiers(); 587 } else { 588 // We've found a member of an anonymous struct/union that is 589 // inside a non-anonymous struct/union, so in a well-formed 590 // program our base object expression is "this". 591 DeclContext *DC = getFunctionLevelDeclContext(); 592 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 593 if (!MD->isStatic()) { 594 QualType AnonFieldType 595 = Context.getTagDeclType( 596 cast<RecordDecl>(AnonFields.back()->getDeclContext())); 597 QualType ThisType = Context.getTagDeclType(MD->getParent()); 598 if ((Context.getCanonicalType(AnonFieldType) 599 == Context.getCanonicalType(ThisType)) || 600 IsDerivedFrom(ThisType, AnonFieldType)) { 601 // Our base object expression is "this". 602 BaseObjectExpr = new (Context) CXXThisExpr(Loc, 603 MD->getThisType(Context), 604 /*isImplicit=*/true); 605 BaseObjectIsPointer = true; 606 } 607 } else { 608 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method) 609 << Field->getDeclName()); 610 } 611 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers()); 612 } 613 614 if (!BaseObjectExpr) 615 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use) 616 << Field->getDeclName()); 617 } 618 619 // Build the implicit member references to the field of the 620 // anonymous struct/union. 621 Expr *Result = BaseObjectExpr; 622 Qualifiers ResultQuals = BaseQuals; 623 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator 624 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend(); 625 FI != FIEnd; ++FI) { 626 QualType MemberType = (*FI)->getType(); 627 Qualifiers MemberTypeQuals = 628 Context.getCanonicalType(MemberType).getQualifiers(); 629 630 // CVR attributes from the base are picked up by members, 631 // except that 'mutable' members don't pick up 'const'. 632 if ((*FI)->isMutable()) 633 ResultQuals.removeConst(); 634 635 // GC attributes are never picked up by members. 636 ResultQuals.removeObjCGCAttr(); 637 638 // TR 18037 does not allow fields to be declared with address spaces. 639 assert(!MemberTypeQuals.hasAddressSpace()); 640 641 Qualifiers NewQuals = ResultQuals + MemberTypeQuals; 642 if (NewQuals != MemberTypeQuals) 643 MemberType = Context.getQualifiedType(MemberType, NewQuals); 644 645 MarkDeclarationReferenced(Loc, *FI); 646 PerformObjectMemberConversion(Result, /*FIXME:Qualifier=*/0, *FI, *FI); 647 // FIXME: Might this end up being a qualified name? 648 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI, 649 OpLoc, MemberType); 650 BaseObjectIsPointer = false; 651 ResultQuals = NewQuals; 652 } 653 654 return Owned(Result); 655} 656 657/// Decomposes the given name into a DeclarationNameInfo, its location, and 658/// possibly a list of template arguments. 659/// 660/// If this produces template arguments, it is permitted to call 661/// DecomposeTemplateName. 662/// 663/// This actually loses a lot of source location information for 664/// non-standard name kinds; we should consider preserving that in 665/// some way. 666static void DecomposeUnqualifiedId(Sema &SemaRef, 667 const UnqualifiedId &Id, 668 TemplateArgumentListInfo &Buffer, 669 DeclarationNameInfo &NameInfo, 670 const TemplateArgumentListInfo *&TemplateArgs) { 671 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 672 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 673 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 674 675 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef, 676 Id.TemplateId->getTemplateArgs(), 677 Id.TemplateId->NumArgs); 678 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer); 679 TemplateArgsPtr.release(); 680 681 TemplateName TName = Id.TemplateId->Template.get(); 682 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 683 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc); 684 TemplateArgs = &Buffer; 685 } else { 686 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id); 687 TemplateArgs = 0; 688 } 689} 690 691/// Determines whether the given record is "fully-formed" at the given 692/// location, i.e. whether a qualified lookup into it is assured of 693/// getting consistent results already. 694static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) { 695 if (!Record->hasDefinition()) 696 return false; 697 698 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(), 699 E = Record->bases_end(); I != E; ++I) { 700 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType()); 701 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>(); 702 if (!BaseRT) return false; 703 704 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl()); 705 if (!BaseRecord->hasDefinition() || 706 !IsFullyFormedScope(SemaRef, BaseRecord)) 707 return false; 708 } 709 710 return true; 711} 712 713/// Determines if the given class is provably not derived from all of 714/// the prospective base classes. 715static bool IsProvablyNotDerivedFrom(Sema &SemaRef, 716 CXXRecordDecl *Record, 717 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) { 718 if (Bases.count(Record->getCanonicalDecl())) 719 return false; 720 721 RecordDecl *RD = Record->getDefinition(); 722 if (!RD) return false; 723 Record = cast<CXXRecordDecl>(RD); 724 725 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(), 726 E = Record->bases_end(); I != E; ++I) { 727 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType()); 728 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>(); 729 if (!BaseRT) return false; 730 731 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl()); 732 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases)) 733 return false; 734 } 735 736 return true; 737} 738 739enum IMAKind { 740 /// The reference is definitely not an instance member access. 741 IMA_Static, 742 743 /// The reference may be an implicit instance member access. 744 IMA_Mixed, 745 746 /// The reference may be to an instance member, but it is invalid if 747 /// so, because the context is not an instance method. 748 IMA_Mixed_StaticContext, 749 750 /// The reference may be to an instance member, but it is invalid if 751 /// so, because the context is from an unrelated class. 752 IMA_Mixed_Unrelated, 753 754 /// The reference is definitely an implicit instance member access. 755 IMA_Instance, 756 757 /// The reference may be to an unresolved using declaration. 758 IMA_Unresolved, 759 760 /// The reference may be to an unresolved using declaration and the 761 /// context is not an instance method. 762 IMA_Unresolved_StaticContext, 763 764 /// The reference is to a member of an anonymous structure in a 765 /// non-class context. 766 IMA_AnonymousMember, 767 768 /// All possible referrents are instance members and the current 769 /// context is not an instance method. 770 IMA_Error_StaticContext, 771 772 /// All possible referrents are instance members of an unrelated 773 /// class. 774 IMA_Error_Unrelated 775}; 776 777/// The given lookup names class member(s) and is not being used for 778/// an address-of-member expression. Classify the type of access 779/// according to whether it's possible that this reference names an 780/// instance member. This is best-effort; it is okay to 781/// conservatively answer "yes", in which case some errors will simply 782/// not be caught until template-instantiation. 783static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef, 784 const LookupResult &R) { 785 assert(!R.empty() && (*R.begin())->isCXXClassMember()); 786 787 DeclContext *DC = SemaRef.getFunctionLevelDeclContext(); 788 bool isStaticContext = 789 (!isa<CXXMethodDecl>(DC) || 790 cast<CXXMethodDecl>(DC)->isStatic()); 791 792 if (R.isUnresolvableResult()) 793 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved; 794 795 // Collect all the declaring classes of instance members we find. 796 bool hasNonInstance = false; 797 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes; 798 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 799 NamedDecl *D = *I; 800 if (D->isCXXInstanceMember()) { 801 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext()); 802 803 // If this is a member of an anonymous record, move out to the 804 // innermost non-anonymous struct or union. If there isn't one, 805 // that's a special case. 806 while (R->isAnonymousStructOrUnion()) { 807 R = dyn_cast<CXXRecordDecl>(R->getParent()); 808 if (!R) return IMA_AnonymousMember; 809 } 810 Classes.insert(R->getCanonicalDecl()); 811 } 812 else 813 hasNonInstance = true; 814 } 815 816 // If we didn't find any instance members, it can't be an implicit 817 // member reference. 818 if (Classes.empty()) 819 return IMA_Static; 820 821 // If the current context is not an instance method, it can't be 822 // an implicit member reference. 823 if (isStaticContext) 824 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext); 825 826 // If we can prove that the current context is unrelated to all the 827 // declaring classes, it can't be an implicit member reference (in 828 // which case it's an error if any of those members are selected). 829 if (IsProvablyNotDerivedFrom(SemaRef, 830 cast<CXXMethodDecl>(DC)->getParent(), 831 Classes)) 832 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated); 833 834 return (hasNonInstance ? IMA_Mixed : IMA_Instance); 835} 836 837/// Diagnose a reference to a field with no object available. 838static void DiagnoseInstanceReference(Sema &SemaRef, 839 const CXXScopeSpec &SS, 840 const LookupResult &R) { 841 SourceLocation Loc = R.getNameLoc(); 842 SourceRange Range(Loc); 843 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin()); 844 845 if (R.getAsSingle<FieldDecl>()) { 846 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) { 847 if (MD->isStatic()) { 848 // "invalid use of member 'x' in static member function" 849 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method) 850 << Range << R.getLookupName(); 851 return; 852 } 853 } 854 855 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use) 856 << R.getLookupName() << Range; 857 return; 858 } 859 860 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range; 861} 862 863/// Diagnose an empty lookup. 864/// 865/// \return false if new lookup candidates were found 866bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 867 CorrectTypoContext CTC) { 868 DeclarationName Name = R.getLookupName(); 869 870 unsigned diagnostic = diag::err_undeclared_var_use; 871 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 872 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 873 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 874 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 875 diagnostic = diag::err_undeclared_use; 876 diagnostic_suggest = diag::err_undeclared_use_suggest; 877 } 878 879 // If the original lookup was an unqualified lookup, fake an 880 // unqualified lookup. This is useful when (for example) the 881 // original lookup would not have found something because it was a 882 // dependent name. 883 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0; 884 DC; DC = DC->getParent()) { 885 if (isa<CXXRecordDecl>(DC)) { 886 LookupQualifiedName(R, DC); 887 888 if (!R.empty()) { 889 // Don't give errors about ambiguities in this lookup. 890 R.suppressDiagnostics(); 891 892 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 893 bool isInstance = CurMethod && 894 CurMethod->isInstance() && 895 DC == CurMethod->getParent(); 896 897 // Give a code modification hint to insert 'this->'. 898 // TODO: fixit for inserting 'Base<T>::' in the other cases. 899 // Actually quite difficult! 900 if (isInstance) { 901 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 902 CallsUndergoingInstantiation.back()->getCallee()); 903 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>( 904 CurMethod->getInstantiatedFromMemberFunction()); 905 if (DepMethod) { 906 Diag(R.getNameLoc(), diagnostic) << Name 907 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 908 QualType DepThisType = DepMethod->getThisType(Context); 909 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 910 R.getNameLoc(), DepThisType, false); 911 TemplateArgumentListInfo TList; 912 if (ULE->hasExplicitTemplateArgs()) 913 ULE->copyTemplateArgumentsInto(TList); 914 CXXDependentScopeMemberExpr *DepExpr = 915 CXXDependentScopeMemberExpr::Create( 916 Context, DepThis, DepThisType, true, SourceLocation(), 917 ULE->getQualifier(), ULE->getQualifierRange(), NULL, 918 R.getLookupNameInfo(), &TList); 919 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 920 } else { 921 // FIXME: we should be able to handle this case too. It is correct 922 // to add this-> here. This is a workaround for PR7947. 923 Diag(R.getNameLoc(), diagnostic) << Name; 924 } 925 } else { 926 Diag(R.getNameLoc(), diagnostic) << Name; 927 } 928 929 // Do we really want to note all of these? 930 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 931 Diag((*I)->getLocation(), diag::note_dependent_var_use); 932 933 // Tell the callee to try to recover. 934 return false; 935 } 936 937 R.clear(); 938 } 939 } 940 941 // We didn't find anything, so try to correct for a typo. 942 DeclarationName Corrected; 943 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) { 944 if (!R.empty()) { 945 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) { 946 if (SS.isEmpty()) 947 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName() 948 << FixItHint::CreateReplacement(R.getNameLoc(), 949 R.getLookupName().getAsString()); 950 else 951 Diag(R.getNameLoc(), diag::err_no_member_suggest) 952 << Name << computeDeclContext(SS, false) << R.getLookupName() 953 << SS.getRange() 954 << FixItHint::CreateReplacement(R.getNameLoc(), 955 R.getLookupName().getAsString()); 956 if (NamedDecl *ND = R.getAsSingle<NamedDecl>()) 957 Diag(ND->getLocation(), diag::note_previous_decl) 958 << ND->getDeclName(); 959 960 // Tell the callee to try to recover. 961 return false; 962 } 963 964 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) { 965 // FIXME: If we ended up with a typo for a type name or 966 // Objective-C class name, we're in trouble because the parser 967 // is in the wrong place to recover. Suggest the typo 968 // correction, but don't make it a fix-it since we're not going 969 // to recover well anyway. 970 if (SS.isEmpty()) 971 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName(); 972 else 973 Diag(R.getNameLoc(), diag::err_no_member_suggest) 974 << Name << computeDeclContext(SS, false) << R.getLookupName() 975 << SS.getRange(); 976 977 // Don't try to recover; it won't work. 978 return true; 979 } 980 } else { 981 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 982 // because we aren't able to recover. 983 if (SS.isEmpty()) 984 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected; 985 else 986 Diag(R.getNameLoc(), diag::err_no_member_suggest) 987 << Name << computeDeclContext(SS, false) << Corrected 988 << SS.getRange(); 989 return true; 990 } 991 R.clear(); 992 } 993 994 // Emit a special diagnostic for failed member lookups. 995 // FIXME: computing the declaration context might fail here (?) 996 if (!SS.isEmpty()) { 997 Diag(R.getNameLoc(), diag::err_no_member) 998 << Name << computeDeclContext(SS, false) 999 << SS.getRange(); 1000 return true; 1001 } 1002 1003 // Give up, we can't recover. 1004 Diag(R.getNameLoc(), diagnostic) << Name; 1005 return true; 1006} 1007 1008static ObjCPropertyDecl *OkToSynthesizeProvisionalIvar(Sema &SemaRef, 1009 IdentifierInfo *II, 1010 SourceLocation NameLoc) { 1011 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl(); 1012 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface(); 1013 if (!IDecl) 1014 return 0; 1015 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation(); 1016 if (!ClassImpDecl) 1017 return 0; 1018 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II); 1019 if (!property) 1020 return 0; 1021 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) 1022 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) 1023 return 0; 1024 return property; 1025} 1026 1027static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef, 1028 LookupResult &Lookup, 1029 IdentifierInfo *II, 1030 SourceLocation NameLoc) { 1031 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl(); 1032 bool LookForIvars; 1033 if (Lookup.empty()) 1034 LookForIvars = true; 1035 else if (CurMeth->isClassMethod()) 1036 LookForIvars = false; 1037 else 1038 LookForIvars = (Lookup.isSingleResult() && 1039 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 1040 if (!LookForIvars) 1041 return 0; 1042 1043 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface(); 1044 if (!IDecl) 1045 return 0; 1046 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation(); 1047 if (!ClassImpDecl) 1048 return 0; 1049 bool DynamicImplSeen = false; 1050 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II); 1051 if (!property) 1052 return 0; 1053 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) 1054 DynamicImplSeen = 1055 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic); 1056 if (!DynamicImplSeen) { 1057 QualType PropType = SemaRef.Context.getCanonicalType(property->getType()); 1058 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl, 1059 NameLoc, 1060 II, PropType, /*Dinfo=*/0, 1061 ObjCIvarDecl::Protected, 1062 (Expr *)0, true); 1063 ClassImpDecl->addDecl(Ivar); 1064 IDecl->makeDeclVisibleInContext(Ivar, false); 1065 property->setPropertyIvarDecl(Ivar); 1066 return Ivar; 1067 } 1068 return 0; 1069} 1070 1071ExprResult Sema::ActOnIdExpression(Scope *S, 1072 CXXScopeSpec &SS, 1073 UnqualifiedId &Id, 1074 bool HasTrailingLParen, 1075 bool isAddressOfOperand) { 1076 assert(!(isAddressOfOperand && HasTrailingLParen) && 1077 "cannot be direct & operand and have a trailing lparen"); 1078 1079 if (SS.isInvalid()) 1080 return ExprError(); 1081 1082 TemplateArgumentListInfo TemplateArgsBuffer; 1083 1084 // Decompose the UnqualifiedId into the following data. 1085 DeclarationNameInfo NameInfo; 1086 const TemplateArgumentListInfo *TemplateArgs; 1087 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 1088 1089 DeclarationName Name = NameInfo.getName(); 1090 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1091 SourceLocation NameLoc = NameInfo.getLoc(); 1092 1093 // C++ [temp.dep.expr]p3: 1094 // An id-expression is type-dependent if it contains: 1095 // -- an identifier that was declared with a dependent type, 1096 // (note: handled after lookup) 1097 // -- a template-id that is dependent, 1098 // (note: handled in BuildTemplateIdExpr) 1099 // -- a conversion-function-id that specifies a dependent type, 1100 // -- a nested-name-specifier that contains a class-name that 1101 // names a dependent type. 1102 // Determine whether this is a member of an unknown specialization; 1103 // we need to handle these differently. 1104 bool DependentID = false; 1105 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 1106 Name.getCXXNameType()->isDependentType()) { 1107 DependentID = true; 1108 } else if (SS.isSet()) { 1109 DeclContext *DC = computeDeclContext(SS, false); 1110 if (DC) { 1111 if (RequireCompleteDeclContext(SS, DC)) 1112 return ExprError(); 1113 // FIXME: We should be checking whether DC is the current instantiation. 1114 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) 1115 DependentID = !IsFullyFormedScope(*this, RD); 1116 } else { 1117 DependentID = true; 1118 } 1119 } 1120 1121 if (DependentID) { 1122 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand, 1123 TemplateArgs); 1124 } 1125 bool IvarLookupFollowUp = false; 1126 // Perform the required lookup. 1127 LookupResult R(*this, NameInfo, LookupOrdinaryName); 1128 if (TemplateArgs) { 1129 // Lookup the template name again to correctly establish the context in 1130 // which it was found. This is really unfortunate as we already did the 1131 // lookup to determine that it was a template name in the first place. If 1132 // this becomes a performance hit, we can work harder to preserve those 1133 // results until we get here but it's likely not worth it. 1134 bool MemberOfUnknownSpecialization; 1135 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 1136 MemberOfUnknownSpecialization); 1137 } else { 1138 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl()); 1139 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 1140 1141 // If this reference is in an Objective-C method, then we need to do 1142 // some special Objective-C lookup, too. 1143 if (IvarLookupFollowUp) { 1144 ExprResult E(LookupInObjCMethod(R, S, II, true)); 1145 if (E.isInvalid()) 1146 return ExprError(); 1147 1148 Expr *Ex = E.takeAs<Expr>(); 1149 if (Ex) return Owned(Ex); 1150 // Synthesize ivars lazily 1151 if (getLangOptions().ObjCNonFragileABI2) { 1152 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) 1153 return ActOnIdExpression(S, SS, Id, HasTrailingLParen, 1154 isAddressOfOperand); 1155 } 1156 // for further use, this must be set to false if in class method. 1157 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod(); 1158 } 1159 } 1160 1161 if (R.isAmbiguous()) 1162 return ExprError(); 1163 1164 // Determine whether this name might be a candidate for 1165 // argument-dependent lookup. 1166 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 1167 1168 if (R.empty() && !ADL) { 1169 // Otherwise, this could be an implicitly declared function reference (legal 1170 // in C90, extension in C99, forbidden in C++). 1171 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) { 1172 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 1173 if (D) R.addDecl(D); 1174 } 1175 1176 // If this name wasn't predeclared and if this is not a function 1177 // call, diagnose the problem. 1178 if (R.empty()) { 1179 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown)) 1180 return ExprError(); 1181 1182 assert(!R.empty() && 1183 "DiagnoseEmptyLookup returned false but added no results"); 1184 1185 // If we found an Objective-C instance variable, let 1186 // LookupInObjCMethod build the appropriate expression to 1187 // reference the ivar. 1188 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 1189 R.clear(); 1190 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 1191 assert(E.isInvalid() || E.get()); 1192 return move(E); 1193 } 1194 } 1195 } 1196 1197 // This is guaranteed from this point on. 1198 assert(!R.empty() || ADL); 1199 1200 if (VarDecl *Var = R.getAsSingle<VarDecl>()) { 1201 if (getLangOptions().ObjCNonFragileABI && IvarLookupFollowUp && 1202 !getLangOptions().ObjCNonFragileABI2 && 1203 Var->isFileVarDecl()) { 1204 ObjCPropertyDecl *Property = 1205 OkToSynthesizeProvisionalIvar(*this, II, NameLoc); 1206 if (Property) { 1207 Diag(NameLoc, diag::warn_ivar_variable_conflict) << Var->getDeclName(); 1208 Diag(Property->getLocation(), diag::note_property_declare); 1209 Diag(Var->getLocation(), diag::note_global_declared_at); 1210 } 1211 } 1212 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) { 1213 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) { 1214 // C99 DR 316 says that, if a function type comes from a 1215 // function definition (without a prototype), that type is only 1216 // used for checking compatibility. Therefore, when referencing 1217 // the function, we pretend that we don't have the full function 1218 // type. 1219 if (DiagnoseUseOfDecl(Func, NameLoc)) 1220 return ExprError(); 1221 1222 QualType T = Func->getType(); 1223 QualType NoProtoType = T; 1224 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>()) 1225 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType(), 1226 Proto->getExtInfo()); 1227 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS); 1228 } 1229 } 1230 1231 // Check whether this might be a C++ implicit instance member access. 1232 // C++ [class.mfct.non-static]p3: 1233 // When an id-expression that is not part of a class member access 1234 // syntax and not used to form a pointer to member is used in the 1235 // body of a non-static member function of class X, if name lookup 1236 // resolves the name in the id-expression to a non-static non-type 1237 // member of some class C, the id-expression is transformed into a 1238 // class member access expression using (*this) as the 1239 // postfix-expression to the left of the . operator. 1240 // 1241 // But we don't actually need to do this for '&' operands if R 1242 // resolved to a function or overloaded function set, because the 1243 // expression is ill-formed if it actually works out to be a 1244 // non-static member function: 1245 // 1246 // C++ [expr.ref]p4: 1247 // Otherwise, if E1.E2 refers to a non-static member function. . . 1248 // [t]he expression can be used only as the left-hand operand of a 1249 // member function call. 1250 // 1251 // There are other safeguards against such uses, but it's important 1252 // to get this right here so that we don't end up making a 1253 // spuriously dependent expression if we're inside a dependent 1254 // instance method. 1255 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 1256 bool MightBeImplicitMember; 1257 if (!isAddressOfOperand) 1258 MightBeImplicitMember = true; 1259 else if (!SS.isEmpty()) 1260 MightBeImplicitMember = false; 1261 else if (R.isOverloadedResult()) 1262 MightBeImplicitMember = false; 1263 else if (R.isUnresolvableResult()) 1264 MightBeImplicitMember = true; 1265 else 1266 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()); 1267 1268 if (MightBeImplicitMember) 1269 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs); 1270 } 1271 1272 if (TemplateArgs) 1273 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs); 1274 1275 return BuildDeclarationNameExpr(SS, R, ADL); 1276} 1277 1278/// Builds an expression which might be an implicit member expression. 1279ExprResult 1280Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, 1281 LookupResult &R, 1282 const TemplateArgumentListInfo *TemplateArgs) { 1283 switch (ClassifyImplicitMemberAccess(*this, R)) { 1284 case IMA_Instance: 1285 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true); 1286 1287 case IMA_AnonymousMember: 1288 assert(R.isSingleResult()); 1289 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(), 1290 R.getAsSingle<FieldDecl>()); 1291 1292 case IMA_Mixed: 1293 case IMA_Mixed_Unrelated: 1294 case IMA_Unresolved: 1295 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false); 1296 1297 case IMA_Static: 1298 case IMA_Mixed_StaticContext: 1299 case IMA_Unresolved_StaticContext: 1300 if (TemplateArgs) 1301 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs); 1302 return BuildDeclarationNameExpr(SS, R, false); 1303 1304 case IMA_Error_StaticContext: 1305 case IMA_Error_Unrelated: 1306 DiagnoseInstanceReference(*this, SS, R); 1307 return ExprError(); 1308 } 1309 1310 llvm_unreachable("unexpected instance member access kind"); 1311 return ExprError(); 1312} 1313 1314/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 1315/// declaration name, generally during template instantiation. 1316/// There's a large number of things which don't need to be done along 1317/// this path. 1318ExprResult 1319Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 1320 const DeclarationNameInfo &NameInfo) { 1321 DeclContext *DC; 1322 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext()) 1323 return BuildDependentDeclRefExpr(SS, NameInfo, 0); 1324 1325 if (RequireCompleteDeclContext(SS, DC)) 1326 return ExprError(); 1327 1328 LookupResult R(*this, NameInfo, LookupOrdinaryName); 1329 LookupQualifiedName(R, DC); 1330 1331 if (R.isAmbiguous()) 1332 return ExprError(); 1333 1334 if (R.empty()) { 1335 Diag(NameInfo.getLoc(), diag::err_no_member) 1336 << NameInfo.getName() << DC << SS.getRange(); 1337 return ExprError(); 1338 } 1339 1340 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false); 1341} 1342 1343/// LookupInObjCMethod - The parser has read a name in, and Sema has 1344/// detected that we're currently inside an ObjC method. Perform some 1345/// additional lookup. 1346/// 1347/// Ideally, most of this would be done by lookup, but there's 1348/// actually quite a lot of extra work involved. 1349/// 1350/// Returns a null sentinel to indicate trivial success. 1351ExprResult 1352Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 1353 IdentifierInfo *II, bool AllowBuiltinCreation) { 1354 SourceLocation Loc = Lookup.getNameLoc(); 1355 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 1356 1357 // There are two cases to handle here. 1) scoped lookup could have failed, 1358 // in which case we should look for an ivar. 2) scoped lookup could have 1359 // found a decl, but that decl is outside the current instance method (i.e. 1360 // a global variable). In these two cases, we do a lookup for an ivar with 1361 // this name, if the lookup sucedes, we replace it our current decl. 1362 1363 // If we're in a class method, we don't normally want to look for 1364 // ivars. But if we don't find anything else, and there's an 1365 // ivar, that's an error. 1366 bool IsClassMethod = CurMethod->isClassMethod(); 1367 1368 bool LookForIvars; 1369 if (Lookup.empty()) 1370 LookForIvars = true; 1371 else if (IsClassMethod) 1372 LookForIvars = false; 1373 else 1374 LookForIvars = (Lookup.isSingleResult() && 1375 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 1376 ObjCInterfaceDecl *IFace = 0; 1377 if (LookForIvars) { 1378 IFace = CurMethod->getClassInterface(); 1379 ObjCInterfaceDecl *ClassDeclared; 1380 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 1381 // Diagnose using an ivar in a class method. 1382 if (IsClassMethod) 1383 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 1384 << IV->getDeclName()); 1385 1386 // If we're referencing an invalid decl, just return this as a silent 1387 // error node. The error diagnostic was already emitted on the decl. 1388 if (IV->isInvalidDecl()) 1389 return ExprError(); 1390 1391 // Check if referencing a field with __attribute__((deprecated)). 1392 if (DiagnoseUseOfDecl(IV, Loc)) 1393 return ExprError(); 1394 1395 // Diagnose the use of an ivar outside of the declaring class. 1396 if (IV->getAccessControl() == ObjCIvarDecl::Private && 1397 ClassDeclared != IFace) 1398 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 1399 1400 // FIXME: This should use a new expr for a direct reference, don't 1401 // turn this into Self->ivar, just return a BareIVarExpr or something. 1402 IdentifierInfo &II = Context.Idents.get("self"); 1403 UnqualifiedId SelfName; 1404 SelfName.setIdentifier(&II, SourceLocation()); 1405 CXXScopeSpec SelfScopeSpec; 1406 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, 1407 SelfName, false, false); 1408 if (SelfExpr.isInvalid()) 1409 return ExprError(); 1410 1411 MarkDeclarationReferenced(Loc, IV); 1412 return Owned(new (Context) 1413 ObjCIvarRefExpr(IV, IV->getType(), Loc, 1414 SelfExpr.takeAs<Expr>(), true, true)); 1415 } 1416 } else if (CurMethod->isInstanceMethod()) { 1417 // We should warn if a local variable hides an ivar. 1418 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 1419 ObjCInterfaceDecl *ClassDeclared; 1420 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 1421 if (IV->getAccessControl() != ObjCIvarDecl::Private || 1422 IFace == ClassDeclared) 1423 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 1424 } 1425 } 1426 1427 if (Lookup.empty() && II && AllowBuiltinCreation) { 1428 // FIXME. Consolidate this with similar code in LookupName. 1429 if (unsigned BuiltinID = II->getBuiltinID()) { 1430 if (!(getLangOptions().CPlusPlus && 1431 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 1432 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 1433 S, Lookup.isForRedeclaration(), 1434 Lookup.getNameLoc()); 1435 if (D) Lookup.addDecl(D); 1436 } 1437 } 1438 } 1439 // Sentinel value saying that we didn't do anything special. 1440 return Owned((Expr*) 0); 1441} 1442 1443/// \brief Cast a base object to a member's actual type. 1444/// 1445/// Logically this happens in three phases: 1446/// 1447/// * First we cast from the base type to the naming class. 1448/// The naming class is the class into which we were looking 1449/// when we found the member; it's the qualifier type if a 1450/// qualifier was provided, and otherwise it's the base type. 1451/// 1452/// * Next we cast from the naming class to the declaring class. 1453/// If the member we found was brought into a class's scope by 1454/// a using declaration, this is that class; otherwise it's 1455/// the class declaring the member. 1456/// 1457/// * Finally we cast from the declaring class to the "true" 1458/// declaring class of the member. This conversion does not 1459/// obey access control. 1460bool 1461Sema::PerformObjectMemberConversion(Expr *&From, 1462 NestedNameSpecifier *Qualifier, 1463 NamedDecl *FoundDecl, 1464 NamedDecl *Member) { 1465 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 1466 if (!RD) 1467 return false; 1468 1469 QualType DestRecordType; 1470 QualType DestType; 1471 QualType FromRecordType; 1472 QualType FromType = From->getType(); 1473 bool PointerConversions = false; 1474 if (isa<FieldDecl>(Member)) { 1475 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 1476 1477 if (FromType->getAs<PointerType>()) { 1478 DestType = Context.getPointerType(DestRecordType); 1479 FromRecordType = FromType->getPointeeType(); 1480 PointerConversions = true; 1481 } else { 1482 DestType = DestRecordType; 1483 FromRecordType = FromType; 1484 } 1485 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 1486 if (Method->isStatic()) 1487 return false; 1488 1489 DestType = Method->getThisType(Context); 1490 DestRecordType = DestType->getPointeeType(); 1491 1492 if (FromType->getAs<PointerType>()) { 1493 FromRecordType = FromType->getPointeeType(); 1494 PointerConversions = true; 1495 } else { 1496 FromRecordType = FromType; 1497 DestType = DestRecordType; 1498 } 1499 } else { 1500 // No conversion necessary. 1501 return false; 1502 } 1503 1504 if (DestType->isDependentType() || FromType->isDependentType()) 1505 return false; 1506 1507 // If the unqualified types are the same, no conversion is necessary. 1508 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 1509 return false; 1510 1511 SourceRange FromRange = From->getSourceRange(); 1512 SourceLocation FromLoc = FromRange.getBegin(); 1513 1514 ExprValueKind VK = CastCategory(From); 1515 1516 // C++ [class.member.lookup]p8: 1517 // [...] Ambiguities can often be resolved by qualifying a name with its 1518 // class name. 1519 // 1520 // If the member was a qualified name and the qualified referred to a 1521 // specific base subobject type, we'll cast to that intermediate type 1522 // first and then to the object in which the member is declared. That allows 1523 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 1524 // 1525 // class Base { public: int x; }; 1526 // class Derived1 : public Base { }; 1527 // class Derived2 : public Base { }; 1528 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 1529 // 1530 // void VeryDerived::f() { 1531 // x = 17; // error: ambiguous base subobjects 1532 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 1533 // } 1534 if (Qualifier) { 1535 QualType QType = QualType(Qualifier->getAsType(), 0); 1536 assert(!QType.isNull() && "lookup done with dependent qualifier?"); 1537 assert(QType->isRecordType() && "lookup done with non-record type"); 1538 1539 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 1540 1541 // In C++98, the qualifier type doesn't actually have to be a base 1542 // type of the object type, in which case we just ignore it. 1543 // Otherwise build the appropriate casts. 1544 if (IsDerivedFrom(FromRecordType, QRecordType)) { 1545 CXXCastPath BasePath; 1546 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 1547 FromLoc, FromRange, &BasePath)) 1548 return true; 1549 1550 if (PointerConversions) 1551 QType = Context.getPointerType(QType); 1552 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 1553 VK, &BasePath); 1554 1555 FromType = QType; 1556 FromRecordType = QRecordType; 1557 1558 // If the qualifier type was the same as the destination type, 1559 // we're done. 1560 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 1561 return false; 1562 } 1563 } 1564 1565 bool IgnoreAccess = false; 1566 1567 // If we actually found the member through a using declaration, cast 1568 // down to the using declaration's type. 1569 // 1570 // Pointer equality is fine here because only one declaration of a 1571 // class ever has member declarations. 1572 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 1573 assert(isa<UsingShadowDecl>(FoundDecl)); 1574 QualType URecordType = Context.getTypeDeclType( 1575 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 1576 1577 // We only need to do this if the naming-class to declaring-class 1578 // conversion is non-trivial. 1579 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 1580 assert(IsDerivedFrom(FromRecordType, URecordType)); 1581 CXXCastPath BasePath; 1582 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 1583 FromLoc, FromRange, &BasePath)) 1584 return true; 1585 1586 QualType UType = URecordType; 1587 if (PointerConversions) 1588 UType = Context.getPointerType(UType); 1589 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 1590 VK, &BasePath); 1591 FromType = UType; 1592 FromRecordType = URecordType; 1593 } 1594 1595 // We don't do access control for the conversion from the 1596 // declaring class to the true declaring class. 1597 IgnoreAccess = true; 1598 } 1599 1600 CXXCastPath BasePath; 1601 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 1602 FromLoc, FromRange, &BasePath, 1603 IgnoreAccess)) 1604 return true; 1605 1606 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 1607 VK, &BasePath); 1608 return false; 1609} 1610 1611/// \brief Build a MemberExpr AST node. 1612static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow, 1613 const CXXScopeSpec &SS, ValueDecl *Member, 1614 DeclAccessPair FoundDecl, 1615 const DeclarationNameInfo &MemberNameInfo, 1616 QualType Ty, 1617 const TemplateArgumentListInfo *TemplateArgs = 0) { 1618 NestedNameSpecifier *Qualifier = 0; 1619 SourceRange QualifierRange; 1620 if (SS.isSet()) { 1621 Qualifier = (NestedNameSpecifier *) SS.getScopeRep(); 1622 QualifierRange = SS.getRange(); 1623 } 1624 1625 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange, 1626 Member, FoundDecl, MemberNameInfo, 1627 TemplateArgs, Ty); 1628} 1629 1630/// Builds an implicit member access expression. The current context 1631/// is known to be an instance method, and the given unqualified lookup 1632/// set is known to contain only instance members, at least one of which 1633/// is from an appropriate type. 1634ExprResult 1635Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS, 1636 LookupResult &R, 1637 const TemplateArgumentListInfo *TemplateArgs, 1638 bool IsKnownInstance) { 1639 assert(!R.empty() && !R.isAmbiguous()); 1640 1641 SourceLocation Loc = R.getNameLoc(); 1642 1643 // We may have found a field within an anonymous union or struct 1644 // (C++ [class.union]). 1645 // FIXME: This needs to happen post-isImplicitMemberReference? 1646 // FIXME: template-ids inside anonymous structs? 1647 if (FieldDecl *FD = R.getAsSingle<FieldDecl>()) 1648 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion()) 1649 return BuildAnonymousStructUnionMemberReference(Loc, FD); 1650 1651 // If this is known to be an instance access, go ahead and build a 1652 // 'this' expression now. 1653 DeclContext *DC = getFunctionLevelDeclContext(); 1654 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context); 1655 Expr *This = 0; // null signifies implicit access 1656 if (IsKnownInstance) { 1657 SourceLocation Loc = R.getNameLoc(); 1658 if (SS.getRange().isValid()) 1659 Loc = SS.getRange().getBegin(); 1660 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true); 1661 } 1662 1663 return BuildMemberReferenceExpr(This, ThisType, 1664 /*OpLoc*/ SourceLocation(), 1665 /*IsArrow*/ true, 1666 SS, 1667 /*FirstQualifierInScope*/ 0, 1668 R, TemplateArgs); 1669} 1670 1671bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 1672 const LookupResult &R, 1673 bool HasTrailingLParen) { 1674 // Only when used directly as the postfix-expression of a call. 1675 if (!HasTrailingLParen) 1676 return false; 1677 1678 // Never if a scope specifier was provided. 1679 if (SS.isSet()) 1680 return false; 1681 1682 // Only in C++ or ObjC++. 1683 if (!getLangOptions().CPlusPlus) 1684 return false; 1685 1686 // Turn off ADL when we find certain kinds of declarations during 1687 // normal lookup: 1688 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 1689 NamedDecl *D = *I; 1690 1691 // C++0x [basic.lookup.argdep]p3: 1692 // -- a declaration of a class member 1693 // Since using decls preserve this property, we check this on the 1694 // original decl. 1695 if (D->isCXXClassMember()) 1696 return false; 1697 1698 // C++0x [basic.lookup.argdep]p3: 1699 // -- a block-scope function declaration that is not a 1700 // using-declaration 1701 // NOTE: we also trigger this for function templates (in fact, we 1702 // don't check the decl type at all, since all other decl types 1703 // turn off ADL anyway). 1704 if (isa<UsingShadowDecl>(D)) 1705 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 1706 else if (D->getDeclContext()->isFunctionOrMethod()) 1707 return false; 1708 1709 // C++0x [basic.lookup.argdep]p3: 1710 // -- a declaration that is neither a function or a function 1711 // template 1712 // And also for builtin functions. 1713 if (isa<FunctionDecl>(D)) { 1714 FunctionDecl *FDecl = cast<FunctionDecl>(D); 1715 1716 // But also builtin functions. 1717 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 1718 return false; 1719 } else if (!isa<FunctionTemplateDecl>(D)) 1720 return false; 1721 } 1722 1723 return true; 1724} 1725 1726 1727/// Diagnoses obvious problems with the use of the given declaration 1728/// as an expression. This is only actually called for lookups that 1729/// were not overloaded, and it doesn't promise that the declaration 1730/// will in fact be used. 1731static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 1732 if (isa<TypedefDecl>(D)) { 1733 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 1734 return true; 1735 } 1736 1737 if (isa<ObjCInterfaceDecl>(D)) { 1738 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 1739 return true; 1740 } 1741 1742 if (isa<NamespaceDecl>(D)) { 1743 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 1744 return true; 1745 } 1746 1747 return false; 1748} 1749 1750ExprResult 1751Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 1752 LookupResult &R, 1753 bool NeedsADL) { 1754 // If this is a single, fully-resolved result and we don't need ADL, 1755 // just build an ordinary singleton decl ref. 1756 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 1757 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), 1758 R.getFoundDecl()); 1759 1760 // We only need to check the declaration if there's exactly one 1761 // result, because in the overloaded case the results can only be 1762 // functions and function templates. 1763 if (R.isSingleResult() && 1764 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 1765 return ExprError(); 1766 1767 // Otherwise, just build an unresolved lookup expression. Suppress 1768 // any lookup-related diagnostics; we'll hash these out later, when 1769 // we've picked a target. 1770 R.suppressDiagnostics(); 1771 1772 bool Dependent 1773 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0); 1774 UnresolvedLookupExpr *ULE 1775 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(), 1776 (NestedNameSpecifier*) SS.getScopeRep(), 1777 SS.getRange(), R.getLookupNameInfo(), 1778 NeedsADL, R.isOverloadedResult(), 1779 R.begin(), R.end()); 1780 1781 return Owned(ULE); 1782} 1783 1784 1785/// \brief Complete semantic analysis for a reference to the given declaration. 1786ExprResult 1787Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 1788 const DeclarationNameInfo &NameInfo, 1789 NamedDecl *D) { 1790 assert(D && "Cannot refer to a NULL declaration"); 1791 assert(!isa<FunctionTemplateDecl>(D) && 1792 "Cannot refer unambiguously to a function template"); 1793 1794 SourceLocation Loc = NameInfo.getLoc(); 1795 if (CheckDeclInExpr(*this, Loc, D)) 1796 return ExprError(); 1797 1798 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 1799 // Specifically diagnose references to class templates that are missing 1800 // a template argument list. 1801 Diag(Loc, diag::err_template_decl_ref) 1802 << Template << SS.getRange(); 1803 Diag(Template->getLocation(), diag::note_template_decl_here); 1804 return ExprError(); 1805 } 1806 1807 // Make sure that we're referring to a value. 1808 ValueDecl *VD = dyn_cast<ValueDecl>(D); 1809 if (!VD) { 1810 Diag(Loc, diag::err_ref_non_value) 1811 << D << SS.getRange(); 1812 Diag(D->getLocation(), diag::note_declared_at); 1813 return ExprError(); 1814 } 1815 1816 // Check whether this declaration can be used. Note that we suppress 1817 // this check when we're going to perform argument-dependent lookup 1818 // on this function name, because this might not be the function 1819 // that overload resolution actually selects. 1820 if (DiagnoseUseOfDecl(VD, Loc)) 1821 return ExprError(); 1822 1823 // Only create DeclRefExpr's for valid Decl's. 1824 if (VD->isInvalidDecl()) 1825 return ExprError(); 1826 1827 // If the identifier reference is inside a block, and it refers to a value 1828 // that is outside the block, create a BlockDeclRefExpr instead of a 1829 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when 1830 // the block is formed. 1831 // 1832 // We do not do this for things like enum constants, global variables, etc, 1833 // as they do not get snapshotted. 1834 // 1835 if (getCurBlock() && 1836 ShouldSnapshotBlockValueReference(*this, getCurBlock(), VD)) { 1837 if (VD->getType().getTypePtr()->isVariablyModifiedType()) { 1838 Diag(Loc, diag::err_ref_vm_type); 1839 Diag(D->getLocation(), diag::note_declared_at); 1840 return ExprError(); 1841 } 1842 1843 if (VD->getType()->isArrayType()) { 1844 Diag(Loc, diag::err_ref_array_type); 1845 Diag(D->getLocation(), diag::note_declared_at); 1846 return ExprError(); 1847 } 1848 1849 MarkDeclarationReferenced(Loc, VD); 1850 QualType ExprTy = VD->getType().getNonReferenceType(); 1851 // The BlocksAttr indicates the variable is bound by-reference. 1852 if (VD->getAttr<BlocksAttr>()) 1853 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true)); 1854 // This is to record that a 'const' was actually synthesize and added. 1855 bool constAdded = !ExprTy.isConstQualified(); 1856 // Variable will be bound by-copy, make it const within the closure. 1857 1858 ExprTy.addConst(); 1859 QualType T = VD->getType(); 1860 BlockDeclRefExpr *BDRE = new (Context) BlockDeclRefExpr(VD, 1861 ExprTy, Loc, false, 1862 constAdded); 1863 if (getLangOptions().CPlusPlus) { 1864 if (!T->isDependentType() && !T->isReferenceType()) { 1865 Expr *E = new (Context) 1866 DeclRefExpr(const_cast<ValueDecl*>(BDRE->getDecl()), T, 1867 SourceLocation()); 1868 1869 ExprResult Res = PerformCopyInitialization( 1870 InitializedEntity::InitializeBlock(VD->getLocation(), 1871 T, false), 1872 SourceLocation(), 1873 Owned(E)); 1874 if (!Res.isInvalid()) { 1875 Res = MaybeCreateCXXExprWithTemporaries(Res.get()); 1876 Expr *Init = Res.takeAs<Expr>(); 1877 BDRE->setCopyConstructorExpr(Init); 1878 } 1879 } 1880 } 1881 return Owned(BDRE); 1882 } 1883 // If this reference is not in a block or if the referenced variable is 1884 // within the block, create a normal DeclRefExpr. 1885 1886 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), 1887 NameInfo, &SS); 1888} 1889 1890ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, 1891 tok::TokenKind Kind) { 1892 PredefinedExpr::IdentType IT; 1893 1894 switch (Kind) { 1895 default: assert(0 && "Unknown simple primary expr!"); 1896 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 1897 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 1898 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 1899 } 1900 1901 // Pre-defined identifiers are of type char[x], where x is the length of the 1902 // string. 1903 1904 Decl *currentDecl = getCurFunctionOrMethodDecl(); 1905 if (!currentDecl && getCurBlock()) 1906 currentDecl = getCurBlock()->TheDecl; 1907 if (!currentDecl) { 1908 Diag(Loc, diag::ext_predef_outside_function); 1909 currentDecl = Context.getTranslationUnitDecl(); 1910 } 1911 1912 QualType ResTy; 1913 if (cast<DeclContext>(currentDecl)->isDependentContext()) { 1914 ResTy = Context.DependentTy; 1915 } else { 1916 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 1917 1918 llvm::APInt LengthI(32, Length + 1); 1919 ResTy = Context.CharTy.withConst(); 1920 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 1921 } 1922 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 1923} 1924 1925ExprResult Sema::ActOnCharacterConstant(const Token &Tok) { 1926 llvm::SmallString<16> CharBuffer; 1927 bool Invalid = false; 1928 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 1929 if (Invalid) 1930 return ExprError(); 1931 1932 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 1933 PP); 1934 if (Literal.hadError()) 1935 return ExprError(); 1936 1937 QualType Ty; 1938 if (!getLangOptions().CPlusPlus) 1939 Ty = Context.IntTy; // 'x' and L'x' -> int in C. 1940 else if (Literal.isWide()) 1941 Ty = Context.WCharTy; // L'x' -> wchar_t in C++. 1942 else if (Literal.isMultiChar()) 1943 Ty = Context.IntTy; // 'wxyz' -> int in C++. 1944 else 1945 Ty = Context.CharTy; // 'x' -> char in C++ 1946 1947 return Owned(new (Context) CharacterLiteral(Literal.getValue(), 1948 Literal.isWide(), 1949 Ty, Tok.getLocation())); 1950} 1951 1952ExprResult Sema::ActOnNumericConstant(const Token &Tok) { 1953 // Fast path for a single digit (which is quite common). A single digit 1954 // cannot have a trigraph, escaped newline, radix prefix, or type suffix. 1955 if (Tok.getLength() == 1) { 1956 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 1957 unsigned IntSize = Context.Target.getIntWidth(); 1958 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'), 1959 Context.IntTy, Tok.getLocation())); 1960 } 1961 1962 llvm::SmallString<512> IntegerBuffer; 1963 // Add padding so that NumericLiteralParser can overread by one character. 1964 IntegerBuffer.resize(Tok.getLength()+1); 1965 const char *ThisTokBegin = &IntegerBuffer[0]; 1966 1967 // Get the spelling of the token, which eliminates trigraphs, etc. 1968 bool Invalid = false; 1969 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid); 1970 if (Invalid) 1971 return ExprError(); 1972 1973 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 1974 Tok.getLocation(), PP); 1975 if (Literal.hadError) 1976 return ExprError(); 1977 1978 Expr *Res; 1979 1980 if (Literal.isFloatingLiteral()) { 1981 QualType Ty; 1982 if (Literal.isFloat) 1983 Ty = Context.FloatTy; 1984 else if (!Literal.isLong) 1985 Ty = Context.DoubleTy; 1986 else 1987 Ty = Context.LongDoubleTy; 1988 1989 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty); 1990 1991 using llvm::APFloat; 1992 APFloat Val(Format); 1993 1994 APFloat::opStatus result = Literal.GetFloatValue(Val); 1995 1996 // Overflow is always an error, but underflow is only an error if 1997 // we underflowed to zero (APFloat reports denormals as underflow). 1998 if ((result & APFloat::opOverflow) || 1999 ((result & APFloat::opUnderflow) && Val.isZero())) { 2000 unsigned diagnostic; 2001 llvm::SmallString<20> buffer; 2002 if (result & APFloat::opOverflow) { 2003 diagnostic = diag::warn_float_overflow; 2004 APFloat::getLargest(Format).toString(buffer); 2005 } else { 2006 diagnostic = diag::warn_float_underflow; 2007 APFloat::getSmallest(Format).toString(buffer); 2008 } 2009 2010 Diag(Tok.getLocation(), diagnostic) 2011 << Ty 2012 << llvm::StringRef(buffer.data(), buffer.size()); 2013 } 2014 2015 bool isExact = (result == APFloat::opOK); 2016 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation()); 2017 2018 } else if (!Literal.isIntegerLiteral()) { 2019 return ExprError(); 2020 } else { 2021 QualType Ty; 2022 2023 // long long is a C99 feature. 2024 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x && 2025 Literal.isLongLong) 2026 Diag(Tok.getLocation(), diag::ext_longlong); 2027 2028 // Get the value in the widest-possible width. 2029 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0); 2030 2031 if (Literal.GetIntegerValue(ResultVal)) { 2032 // If this value didn't fit into uintmax_t, warn and force to ull. 2033 Diag(Tok.getLocation(), diag::warn_integer_too_large); 2034 Ty = Context.UnsignedLongLongTy; 2035 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 2036 "long long is not intmax_t?"); 2037 } else { 2038 // If this value fits into a ULL, try to figure out what else it fits into 2039 // according to the rules of C99 6.4.4.1p5. 2040 2041 // Octal, Hexadecimal, and integers with a U suffix are allowed to 2042 // be an unsigned int. 2043 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 2044 2045 // Check from smallest to largest, picking the smallest type we can. 2046 unsigned Width = 0; 2047 if (!Literal.isLong && !Literal.isLongLong) { 2048 // Are int/unsigned possibilities? 2049 unsigned IntSize = Context.Target.getIntWidth(); 2050 2051 // Does it fit in a unsigned int? 2052 if (ResultVal.isIntN(IntSize)) { 2053 // Does it fit in a signed int? 2054 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 2055 Ty = Context.IntTy; 2056 else if (AllowUnsigned) 2057 Ty = Context.UnsignedIntTy; 2058 Width = IntSize; 2059 } 2060 } 2061 2062 // Are long/unsigned long possibilities? 2063 if (Ty.isNull() && !Literal.isLongLong) { 2064 unsigned LongSize = Context.Target.getLongWidth(); 2065 2066 // Does it fit in a unsigned long? 2067 if (ResultVal.isIntN(LongSize)) { 2068 // Does it fit in a signed long? 2069 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 2070 Ty = Context.LongTy; 2071 else if (AllowUnsigned) 2072 Ty = Context.UnsignedLongTy; 2073 Width = LongSize; 2074 } 2075 } 2076 2077 // Finally, check long long if needed. 2078 if (Ty.isNull()) { 2079 unsigned LongLongSize = Context.Target.getLongLongWidth(); 2080 2081 // Does it fit in a unsigned long long? 2082 if (ResultVal.isIntN(LongLongSize)) { 2083 // Does it fit in a signed long long? 2084 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0) 2085 Ty = Context.LongLongTy; 2086 else if (AllowUnsigned) 2087 Ty = Context.UnsignedLongLongTy; 2088 Width = LongLongSize; 2089 } 2090 } 2091 2092 // If we still couldn't decide a type, we probably have something that 2093 // does not fit in a signed long long, but has no U suffix. 2094 if (Ty.isNull()) { 2095 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 2096 Ty = Context.UnsignedLongLongTy; 2097 Width = Context.Target.getLongLongWidth(); 2098 } 2099 2100 if (ResultVal.getBitWidth() != Width) 2101 ResultVal.trunc(Width); 2102 } 2103 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 2104 } 2105 2106 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 2107 if (Literal.isImaginary) 2108 Res = new (Context) ImaginaryLiteral(Res, 2109 Context.getComplexType(Res->getType())); 2110 2111 return Owned(Res); 2112} 2113 2114ExprResult Sema::ActOnParenExpr(SourceLocation L, 2115 SourceLocation R, Expr *E) { 2116 assert((E != 0) && "ActOnParenExpr() missing expr"); 2117 return Owned(new (Context) ParenExpr(L, R, E)); 2118} 2119 2120/// The UsualUnaryConversions() function is *not* called by this routine. 2121/// See C99 6.3.2.1p[2-4] for more details. 2122bool Sema::CheckSizeOfAlignOfOperand(QualType exprType, 2123 SourceLocation OpLoc, 2124 SourceRange ExprRange, 2125 bool isSizeof) { 2126 if (exprType->isDependentType()) 2127 return false; 2128 2129 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 2130 // the result is the size of the referenced type." 2131 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 2132 // result shall be the alignment of the referenced type." 2133 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>()) 2134 exprType = Ref->getPointeeType(); 2135 2136 // C99 6.5.3.4p1: 2137 if (exprType->isFunctionType()) { 2138 // alignof(function) is allowed as an extension. 2139 if (isSizeof) 2140 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange; 2141 return false; 2142 } 2143 2144 // Allow sizeof(void)/alignof(void) as an extension. 2145 if (exprType->isVoidType()) { 2146 Diag(OpLoc, diag::ext_sizeof_void_type) 2147 << (isSizeof ? "sizeof" : "__alignof") << ExprRange; 2148 return false; 2149 } 2150 2151 if (RequireCompleteType(OpLoc, exprType, 2152 PDiag(diag::err_sizeof_alignof_incomplete_type) 2153 << int(!isSizeof) << ExprRange)) 2154 return true; 2155 2156 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode. 2157 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) { 2158 Diag(OpLoc, diag::err_sizeof_nonfragile_interface) 2159 << exprType << isSizeof << ExprRange; 2160 return true; 2161 } 2162 2163 return false; 2164} 2165 2166static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc, 2167 SourceRange ExprRange) { 2168 E = E->IgnoreParens(); 2169 2170 // alignof decl is always ok. 2171 if (isa<DeclRefExpr>(E)) 2172 return false; 2173 2174 // Cannot know anything else if the expression is dependent. 2175 if (E->isTypeDependent()) 2176 return false; 2177 2178 if (E->getBitField()) { 2179 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange; 2180 return true; 2181 } 2182 2183 // Alignment of a field access is always okay, so long as it isn't a 2184 // bit-field. 2185 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) 2186 if (isa<FieldDecl>(ME->getMemberDecl())) 2187 return false; 2188 2189 return S.CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false); 2190} 2191 2192/// \brief Build a sizeof or alignof expression given a type operand. 2193ExprResult 2194Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo, 2195 SourceLocation OpLoc, 2196 bool isSizeOf, SourceRange R) { 2197 if (!TInfo) 2198 return ExprError(); 2199 2200 QualType T = TInfo->getType(); 2201 2202 if (!T->isDependentType() && 2203 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf)) 2204 return ExprError(); 2205 2206 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 2207 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo, 2208 Context.getSizeType(), OpLoc, 2209 R.getEnd())); 2210} 2211 2212/// \brief Build a sizeof or alignof expression given an expression 2213/// operand. 2214ExprResult 2215Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc, 2216 bool isSizeOf, SourceRange R) { 2217 // Verify that the operand is valid. 2218 bool isInvalid = false; 2219 if (E->isTypeDependent()) { 2220 // Delay type-checking for type-dependent expressions. 2221 } else if (!isSizeOf) { 2222 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R); 2223 } else if (E->getBitField()) { // C99 6.5.3.4p1. 2224 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0; 2225 isInvalid = true; 2226 } else if (E->getType()->isPlaceholderType()) { 2227 ExprResult PE = CheckPlaceholderExpr(E, OpLoc); 2228 if (PE.isInvalid()) return ExprError(); 2229 return CreateSizeOfAlignOfExpr(PE.take(), OpLoc, isSizeOf, R); 2230 } else { 2231 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true); 2232 } 2233 2234 if (isInvalid) 2235 return ExprError(); 2236 2237 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 2238 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E, 2239 Context.getSizeType(), OpLoc, 2240 R.getEnd())); 2241} 2242 2243/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and 2244/// the same for @c alignof and @c __alignof 2245/// Note that the ArgRange is invalid if isType is false. 2246ExprResult 2247Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType, 2248 void *TyOrEx, const SourceRange &ArgRange) { 2249 // If error parsing type, ignore. 2250 if (TyOrEx == 0) return ExprError(); 2251 2252 if (isType) { 2253 TypeSourceInfo *TInfo; 2254 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 2255 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange); 2256 } 2257 2258 Expr *ArgEx = (Expr *)TyOrEx; 2259 ExprResult Result 2260 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange()); 2261 2262 return move(Result); 2263} 2264 2265QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) { 2266 if (V->isTypeDependent()) 2267 return Context.DependentTy; 2268 2269 // These operators return the element type of a complex type. 2270 if (const ComplexType *CT = V->getType()->getAs<ComplexType>()) 2271 return CT->getElementType(); 2272 2273 // Otherwise they pass through real integer and floating point types here. 2274 if (V->getType()->isArithmeticType()) 2275 return V->getType(); 2276 2277 // Test for placeholders. 2278 ExprResult PR = CheckPlaceholderExpr(V, Loc); 2279 if (PR.isInvalid()) return QualType(); 2280 if (PR.take() != V) { 2281 V = PR.take(); 2282 return CheckRealImagOperand(V, Loc, isReal); 2283 } 2284 2285 // Reject anything else. 2286 Diag(Loc, diag::err_realimag_invalid_type) << V->getType() 2287 << (isReal ? "__real" : "__imag"); 2288 return QualType(); 2289} 2290 2291 2292 2293ExprResult 2294Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 2295 tok::TokenKind Kind, Expr *Input) { 2296 UnaryOperatorKind Opc; 2297 switch (Kind) { 2298 default: assert(0 && "Unknown unary op!"); 2299 case tok::plusplus: Opc = UO_PostInc; break; 2300 case tok::minusminus: Opc = UO_PostDec; break; 2301 } 2302 2303 return BuildUnaryOp(S, OpLoc, Opc, Input); 2304} 2305 2306ExprResult 2307Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, 2308 Expr *Idx, SourceLocation RLoc) { 2309 // Since this might be a postfix expression, get rid of ParenListExprs. 2310 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 2311 if (Result.isInvalid()) return ExprError(); 2312 Base = Result.take(); 2313 2314 Expr *LHSExp = Base, *RHSExp = Idx; 2315 2316 if (getLangOptions().CPlusPlus && 2317 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) { 2318 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 2319 Context.DependentTy, RLoc)); 2320 } 2321 2322 if (getLangOptions().CPlusPlus && 2323 (LHSExp->getType()->isRecordType() || 2324 LHSExp->getType()->isEnumeralType() || 2325 RHSExp->getType()->isRecordType() || 2326 RHSExp->getType()->isEnumeralType())) { 2327 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx); 2328 } 2329 2330 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc); 2331} 2332 2333 2334ExprResult 2335Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 2336 Expr *Idx, SourceLocation RLoc) { 2337 Expr *LHSExp = Base; 2338 Expr *RHSExp = Idx; 2339 2340 // Perform default conversions. 2341 if (!LHSExp->getType()->getAs<VectorType>()) 2342 DefaultFunctionArrayLvalueConversion(LHSExp); 2343 DefaultFunctionArrayLvalueConversion(RHSExp); 2344 2345 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 2346 2347 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 2348 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 2349 // in the subscript position. As a result, we need to derive the array base 2350 // and index from the expression types. 2351 Expr *BaseExpr, *IndexExpr; 2352 QualType ResultType; 2353 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 2354 BaseExpr = LHSExp; 2355 IndexExpr = RHSExp; 2356 ResultType = Context.DependentTy; 2357 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 2358 BaseExpr = LHSExp; 2359 IndexExpr = RHSExp; 2360 ResultType = PTy->getPointeeType(); 2361 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 2362 // Handle the uncommon case of "123[Ptr]". 2363 BaseExpr = RHSExp; 2364 IndexExpr = LHSExp; 2365 ResultType = PTy->getPointeeType(); 2366 } else if (const ObjCObjectPointerType *PTy = 2367 LHSTy->getAs<ObjCObjectPointerType>()) { 2368 BaseExpr = LHSExp; 2369 IndexExpr = RHSExp; 2370 ResultType = PTy->getPointeeType(); 2371 } else if (const ObjCObjectPointerType *PTy = 2372 RHSTy->getAs<ObjCObjectPointerType>()) { 2373 // Handle the uncommon case of "123[Ptr]". 2374 BaseExpr = RHSExp; 2375 IndexExpr = LHSExp; 2376 ResultType = PTy->getPointeeType(); 2377 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 2378 BaseExpr = LHSExp; // vectors: V[123] 2379 IndexExpr = RHSExp; 2380 2381 // FIXME: need to deal with const... 2382 ResultType = VTy->getElementType(); 2383 } else if (LHSTy->isArrayType()) { 2384 // If we see an array that wasn't promoted by 2385 // DefaultFunctionArrayLvalueConversion, it must be an array that 2386 // wasn't promoted because of the C90 rule that doesn't 2387 // allow promoting non-lvalue arrays. Warn, then 2388 // force the promotion here. 2389 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 2390 LHSExp->getSourceRange(); 2391 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 2392 CK_ArrayToPointerDecay); 2393 LHSTy = LHSExp->getType(); 2394 2395 BaseExpr = LHSExp; 2396 IndexExpr = RHSExp; 2397 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 2398 } else if (RHSTy->isArrayType()) { 2399 // Same as previous, except for 123[f().a] case 2400 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 2401 RHSExp->getSourceRange(); 2402 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 2403 CK_ArrayToPointerDecay); 2404 RHSTy = RHSExp->getType(); 2405 2406 BaseExpr = RHSExp; 2407 IndexExpr = LHSExp; 2408 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 2409 } else { 2410 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 2411 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 2412 } 2413 // C99 6.5.2.1p1 2414 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 2415 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 2416 << IndexExpr->getSourceRange()); 2417 2418 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 2419 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 2420 && !IndexExpr->isTypeDependent()) 2421 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 2422 2423 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 2424 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 2425 // type. Note that Functions are not objects, and that (in C99 parlance) 2426 // incomplete types are not object types. 2427 if (ResultType->isFunctionType()) { 2428 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 2429 << ResultType << BaseExpr->getSourceRange(); 2430 return ExprError(); 2431 } 2432 2433 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) { 2434 // GNU extension: subscripting on pointer to void 2435 Diag(LLoc, diag::ext_gnu_void_ptr) 2436 << BaseExpr->getSourceRange(); 2437 } else if (!ResultType->isDependentType() && 2438 RequireCompleteType(LLoc, ResultType, 2439 PDiag(diag::err_subscript_incomplete_type) 2440 << BaseExpr->getSourceRange())) 2441 return ExprError(); 2442 2443 // Diagnose bad cases where we step over interface counts. 2444 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) { 2445 Diag(LLoc, diag::err_subscript_nonfragile_interface) 2446 << ResultType << BaseExpr->getSourceRange(); 2447 return ExprError(); 2448 } 2449 2450 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 2451 ResultType, RLoc)); 2452} 2453 2454QualType Sema:: 2455CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc, 2456 const IdentifierInfo *CompName, 2457 SourceLocation CompLoc) { 2458 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements, 2459 // see FIXME there. 2460 // 2461 // FIXME: This logic can be greatly simplified by splitting it along 2462 // halving/not halving and reworking the component checking. 2463 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>(); 2464 2465 // The vector accessor can't exceed the number of elements. 2466 const char *compStr = CompName->getNameStart(); 2467 2468 // This flag determines whether or not the component is one of the four 2469 // special names that indicate a subset of exactly half the elements are 2470 // to be selected. 2471 bool HalvingSwizzle = false; 2472 2473 // This flag determines whether or not CompName has an 's' char prefix, 2474 // indicating that it is a string of hex values to be used as vector indices. 2475 bool HexSwizzle = *compStr == 's' || *compStr == 'S'; 2476 2477 // Check that we've found one of the special components, or that the component 2478 // names must come from the same set. 2479 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") || 2480 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) { 2481 HalvingSwizzle = true; 2482 } else if (vecType->getPointAccessorIdx(*compStr) != -1) { 2483 do 2484 compStr++; 2485 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1); 2486 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) { 2487 do 2488 compStr++; 2489 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1); 2490 } 2491 2492 if (!HalvingSwizzle && *compStr) { 2493 // We didn't get to the end of the string. This means the component names 2494 // didn't come from the same set *or* we encountered an illegal name. 2495 Diag(OpLoc, diag::err_ext_vector_component_name_illegal) 2496 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc); 2497 return QualType(); 2498 } 2499 2500 // Ensure no component accessor exceeds the width of the vector type it 2501 // operates on. 2502 if (!HalvingSwizzle) { 2503 compStr = CompName->getNameStart(); 2504 2505 if (HexSwizzle) 2506 compStr++; 2507 2508 while (*compStr) { 2509 if (!vecType->isAccessorWithinNumElements(*compStr++)) { 2510 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length) 2511 << baseType << SourceRange(CompLoc); 2512 return QualType(); 2513 } 2514 } 2515 } 2516 2517 // The component accessor looks fine - now we need to compute the actual type. 2518 // The vector type is implied by the component accessor. For example, 2519 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc. 2520 // vec4.s0 is a float, vec4.s23 is a vec3, etc. 2521 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2. 2522 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2 2523 : CompName->getLength(); 2524 if (HexSwizzle) 2525 CompSize--; 2526 2527 if (CompSize == 1) 2528 return vecType->getElementType(); 2529 2530 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize); 2531 // Now look up the TypeDefDecl from the vector type. Without this, 2532 // diagostics look bad. We want extended vector types to appear built-in. 2533 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) { 2534 if (ExtVectorDecls[i]->getUnderlyingType() == VT) 2535 return Context.getTypedefType(ExtVectorDecls[i]); 2536 } 2537 return VT; // should never get here (a typedef type should always be found). 2538} 2539 2540static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl, 2541 IdentifierInfo *Member, 2542 const Selector &Sel, 2543 ASTContext &Context) { 2544 if (Member) 2545 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member)) 2546 return PD; 2547 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel)) 2548 return OMD; 2549 2550 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(), 2551 E = PDecl->protocol_end(); I != E; ++I) { 2552 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel, 2553 Context)) 2554 return D; 2555 } 2556 return 0; 2557} 2558 2559static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy, 2560 IdentifierInfo *Member, 2561 const Selector &Sel, 2562 ASTContext &Context) { 2563 // Check protocols on qualified interfaces. 2564 Decl *GDecl = 0; 2565 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(), 2566 E = QIdTy->qual_end(); I != E; ++I) { 2567 if (Member) 2568 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) { 2569 GDecl = PD; 2570 break; 2571 } 2572 // Also must look for a getter or setter name which uses property syntax. 2573 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) { 2574 GDecl = OMD; 2575 break; 2576 } 2577 } 2578 if (!GDecl) { 2579 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(), 2580 E = QIdTy->qual_end(); I != E; ++I) { 2581 // Search in the protocol-qualifier list of current protocol. 2582 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel, 2583 Context); 2584 if (GDecl) 2585 return GDecl; 2586 } 2587 } 2588 return GDecl; 2589} 2590 2591ExprResult 2592Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType, 2593 bool IsArrow, SourceLocation OpLoc, 2594 const CXXScopeSpec &SS, 2595 NamedDecl *FirstQualifierInScope, 2596 const DeclarationNameInfo &NameInfo, 2597 const TemplateArgumentListInfo *TemplateArgs) { 2598 // Even in dependent contexts, try to diagnose base expressions with 2599 // obviously wrong types, e.g.: 2600 // 2601 // T* t; 2602 // t.f; 2603 // 2604 // In Obj-C++, however, the above expression is valid, since it could be 2605 // accessing the 'f' property if T is an Obj-C interface. The extra check 2606 // allows this, while still reporting an error if T is a struct pointer. 2607 if (!IsArrow) { 2608 const PointerType *PT = BaseType->getAs<PointerType>(); 2609 if (PT && (!getLangOptions().ObjC1 || 2610 PT->getPointeeType()->isRecordType())) { 2611 assert(BaseExpr && "cannot happen with implicit member accesses"); 2612 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union) 2613 << BaseType << BaseExpr->getSourceRange(); 2614 return ExprError(); 2615 } 2616 } 2617 2618 assert(BaseType->isDependentType() || 2619 NameInfo.getName().isDependentName() || 2620 isDependentScopeSpecifier(SS)); 2621 2622 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr 2623 // must have pointer type, and the accessed type is the pointee. 2624 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType, 2625 IsArrow, OpLoc, 2626 SS.getScopeRep(), 2627 SS.getRange(), 2628 FirstQualifierInScope, 2629 NameInfo, TemplateArgs)); 2630} 2631 2632/// We know that the given qualified member reference points only to 2633/// declarations which do not belong to the static type of the base 2634/// expression. Diagnose the problem. 2635static void DiagnoseQualifiedMemberReference(Sema &SemaRef, 2636 Expr *BaseExpr, 2637 QualType BaseType, 2638 const CXXScopeSpec &SS, 2639 const LookupResult &R) { 2640 // If this is an implicit member access, use a different set of 2641 // diagnostics. 2642 if (!BaseExpr) 2643 return DiagnoseInstanceReference(SemaRef, SS, R); 2644 2645 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_of_unrelated) 2646 << SS.getRange() << R.getRepresentativeDecl() << BaseType; 2647} 2648 2649// Check whether the declarations we found through a nested-name 2650// specifier in a member expression are actually members of the base 2651// type. The restriction here is: 2652// 2653// C++ [expr.ref]p2: 2654// ... In these cases, the id-expression shall name a 2655// member of the class or of one of its base classes. 2656// 2657// So it's perfectly legitimate for the nested-name specifier to name 2658// an unrelated class, and for us to find an overload set including 2659// decls from classes which are not superclasses, as long as the decl 2660// we actually pick through overload resolution is from a superclass. 2661bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr, 2662 QualType BaseType, 2663 const CXXScopeSpec &SS, 2664 const LookupResult &R) { 2665 const RecordType *BaseRT = BaseType->getAs<RecordType>(); 2666 if (!BaseRT) { 2667 // We can't check this yet because the base type is still 2668 // dependent. 2669 assert(BaseType->isDependentType()); 2670 return false; 2671 } 2672 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl()); 2673 2674 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2675 // If this is an implicit member reference and we find a 2676 // non-instance member, it's not an error. 2677 if (!BaseExpr && !(*I)->isCXXInstanceMember()) 2678 return false; 2679 2680 // Note that we use the DC of the decl, not the underlying decl. 2681 DeclContext *DC = (*I)->getDeclContext(); 2682 while (DC->isTransparentContext()) 2683 DC = DC->getParent(); 2684 2685 if (!DC->isRecord()) 2686 continue; 2687 2688 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord; 2689 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl()); 2690 2691 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord)) 2692 return false; 2693 } 2694 2695 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R); 2696 return true; 2697} 2698 2699static bool 2700LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R, 2701 SourceRange BaseRange, const RecordType *RTy, 2702 SourceLocation OpLoc, CXXScopeSpec &SS, 2703 bool HasTemplateArgs) { 2704 RecordDecl *RDecl = RTy->getDecl(); 2705 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0), 2706 SemaRef.PDiag(diag::err_typecheck_incomplete_tag) 2707 << BaseRange)) 2708 return true; 2709 2710 if (HasTemplateArgs) { 2711 // LookupTemplateName doesn't expect these both to exist simultaneously. 2712 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0); 2713 2714 bool MOUS; 2715 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS); 2716 return false; 2717 } 2718 2719 DeclContext *DC = RDecl; 2720 if (SS.isSet()) { 2721 // If the member name was a qualified-id, look into the 2722 // nested-name-specifier. 2723 DC = SemaRef.computeDeclContext(SS, false); 2724 2725 if (SemaRef.RequireCompleteDeclContext(SS, DC)) { 2726 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag) 2727 << SS.getRange() << DC; 2728 return true; 2729 } 2730 2731 assert(DC && "Cannot handle non-computable dependent contexts in lookup"); 2732 2733 if (!isa<TypeDecl>(DC)) { 2734 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass) 2735 << DC << SS.getRange(); 2736 return true; 2737 } 2738 } 2739 2740 // The record definition is complete, now look up the member. 2741 SemaRef.LookupQualifiedName(R, DC); 2742 2743 if (!R.empty()) 2744 return false; 2745 2746 // We didn't find anything with the given name, so try to correct 2747 // for typos. 2748 DeclarationName Name = R.getLookupName(); 2749 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) && 2750 !R.empty() && 2751 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) { 2752 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest) 2753 << Name << DC << R.getLookupName() << SS.getRange() 2754 << FixItHint::CreateReplacement(R.getNameLoc(), 2755 R.getLookupName().getAsString()); 2756 if (NamedDecl *ND = R.getAsSingle<NamedDecl>()) 2757 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl) 2758 << ND->getDeclName(); 2759 return false; 2760 } else { 2761 R.clear(); 2762 R.setLookupName(Name); 2763 } 2764 2765 return false; 2766} 2767 2768ExprResult 2769Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType, 2770 SourceLocation OpLoc, bool IsArrow, 2771 CXXScopeSpec &SS, 2772 NamedDecl *FirstQualifierInScope, 2773 const DeclarationNameInfo &NameInfo, 2774 const TemplateArgumentListInfo *TemplateArgs) { 2775 if (BaseType->isDependentType() || 2776 (SS.isSet() && isDependentScopeSpecifier(SS))) 2777 return ActOnDependentMemberExpr(Base, BaseType, 2778 IsArrow, OpLoc, 2779 SS, FirstQualifierInScope, 2780 NameInfo, TemplateArgs); 2781 2782 LookupResult R(*this, NameInfo, LookupMemberName); 2783 2784 // Implicit member accesses. 2785 if (!Base) { 2786 QualType RecordTy = BaseType; 2787 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType(); 2788 if (LookupMemberExprInRecord(*this, R, SourceRange(), 2789 RecordTy->getAs<RecordType>(), 2790 OpLoc, SS, TemplateArgs != 0)) 2791 return ExprError(); 2792 2793 // Explicit member accesses. 2794 } else { 2795 ExprResult Result = 2796 LookupMemberExpr(R, Base, IsArrow, OpLoc, 2797 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0); 2798 2799 if (Result.isInvalid()) { 2800 Owned(Base); 2801 return ExprError(); 2802 } 2803 2804 if (Result.get()) 2805 return move(Result); 2806 2807 // LookupMemberExpr can modify Base, and thus change BaseType 2808 BaseType = Base->getType(); 2809 } 2810 2811 return BuildMemberReferenceExpr(Base, BaseType, 2812 OpLoc, IsArrow, SS, FirstQualifierInScope, 2813 R, TemplateArgs); 2814} 2815 2816ExprResult 2817Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType, 2818 SourceLocation OpLoc, bool IsArrow, 2819 const CXXScopeSpec &SS, 2820 NamedDecl *FirstQualifierInScope, 2821 LookupResult &R, 2822 const TemplateArgumentListInfo *TemplateArgs, 2823 bool SuppressQualifierCheck) { 2824 QualType BaseType = BaseExprType; 2825 if (IsArrow) { 2826 assert(BaseType->isPointerType()); 2827 BaseType = BaseType->getAs<PointerType>()->getPointeeType(); 2828 } 2829 R.setBaseObjectType(BaseType); 2830 2831 NestedNameSpecifier *Qualifier = SS.getScopeRep(); 2832 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo(); 2833 DeclarationName MemberName = MemberNameInfo.getName(); 2834 SourceLocation MemberLoc = MemberNameInfo.getLoc(); 2835 2836 if (R.isAmbiguous()) 2837 return ExprError(); 2838 2839 if (R.empty()) { 2840 // Rederive where we looked up. 2841 DeclContext *DC = (SS.isSet() 2842 ? computeDeclContext(SS, false) 2843 : BaseType->getAs<RecordType>()->getDecl()); 2844 2845 Diag(R.getNameLoc(), diag::err_no_member) 2846 << MemberName << DC 2847 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange()); 2848 return ExprError(); 2849 } 2850 2851 // Diagnose lookups that find only declarations from a non-base 2852 // type. This is possible for either qualified lookups (which may 2853 // have been qualified with an unrelated type) or implicit member 2854 // expressions (which were found with unqualified lookup and thus 2855 // may have come from an enclosing scope). Note that it's okay for 2856 // lookup to find declarations from a non-base type as long as those 2857 // aren't the ones picked by overload resolution. 2858 if ((SS.isSet() || !BaseExpr || 2859 (isa<CXXThisExpr>(BaseExpr) && 2860 cast<CXXThisExpr>(BaseExpr)->isImplicit())) && 2861 !SuppressQualifierCheck && 2862 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R)) 2863 return ExprError(); 2864 2865 // Construct an unresolved result if we in fact got an unresolved 2866 // result. 2867 if (R.isOverloadedResult() || R.isUnresolvableResult()) { 2868 bool Dependent = 2869 BaseExprType->isDependentType() || 2870 R.isUnresolvableResult() || 2871 OverloadExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs); 2872 2873 // Suppress any lookup-related diagnostics; we'll do these when we 2874 // pick a member. 2875 R.suppressDiagnostics(); 2876 2877 UnresolvedMemberExpr *MemExpr 2878 = UnresolvedMemberExpr::Create(Context, Dependent, 2879 R.isUnresolvableResult(), 2880 BaseExpr, BaseExprType, 2881 IsArrow, OpLoc, 2882 Qualifier, SS.getRange(), 2883 MemberNameInfo, 2884 TemplateArgs, R.begin(), R.end()); 2885 2886 return Owned(MemExpr); 2887 } 2888 2889 assert(R.isSingleResult()); 2890 DeclAccessPair FoundDecl = R.begin().getPair(); 2891 NamedDecl *MemberDecl = R.getFoundDecl(); 2892 2893 // FIXME: diagnose the presence of template arguments now. 2894 2895 // If the decl being referenced had an error, return an error for this 2896 // sub-expr without emitting another error, in order to avoid cascading 2897 // error cases. 2898 if (MemberDecl->isInvalidDecl()) 2899 return ExprError(); 2900 2901 // Handle the implicit-member-access case. 2902 if (!BaseExpr) { 2903 // If this is not an instance member, convert to a non-member access. 2904 if (!MemberDecl->isCXXInstanceMember()) 2905 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl); 2906 2907 SourceLocation Loc = R.getNameLoc(); 2908 if (SS.getRange().isValid()) 2909 Loc = SS.getRange().getBegin(); 2910 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true); 2911 } 2912 2913 bool ShouldCheckUse = true; 2914 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) { 2915 // Don't diagnose the use of a virtual member function unless it's 2916 // explicitly qualified. 2917 if (MD->isVirtual() && !SS.isSet()) 2918 ShouldCheckUse = false; 2919 } 2920 2921 // Check the use of this member. 2922 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) { 2923 Owned(BaseExpr); 2924 return ExprError(); 2925 } 2926 2927 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) { 2928 // We may have found a field within an anonymous union or struct 2929 // (C++ [class.union]). 2930 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() && 2931 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion()) 2932 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD, 2933 BaseExpr, OpLoc); 2934 2935 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref] 2936 QualType MemberType = FD->getType(); 2937 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) 2938 MemberType = Ref->getPointeeType(); 2939 else { 2940 Qualifiers BaseQuals = BaseType.getQualifiers(); 2941 BaseQuals.removeObjCGCAttr(); 2942 if (FD->isMutable()) BaseQuals.removeConst(); 2943 2944 Qualifiers MemberQuals 2945 = Context.getCanonicalType(MemberType).getQualifiers(); 2946 2947 Qualifiers Combined = BaseQuals + MemberQuals; 2948 if (Combined != MemberQuals) 2949 MemberType = Context.getQualifiedType(MemberType, Combined); 2950 } 2951 2952 MarkDeclarationReferenced(MemberLoc, FD); 2953 if (PerformObjectMemberConversion(BaseExpr, Qualifier, FoundDecl, FD)) 2954 return ExprError(); 2955 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS, 2956 FD, FoundDecl, MemberNameInfo, 2957 MemberType)); 2958 } 2959 2960 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) { 2961 MarkDeclarationReferenced(MemberLoc, Var); 2962 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS, 2963 Var, FoundDecl, MemberNameInfo, 2964 Var->getType().getNonReferenceType())); 2965 } 2966 2967 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) { 2968 MarkDeclarationReferenced(MemberLoc, MemberDecl); 2969 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS, 2970 MemberFn, FoundDecl, MemberNameInfo, 2971 MemberFn->getType())); 2972 } 2973 2974 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) { 2975 MarkDeclarationReferenced(MemberLoc, MemberDecl); 2976 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS, 2977 Enum, FoundDecl, MemberNameInfo, 2978 Enum->getType())); 2979 } 2980 2981 Owned(BaseExpr); 2982 2983 // We found something that we didn't expect. Complain. 2984 if (isa<TypeDecl>(MemberDecl)) 2985 Diag(MemberLoc, diag::err_typecheck_member_reference_type) 2986 << MemberName << BaseType << int(IsArrow); 2987 else 2988 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown) 2989 << MemberName << BaseType << int(IsArrow); 2990 2991 Diag(MemberDecl->getLocation(), diag::note_member_declared_here) 2992 << MemberName; 2993 R.suppressDiagnostics(); 2994 return ExprError(); 2995} 2996 2997/// Look up the given member of the given non-type-dependent 2998/// expression. This can return in one of two ways: 2999/// * If it returns a sentinel null-but-valid result, the caller will 3000/// assume that lookup was performed and the results written into 3001/// the provided structure. It will take over from there. 3002/// * Otherwise, the returned expression will be produced in place of 3003/// an ordinary member expression. 3004/// 3005/// The ObjCImpDecl bit is a gross hack that will need to be properly 3006/// fixed for ObjC++. 3007ExprResult 3008Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr, 3009 bool &IsArrow, SourceLocation OpLoc, 3010 CXXScopeSpec &SS, 3011 Decl *ObjCImpDecl, bool HasTemplateArgs) { 3012 assert(BaseExpr && "no base expression"); 3013 3014 // Perform default conversions. 3015 DefaultFunctionArrayConversion(BaseExpr); 3016 3017 QualType BaseType = BaseExpr->getType(); 3018 assert(!BaseType->isDependentType()); 3019 3020 DeclarationName MemberName = R.getLookupName(); 3021 SourceLocation MemberLoc = R.getNameLoc(); 3022 3023 // If the user is trying to apply -> or . to a function pointer 3024 // type, it's probably because they forgot parentheses to call that 3025 // function. Suggest the addition of those parentheses, build the 3026 // call, and continue on. 3027 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 3028 if (const FunctionProtoType *Fun 3029 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) { 3030 QualType ResultTy = Fun->getResultType(); 3031 if (Fun->getNumArgs() == 0 && 3032 ((!IsArrow && ResultTy->isRecordType()) || 3033 (IsArrow && ResultTy->isPointerType() && 3034 ResultTy->getAs<PointerType>()->getPointeeType() 3035 ->isRecordType()))) { 3036 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd()); 3037 Diag(Loc, diag::err_member_reference_needs_call) 3038 << QualType(Fun, 0) 3039 << FixItHint::CreateInsertion(Loc, "()"); 3040 3041 ExprResult NewBase 3042 = ActOnCallExpr(0, BaseExpr, Loc, MultiExprArg(*this, 0, 0), Loc); 3043 BaseExpr = 0; 3044 if (NewBase.isInvalid()) 3045 return ExprError(); 3046 3047 BaseExpr = NewBase.takeAs<Expr>(); 3048 DefaultFunctionArrayConversion(BaseExpr); 3049 BaseType = BaseExpr->getType(); 3050 } 3051 } 3052 } 3053 3054 // If this is an Objective-C pseudo-builtin and a definition is provided then 3055 // use that. 3056 if (BaseType->isObjCIdType()) { 3057 if (IsArrow) { 3058 // Handle the following exceptional case PObj->isa. 3059 if (const ObjCObjectPointerType *OPT = 3060 BaseType->getAs<ObjCObjectPointerType>()) { 3061 if (OPT->getObjectType()->isObjCId() && 3062 MemberName.getAsIdentifierInfo()->isStr("isa")) 3063 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc, 3064 Context.getObjCClassType())); 3065 } 3066 } 3067 // We have an 'id' type. Rather than fall through, we check if this 3068 // is a reference to 'isa'. 3069 if (BaseType != Context.ObjCIdRedefinitionType) { 3070 BaseType = Context.ObjCIdRedefinitionType; 3071 ImpCastExprToType(BaseExpr, BaseType, CK_BitCast); 3072 } 3073 } 3074 3075 // If this is an Objective-C pseudo-builtin and a definition is provided then 3076 // use that. 3077 if (Context.isObjCSelType(BaseType)) { 3078 // We have an 'SEL' type. Rather than fall through, we check if this 3079 // is a reference to 'sel_id'. 3080 if (BaseType != Context.ObjCSelRedefinitionType) { 3081 BaseType = Context.ObjCSelRedefinitionType; 3082 ImpCastExprToType(BaseExpr, BaseType, CK_BitCast); 3083 } 3084 } 3085 3086 assert(!BaseType.isNull() && "no type for member expression"); 3087 3088 // Handle properties on ObjC 'Class' types. 3089 if (!IsArrow && BaseType->isObjCClassType()) { 3090 // Also must look for a getter name which uses property syntax. 3091 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 3092 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 3093 if (ObjCMethodDecl *MD = getCurMethodDecl()) { 3094 ObjCInterfaceDecl *IFace = MD->getClassInterface(); 3095 ObjCMethodDecl *Getter; 3096 // FIXME: need to also look locally in the implementation. 3097 if ((Getter = IFace->lookupClassMethod(Sel))) { 3098 // Check the use of this method. 3099 if (DiagnoseUseOfDecl(Getter, MemberLoc)) 3100 return ExprError(); 3101 } 3102 // If we found a getter then this may be a valid dot-reference, we 3103 // will look for the matching setter, in case it is needed. 3104 Selector SetterSel = 3105 SelectorTable::constructSetterName(PP.getIdentifierTable(), 3106 PP.getSelectorTable(), Member); 3107 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel); 3108 if (!Setter) { 3109 // If this reference is in an @implementation, also check for 'private' 3110 // methods. 3111 Setter = IFace->lookupPrivateInstanceMethod(SetterSel); 3112 } 3113 // Look through local category implementations associated with the class. 3114 if (!Setter) 3115 Setter = IFace->getCategoryClassMethod(SetterSel); 3116 3117 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) 3118 return ExprError(); 3119 3120 if (Getter || Setter) { 3121 QualType PType; 3122 3123 if (Getter) 3124 PType = Getter->getSendResultType(); 3125 else 3126 // Get the expression type from Setter's incoming parameter. 3127 PType = (*(Setter->param_end() -1))->getType(); 3128 // FIXME: we must check that the setter has property type. 3129 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, 3130 PType, 3131 Setter, MemberLoc, BaseExpr)); 3132 } 3133 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 3134 << MemberName << BaseType); 3135 } 3136 } 3137 3138 if (BaseType->isObjCClassType() && 3139 BaseType != Context.ObjCClassRedefinitionType) { 3140 BaseType = Context.ObjCClassRedefinitionType; 3141 ImpCastExprToType(BaseExpr, BaseType, CK_BitCast); 3142 } 3143 3144 if (IsArrow) { 3145 if (const PointerType *PT = BaseType->getAs<PointerType>()) 3146 BaseType = PT->getPointeeType(); 3147 else if (BaseType->isObjCObjectPointerType()) 3148 ; 3149 else if (BaseType->isRecordType()) { 3150 // Recover from arrow accesses to records, e.g.: 3151 // struct MyRecord foo; 3152 // foo->bar 3153 // This is actually well-formed in C++ if MyRecord has an 3154 // overloaded operator->, but that should have been dealt with 3155 // by now. 3156 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 3157 << BaseType << int(IsArrow) << BaseExpr->getSourceRange() 3158 << FixItHint::CreateReplacement(OpLoc, "."); 3159 IsArrow = false; 3160 } else { 3161 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow) 3162 << BaseType << BaseExpr->getSourceRange(); 3163 return ExprError(); 3164 } 3165 } else { 3166 // Recover from dot accesses to pointers, e.g.: 3167 // type *foo; 3168 // foo.bar 3169 // This is actually well-formed in two cases: 3170 // - 'type' is an Objective C type 3171 // - 'bar' is a pseudo-destructor name which happens to refer to 3172 // the appropriate pointer type 3173 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) { 3174 const PointerType *PT = BaseType->getAs<PointerType>(); 3175 if (PT && PT->getPointeeType()->isRecordType()) { 3176 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 3177 << BaseType << int(IsArrow) << BaseExpr->getSourceRange() 3178 << FixItHint::CreateReplacement(OpLoc, "->"); 3179 BaseType = PT->getPointeeType(); 3180 IsArrow = true; 3181 } 3182 } 3183 } 3184 3185 // Handle field access to simple records. 3186 if (const RecordType *RTy = BaseType->getAs<RecordType>()) { 3187 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(), 3188 RTy, OpLoc, SS, HasTemplateArgs)) 3189 return ExprError(); 3190 return Owned((Expr*) 0); 3191 } 3192 3193 // Handle access to Objective-C instance variables, such as "Obj->ivar" and 3194 // (*Obj).ivar. 3195 if ((IsArrow && BaseType->isObjCObjectPointerType()) || 3196 (!IsArrow && BaseType->isObjCObjectType())) { 3197 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>(); 3198 ObjCInterfaceDecl *IDecl = 3199 OPT ? OPT->getInterfaceDecl() 3200 : BaseType->getAs<ObjCObjectType>()->getInterface(); 3201 if (IDecl) { 3202 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 3203 3204 ObjCInterfaceDecl *ClassDeclared; 3205 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 3206 3207 if (!IV) { 3208 // Attempt to correct for typos in ivar names. 3209 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(), 3210 LookupMemberName); 3211 if (CorrectTypo(Res, 0, 0, IDecl, false, CTC_MemberLookup) && 3212 (IV = Res.getAsSingle<ObjCIvarDecl>())) { 3213 Diag(R.getNameLoc(), 3214 diag::err_typecheck_member_reference_ivar_suggest) 3215 << IDecl->getDeclName() << MemberName << IV->getDeclName() 3216 << FixItHint::CreateReplacement(R.getNameLoc(), 3217 IV->getNameAsString()); 3218 Diag(IV->getLocation(), diag::note_previous_decl) 3219 << IV->getDeclName(); 3220 } else { 3221 Res.clear(); 3222 Res.setLookupName(Member); 3223 } 3224 } 3225 3226 if (IV) { 3227 // If the decl being referenced had an error, return an error for this 3228 // sub-expr without emitting another error, in order to avoid cascading 3229 // error cases. 3230 if (IV->isInvalidDecl()) 3231 return ExprError(); 3232 3233 // Check whether we can reference this field. 3234 if (DiagnoseUseOfDecl(IV, MemberLoc)) 3235 return ExprError(); 3236 if (IV->getAccessControl() != ObjCIvarDecl::Public && 3237 IV->getAccessControl() != ObjCIvarDecl::Package) { 3238 ObjCInterfaceDecl *ClassOfMethodDecl = 0; 3239 if (ObjCMethodDecl *MD = getCurMethodDecl()) 3240 ClassOfMethodDecl = MD->getClassInterface(); 3241 else if (ObjCImpDecl && getCurFunctionDecl()) { 3242 // Case of a c-function declared inside an objc implementation. 3243 // FIXME: For a c-style function nested inside an objc implementation 3244 // class, there is no implementation context available, so we pass 3245 // down the context as argument to this routine. Ideally, this context 3246 // need be passed down in the AST node and somehow calculated from the 3247 // AST for a function decl. 3248 if (ObjCImplementationDecl *IMPD = 3249 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl)) 3250 ClassOfMethodDecl = IMPD->getClassInterface(); 3251 else if (ObjCCategoryImplDecl* CatImplClass = 3252 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl)) 3253 ClassOfMethodDecl = CatImplClass->getClassInterface(); 3254 } 3255 3256 if (IV->getAccessControl() == ObjCIvarDecl::Private) { 3257 if (ClassDeclared != IDecl || 3258 ClassOfMethodDecl != ClassDeclared) 3259 Diag(MemberLoc, diag::error_private_ivar_access) 3260 << IV->getDeclName(); 3261 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl)) 3262 // @protected 3263 Diag(MemberLoc, diag::error_protected_ivar_access) 3264 << IV->getDeclName(); 3265 } 3266 3267 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(), 3268 MemberLoc, BaseExpr, 3269 IsArrow)); 3270 } 3271 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar) 3272 << IDecl->getDeclName() << MemberName 3273 << BaseExpr->getSourceRange()); 3274 } 3275 } 3276 // Handle properties on 'id' and qualified "id". 3277 if (!IsArrow && (BaseType->isObjCIdType() || 3278 BaseType->isObjCQualifiedIdType())) { 3279 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>(); 3280 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 3281 3282 // Check protocols on qualified interfaces. 3283 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 3284 if (Decl *PMDecl = FindGetterSetterNameDecl(QIdTy, Member, Sel, 3285 Context)) { 3286 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) { 3287 // Check the use of this declaration 3288 if (DiagnoseUseOfDecl(PD, MemberLoc)) 3289 return ExprError(); 3290 3291 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(), 3292 MemberLoc, BaseExpr)); 3293 } 3294 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) { 3295 // Check the use of this method. 3296 if (DiagnoseUseOfDecl(OMD, MemberLoc)) 3297 return ExprError(); 3298 Selector SetterSel = 3299 SelectorTable::constructSetterName(PP.getIdentifierTable(), 3300 PP.getSelectorTable(), Member); 3301 ObjCMethodDecl *SMD = 0; 3302 if (Decl *SDecl = FindGetterSetterNameDecl(QIdTy, /*Property id*/0, 3303 SetterSel, Context)) 3304 SMD = dyn_cast<ObjCMethodDecl>(SDecl); 3305 QualType PType = OMD->getSendResultType(); 3306 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(OMD, PType, 3307 SMD, 3308 MemberLoc, 3309 BaseExpr)); 3310 } 3311 } 3312 3313 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 3314 << MemberName << BaseType); 3315 } 3316 3317 // Handle Objective-C property access, which is "Obj.property" where Obj is a 3318 // pointer to a (potentially qualified) interface type. 3319 if (!IsArrow) 3320 if (const ObjCObjectPointerType *OPT = 3321 BaseType->getAsObjCInterfacePointerType()) 3322 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc); 3323 3324 // Handle the following exceptional case (*Obj).isa. 3325 if (!IsArrow && 3326 BaseType->isObjCObjectType() && 3327 BaseType->getAs<ObjCObjectType>()->isObjCId() && 3328 MemberName.getAsIdentifierInfo()->isStr("isa")) 3329 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc, 3330 Context.getObjCClassType())); 3331 3332 // Handle 'field access' to vectors, such as 'V.xx'. 3333 if (BaseType->isExtVectorType()) { 3334 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 3335 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc); 3336 if (ret.isNull()) 3337 return ExprError(); 3338 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member, 3339 MemberLoc)); 3340 } 3341 3342 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union) 3343 << BaseType << BaseExpr->getSourceRange(); 3344 3345 return ExprError(); 3346} 3347 3348/// The main callback when the parser finds something like 3349/// expression . [nested-name-specifier] identifier 3350/// expression -> [nested-name-specifier] identifier 3351/// where 'identifier' encompasses a fairly broad spectrum of 3352/// possibilities, including destructor and operator references. 3353/// 3354/// \param OpKind either tok::arrow or tok::period 3355/// \param HasTrailingLParen whether the next token is '(', which 3356/// is used to diagnose mis-uses of special members that can 3357/// only be called 3358/// \param ObjCImpDecl the current ObjC @implementation decl; 3359/// this is an ugly hack around the fact that ObjC @implementations 3360/// aren't properly put in the context chain 3361ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base, 3362 SourceLocation OpLoc, 3363 tok::TokenKind OpKind, 3364 CXXScopeSpec &SS, 3365 UnqualifiedId &Id, 3366 Decl *ObjCImpDecl, 3367 bool HasTrailingLParen) { 3368 if (SS.isSet() && SS.isInvalid()) 3369 return ExprError(); 3370 3371 TemplateArgumentListInfo TemplateArgsBuffer; 3372 3373 // Decompose the name into its component parts. 3374 DeclarationNameInfo NameInfo; 3375 const TemplateArgumentListInfo *TemplateArgs; 3376 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, 3377 NameInfo, TemplateArgs); 3378 3379 DeclarationName Name = NameInfo.getName(); 3380 bool IsArrow = (OpKind == tok::arrow); 3381 3382 NamedDecl *FirstQualifierInScope 3383 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S, 3384 static_cast<NestedNameSpecifier*>(SS.getScopeRep()))); 3385 3386 // This is a postfix expression, so get rid of ParenListExprs. 3387 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 3388 if (Result.isInvalid()) return ExprError(); 3389 Base = Result.take(); 3390 3391 if (Base->getType()->isDependentType() || Name.isDependentName() || 3392 isDependentScopeSpecifier(SS)) { 3393 Result = ActOnDependentMemberExpr(Base, Base->getType(), 3394 IsArrow, OpLoc, 3395 SS, FirstQualifierInScope, 3396 NameInfo, TemplateArgs); 3397 } else { 3398 LookupResult R(*this, NameInfo, LookupMemberName); 3399 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc, 3400 SS, ObjCImpDecl, TemplateArgs != 0); 3401 3402 if (Result.isInvalid()) { 3403 Owned(Base); 3404 return ExprError(); 3405 } 3406 3407 if (Result.get()) { 3408 // The only way a reference to a destructor can be used is to 3409 // immediately call it, which falls into this case. If the 3410 // next token is not a '(', produce a diagnostic and build the 3411 // call now. 3412 if (!HasTrailingLParen && 3413 Id.getKind() == UnqualifiedId::IK_DestructorName) 3414 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get()); 3415 3416 return move(Result); 3417 } 3418 3419 Result = BuildMemberReferenceExpr(Base, Base->getType(), 3420 OpLoc, IsArrow, SS, FirstQualifierInScope, 3421 R, TemplateArgs); 3422 } 3423 3424 return move(Result); 3425} 3426 3427ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3428 FunctionDecl *FD, 3429 ParmVarDecl *Param) { 3430 if (Param->hasUnparsedDefaultArg()) { 3431 Diag(CallLoc, 3432 diag::err_use_of_default_argument_to_function_declared_later) << 3433 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 3434 Diag(UnparsedDefaultArgLocs[Param], 3435 diag::note_default_argument_declared_here); 3436 return ExprError(); 3437 } 3438 3439 if (Param->hasUninstantiatedDefaultArg()) { 3440 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 3441 3442 // Instantiate the expression. 3443 MultiLevelTemplateArgumentList ArgList 3444 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true); 3445 3446 std::pair<const TemplateArgument *, unsigned> Innermost 3447 = ArgList.getInnermost(); 3448 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first, 3449 Innermost.second); 3450 3451 ExprResult Result = SubstExpr(UninstExpr, ArgList); 3452 if (Result.isInvalid()) 3453 return ExprError(); 3454 3455 // Check the expression as an initializer for the parameter. 3456 InitializedEntity Entity 3457 = InitializedEntity::InitializeParameter(Context, Param); 3458 InitializationKind Kind 3459 = InitializationKind::CreateCopy(Param->getLocation(), 3460 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin()); 3461 Expr *ResultE = Result.takeAs<Expr>(); 3462 3463 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1); 3464 Result = InitSeq.Perform(*this, Entity, Kind, 3465 MultiExprArg(*this, &ResultE, 1)); 3466 if (Result.isInvalid()) 3467 return ExprError(); 3468 3469 // Build the default argument expression. 3470 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, 3471 Result.takeAs<Expr>())); 3472 } 3473 3474 // If the default expression creates temporaries, we need to 3475 // push them to the current stack of expression temporaries so they'll 3476 // be properly destroyed. 3477 // FIXME: We should really be rebuilding the default argument with new 3478 // bound temporaries; see the comment in PR5810. 3479 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) { 3480 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i); 3481 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(), 3482 const_cast<CXXDestructorDecl*>(Temporary->getDestructor())); 3483 ExprTemporaries.push_back(Temporary); 3484 } 3485 3486 // We already type-checked the argument, so we know it works. 3487 // Just mark all of the declarations in this potentially-evaluated expression 3488 // as being "referenced". 3489 MarkDeclarationsReferencedInExpr(Param->getDefaultArg()); 3490 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param)); 3491} 3492 3493/// ConvertArgumentsForCall - Converts the arguments specified in 3494/// Args/NumArgs to the parameter types of the function FDecl with 3495/// function prototype Proto. Call is the call expression itself, and 3496/// Fn is the function expression. For a C++ member function, this 3497/// routine does not attempt to convert the object argument. Returns 3498/// true if the call is ill-formed. 3499bool 3500Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 3501 FunctionDecl *FDecl, 3502 const FunctionProtoType *Proto, 3503 Expr **Args, unsigned NumArgs, 3504 SourceLocation RParenLoc) { 3505 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 3506 // assignment, to the types of the corresponding parameter, ... 3507 unsigned NumArgsInProto = Proto->getNumArgs(); 3508 bool Invalid = false; 3509 3510 // If too few arguments are available (and we don't have default 3511 // arguments for the remaining parameters), don't make the call. 3512 if (NumArgs < NumArgsInProto) { 3513 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) 3514 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args) 3515 << Fn->getType()->isBlockPointerType() 3516 << NumArgsInProto << NumArgs << Fn->getSourceRange(); 3517 Call->setNumArgs(Context, NumArgsInProto); 3518 } 3519 3520 // If too many are passed and not variadic, error on the extras and drop 3521 // them. 3522 if (NumArgs > NumArgsInProto) { 3523 if (!Proto->isVariadic()) { 3524 Diag(Args[NumArgsInProto]->getLocStart(), 3525 diag::err_typecheck_call_too_many_args) 3526 << Fn->getType()->isBlockPointerType() 3527 << NumArgsInProto << NumArgs << Fn->getSourceRange() 3528 << SourceRange(Args[NumArgsInProto]->getLocStart(), 3529 Args[NumArgs-1]->getLocEnd()); 3530 // This deletes the extra arguments. 3531 Call->setNumArgs(Context, NumArgsInProto); 3532 return true; 3533 } 3534 } 3535 llvm::SmallVector<Expr *, 8> AllArgs; 3536 VariadicCallType CallType = 3537 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply; 3538 if (Fn->getType()->isBlockPointerType()) 3539 CallType = VariadicBlock; // Block 3540 else if (isa<MemberExpr>(Fn)) 3541 CallType = VariadicMethod; 3542 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl, 3543 Proto, 0, Args, NumArgs, AllArgs, CallType); 3544 if (Invalid) 3545 return true; 3546 unsigned TotalNumArgs = AllArgs.size(); 3547 for (unsigned i = 0; i < TotalNumArgs; ++i) 3548 Call->setArg(i, AllArgs[i]); 3549 3550 return false; 3551} 3552 3553bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, 3554 FunctionDecl *FDecl, 3555 const FunctionProtoType *Proto, 3556 unsigned FirstProtoArg, 3557 Expr **Args, unsigned NumArgs, 3558 llvm::SmallVector<Expr *, 8> &AllArgs, 3559 VariadicCallType CallType) { 3560 unsigned NumArgsInProto = Proto->getNumArgs(); 3561 unsigned NumArgsToCheck = NumArgs; 3562 bool Invalid = false; 3563 if (NumArgs != NumArgsInProto) 3564 // Use default arguments for missing arguments 3565 NumArgsToCheck = NumArgsInProto; 3566 unsigned ArgIx = 0; 3567 // Continue to check argument types (even if we have too few/many args). 3568 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) { 3569 QualType ProtoArgType = Proto->getArgType(i); 3570 3571 Expr *Arg; 3572 if (ArgIx < NumArgs) { 3573 Arg = Args[ArgIx++]; 3574 3575 if (RequireCompleteType(Arg->getSourceRange().getBegin(), 3576 ProtoArgType, 3577 PDiag(diag::err_call_incomplete_argument) 3578 << Arg->getSourceRange())) 3579 return true; 3580 3581 // Pass the argument 3582 ParmVarDecl *Param = 0; 3583 if (FDecl && i < FDecl->getNumParams()) 3584 Param = FDecl->getParamDecl(i); 3585 3586 InitializedEntity Entity = 3587 Param? InitializedEntity::InitializeParameter(Context, Param) 3588 : InitializedEntity::InitializeParameter(Context, ProtoArgType); 3589 ExprResult ArgE = PerformCopyInitialization(Entity, 3590 SourceLocation(), 3591 Owned(Arg)); 3592 if (ArgE.isInvalid()) 3593 return true; 3594 3595 Arg = ArgE.takeAs<Expr>(); 3596 } else { 3597 ParmVarDecl *Param = FDecl->getParamDecl(i); 3598 3599 ExprResult ArgExpr = 3600 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 3601 if (ArgExpr.isInvalid()) 3602 return true; 3603 3604 Arg = ArgExpr.takeAs<Expr>(); 3605 } 3606 AllArgs.push_back(Arg); 3607 } 3608 3609 // If this is a variadic call, handle args passed through "...". 3610 if (CallType != VariadicDoesNotApply) { 3611 // Promote the arguments (C99 6.5.2.2p7). 3612 for (unsigned i = ArgIx; i != NumArgs; ++i) { 3613 Expr *Arg = Args[i]; 3614 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl); 3615 AllArgs.push_back(Arg); 3616 } 3617 } 3618 return Invalid; 3619} 3620 3621/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 3622/// This provides the location of the left/right parens and a list of comma 3623/// locations. 3624ExprResult 3625Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 3626 MultiExprArg args, SourceLocation RParenLoc) { 3627 unsigned NumArgs = args.size(); 3628 3629 // Since this might be a postfix expression, get rid of ParenListExprs. 3630 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 3631 if (Result.isInvalid()) return ExprError(); 3632 Fn = Result.take(); 3633 3634 Expr **Args = args.release(); 3635 3636 if (getLangOptions().CPlusPlus) { 3637 // If this is a pseudo-destructor expression, build the call immediately. 3638 if (isa<CXXPseudoDestructorExpr>(Fn)) { 3639 if (NumArgs > 0) { 3640 // Pseudo-destructor calls should not have any arguments. 3641 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 3642 << FixItHint::CreateRemoval( 3643 SourceRange(Args[0]->getLocStart(), 3644 Args[NumArgs-1]->getLocEnd())); 3645 3646 NumArgs = 0; 3647 } 3648 3649 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy, 3650 RParenLoc)); 3651 } 3652 3653 // Determine whether this is a dependent call inside a C++ template, 3654 // in which case we won't do any semantic analysis now. 3655 // FIXME: Will need to cache the results of name lookup (including ADL) in 3656 // Fn. 3657 bool Dependent = false; 3658 if (Fn->isTypeDependent()) 3659 Dependent = true; 3660 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs)) 3661 Dependent = true; 3662 3663 if (Dependent) 3664 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs, 3665 Context.DependentTy, RParenLoc)); 3666 3667 // Determine whether this is a call to an object (C++ [over.call.object]). 3668 if (Fn->getType()->isRecordType()) 3669 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs, 3670 RParenLoc)); 3671 3672 Expr *NakedFn = Fn->IgnoreParens(); 3673 3674 // Determine whether this is a call to an unresolved member function. 3675 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) { 3676 // If lookup was unresolved but not dependent (i.e. didn't find 3677 // an unresolved using declaration), it has to be an overloaded 3678 // function set, which means it must contain either multiple 3679 // declarations (all methods or method templates) or a single 3680 // method template. 3681 assert((MemE->getNumDecls() > 1) || 3682 isa<FunctionTemplateDecl>( 3683 (*MemE->decls_begin())->getUnderlyingDecl())); 3684 (void)MemE; 3685 3686 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs, 3687 RParenLoc); 3688 } 3689 3690 // Determine whether this is a call to a member function. 3691 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) { 3692 NamedDecl *MemDecl = MemExpr->getMemberDecl(); 3693 if (isa<CXXMethodDecl>(MemDecl)) 3694 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs, 3695 RParenLoc); 3696 } 3697 3698 // Determine whether this is a call to a pointer-to-member function. 3699 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) { 3700 if (BO->getOpcode() == BO_PtrMemD || 3701 BO->getOpcode() == BO_PtrMemI) { 3702 if (const FunctionProtoType *FPT 3703 = BO->getType()->getAs<FunctionProtoType>()) { 3704 QualType ResultTy = FPT->getCallResultType(Context); 3705 3706 CXXMemberCallExpr *TheCall 3707 = new (Context) CXXMemberCallExpr(Context, BO, Args, 3708 NumArgs, ResultTy, 3709 RParenLoc); 3710 3711 if (CheckCallReturnType(FPT->getResultType(), 3712 BO->getRHS()->getSourceRange().getBegin(), 3713 TheCall, 0)) 3714 return ExprError(); 3715 3716 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs, 3717 RParenLoc)) 3718 return ExprError(); 3719 3720 return MaybeBindToTemporary(TheCall); 3721 } 3722 return ExprError(Diag(Fn->getLocStart(), 3723 diag::err_typecheck_call_not_function) 3724 << Fn->getType() << Fn->getSourceRange()); 3725 } 3726 } 3727 } 3728 3729 // If we're directly calling a function, get the appropriate declaration. 3730 // Also, in C++, keep track of whether we should perform argument-dependent 3731 // lookup and whether there were any explicitly-specified template arguments. 3732 3733 Expr *NakedFn = Fn->IgnoreParens(); 3734 if (isa<UnresolvedLookupExpr>(NakedFn)) { 3735 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn); 3736 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs, 3737 RParenLoc); 3738 } 3739 3740 NamedDecl *NDecl = 0; 3741 if (isa<DeclRefExpr>(NakedFn)) 3742 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 3743 3744 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc); 3745} 3746 3747/// BuildResolvedCallExpr - Build a call to a resolved expression, 3748/// i.e. an expression not of \p OverloadTy. The expression should 3749/// unary-convert to an expression of function-pointer or 3750/// block-pointer type. 3751/// 3752/// \param NDecl the declaration being called, if available 3753ExprResult 3754Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 3755 SourceLocation LParenLoc, 3756 Expr **Args, unsigned NumArgs, 3757 SourceLocation RParenLoc) { 3758 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 3759 3760 // Promote the function operand. 3761 UsualUnaryConversions(Fn); 3762 3763 // Make the call expr early, before semantic checks. This guarantees cleanup 3764 // of arguments and function on error. 3765 CallExpr *TheCall = new (Context) CallExpr(Context, Fn, 3766 Args, NumArgs, 3767 Context.BoolTy, 3768 RParenLoc); 3769 3770 const FunctionType *FuncT; 3771 if (!Fn->getType()->isBlockPointerType()) { 3772 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 3773 // have type pointer to function". 3774 const PointerType *PT = Fn->getType()->getAs<PointerType>(); 3775 if (PT == 0) 3776 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 3777 << Fn->getType() << Fn->getSourceRange()); 3778 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 3779 } else { // This is a block call. 3780 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()-> 3781 getAs<FunctionType>(); 3782 } 3783 if (FuncT == 0) 3784 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 3785 << Fn->getType() << Fn->getSourceRange()); 3786 3787 // Check for a valid return type 3788 if (CheckCallReturnType(FuncT->getResultType(), 3789 Fn->getSourceRange().getBegin(), TheCall, 3790 FDecl)) 3791 return ExprError(); 3792 3793 // We know the result type of the call, set it. 3794 TheCall->setType(FuncT->getCallResultType(Context)); 3795 3796 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) { 3797 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs, 3798 RParenLoc)) 3799 return ExprError(); 3800 } else { 3801 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 3802 3803 if (FDecl) { 3804 // Check if we have too few/too many template arguments, based 3805 // on our knowledge of the function definition. 3806 const FunctionDecl *Def = 0; 3807 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) { 3808 const FunctionProtoType *Proto = 3809 Def->getType()->getAs<FunctionProtoType>(); 3810 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) { 3811 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 3812 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange(); 3813 } 3814 } 3815 } 3816 3817 // Promote the arguments (C99 6.5.2.2p6). 3818 for (unsigned i = 0; i != NumArgs; i++) { 3819 Expr *Arg = Args[i]; 3820 DefaultArgumentPromotion(Arg); 3821 if (RequireCompleteType(Arg->getSourceRange().getBegin(), 3822 Arg->getType(), 3823 PDiag(diag::err_call_incomplete_argument) 3824 << Arg->getSourceRange())) 3825 return ExprError(); 3826 TheCall->setArg(i, Arg); 3827 } 3828 } 3829 3830 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 3831 if (!Method->isStatic()) 3832 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 3833 << Fn->getSourceRange()); 3834 3835 // Check for sentinels 3836 if (NDecl) 3837 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs); 3838 3839 // Do special checking on direct calls to functions. 3840 if (FDecl) { 3841 if (CheckFunctionCall(FDecl, TheCall)) 3842 return ExprError(); 3843 3844 if (unsigned BuiltinID = FDecl->getBuiltinID()) 3845 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 3846 } else if (NDecl) { 3847 if (CheckBlockCall(NDecl, TheCall)) 3848 return ExprError(); 3849 } 3850 3851 return MaybeBindToTemporary(TheCall); 3852} 3853 3854ExprResult 3855Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 3856 SourceLocation RParenLoc, Expr *InitExpr) { 3857 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type"); 3858 // FIXME: put back this assert when initializers are worked out. 3859 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 3860 3861 TypeSourceInfo *TInfo; 3862 QualType literalType = GetTypeFromParser(Ty, &TInfo); 3863 if (!TInfo) 3864 TInfo = Context.getTrivialTypeSourceInfo(literalType); 3865 3866 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 3867} 3868 3869ExprResult 3870Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 3871 SourceLocation RParenLoc, Expr *literalExpr) { 3872 QualType literalType = TInfo->getType(); 3873 3874 if (literalType->isArrayType()) { 3875 if (literalType->isVariableArrayType()) 3876 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 3877 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())); 3878 } else if (!literalType->isDependentType() && 3879 RequireCompleteType(LParenLoc, literalType, 3880 PDiag(diag::err_typecheck_decl_incomplete_type) 3881 << SourceRange(LParenLoc, 3882 literalExpr->getSourceRange().getEnd()))) 3883 return ExprError(); 3884 3885 InitializedEntity Entity 3886 = InitializedEntity::InitializeTemporary(literalType); 3887 InitializationKind Kind 3888 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc), 3889 /*IsCStyleCast=*/true); 3890 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1); 3891 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 3892 MultiExprArg(*this, &literalExpr, 1), 3893 &literalType); 3894 if (Result.isInvalid()) 3895 return ExprError(); 3896 literalExpr = Result.get(); 3897 3898 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 3899 if (isFileScope) { // 6.5.2.5p3 3900 if (CheckForConstantInitializer(literalExpr, literalType)) 3901 return ExprError(); 3902 } 3903 3904 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 3905 literalExpr, isFileScope)); 3906} 3907 3908ExprResult 3909Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist, 3910 SourceLocation RBraceLoc) { 3911 unsigned NumInit = initlist.size(); 3912 Expr **InitList = initlist.release(); 3913 3914 // Semantic analysis for initializers is done by ActOnDeclarator() and 3915 // CheckInitializer() - it requires knowledge of the object being intialized. 3916 3917 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList, 3918 NumInit, RBraceLoc); 3919 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 3920 return Owned(E); 3921} 3922 3923static CastKind getScalarCastKind(ASTContext &Context, 3924 QualType SrcTy, QualType DestTy) { 3925 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 3926 return CK_NoOp; 3927 3928 if (SrcTy->hasPointerRepresentation()) { 3929 if (DestTy->hasPointerRepresentation()) 3930 return DestTy->isObjCObjectPointerType() ? 3931 CK_AnyPointerToObjCPointerCast : 3932 CK_BitCast; 3933 if (DestTy->isIntegerType()) 3934 return CK_PointerToIntegral; 3935 } 3936 3937 if (SrcTy->isIntegerType()) { 3938 if (DestTy->isIntegerType()) 3939 return CK_IntegralCast; 3940 if (DestTy->hasPointerRepresentation()) 3941 return CK_IntegralToPointer; 3942 if (DestTy->isRealFloatingType()) 3943 return CK_IntegralToFloating; 3944 } 3945 3946 if (SrcTy->isRealFloatingType()) { 3947 if (DestTy->isRealFloatingType()) 3948 return CK_FloatingCast; 3949 if (DestTy->isIntegerType()) 3950 return CK_FloatingToIntegral; 3951 } 3952 3953 // FIXME: Assert here. 3954 // assert(false && "Unhandled cast combination!"); 3955 return CK_Unknown; 3956} 3957 3958/// CheckCastTypes - Check type constraints for casting between types. 3959bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr, 3960 CastKind& Kind, 3961 CXXCastPath &BasePath, 3962 bool FunctionalStyle) { 3963 if (getLangOptions().CPlusPlus) 3964 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, BasePath, 3965 FunctionalStyle); 3966 3967 DefaultFunctionArrayLvalueConversion(castExpr); 3968 3969 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression 3970 // type needs to be scalar. 3971 if (castType->isVoidType()) { 3972 // Cast to void allows any expr type. 3973 Kind = CK_ToVoid; 3974 return false; 3975 } 3976 3977 if (RequireCompleteType(TyR.getBegin(), castType, 3978 diag::err_typecheck_cast_to_incomplete)) 3979 return true; 3980 3981 if (!castType->isScalarType() && !castType->isVectorType()) { 3982 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) && 3983 (castType->isStructureType() || castType->isUnionType())) { 3984 // GCC struct/union extension: allow cast to self. 3985 // FIXME: Check that the cast destination type is complete. 3986 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar) 3987 << castType << castExpr->getSourceRange(); 3988 Kind = CK_NoOp; 3989 return false; 3990 } 3991 3992 if (castType->isUnionType()) { 3993 // GCC cast to union extension 3994 RecordDecl *RD = castType->getAs<RecordType>()->getDecl(); 3995 RecordDecl::field_iterator Field, FieldEnd; 3996 for (Field = RD->field_begin(), FieldEnd = RD->field_end(); 3997 Field != FieldEnd; ++Field) { 3998 if (Context.hasSameUnqualifiedType(Field->getType(), 3999 castExpr->getType()) && 4000 !Field->isUnnamedBitfield()) { 4001 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union) 4002 << castExpr->getSourceRange(); 4003 break; 4004 } 4005 } 4006 if (Field == FieldEnd) 4007 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type) 4008 << castExpr->getType() << castExpr->getSourceRange(); 4009 Kind = CK_ToUnion; 4010 return false; 4011 } 4012 4013 // Reject any other conversions to non-scalar types. 4014 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar) 4015 << castType << castExpr->getSourceRange(); 4016 } 4017 4018 if (!castExpr->getType()->isScalarType() && 4019 !castExpr->getType()->isVectorType()) { 4020 return Diag(castExpr->getLocStart(), 4021 diag::err_typecheck_expect_scalar_operand) 4022 << castExpr->getType() << castExpr->getSourceRange(); 4023 } 4024 4025 if (castType->isExtVectorType()) 4026 return CheckExtVectorCast(TyR, castType, castExpr, Kind); 4027 4028 if (castType->isVectorType()) 4029 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind); 4030 if (castExpr->getType()->isVectorType()) 4031 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind); 4032 4033 if (isa<ObjCSelectorExpr>(castExpr)) 4034 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr); 4035 4036 if (!castType->isArithmeticType()) { 4037 QualType castExprType = castExpr->getType(); 4038 if (!castExprType->isIntegralType(Context) && 4039 castExprType->isArithmeticType()) 4040 return Diag(castExpr->getLocStart(), 4041 diag::err_cast_pointer_from_non_pointer_int) 4042 << castExprType << castExpr->getSourceRange(); 4043 } else if (!castExpr->getType()->isArithmeticType()) { 4044 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) 4045 return Diag(castExpr->getLocStart(), 4046 diag::err_cast_pointer_to_non_pointer_int) 4047 << castType << castExpr->getSourceRange(); 4048 } 4049 4050 Kind = getScalarCastKind(Context, castExpr->getType(), castType); 4051 4052 if (Kind == CK_Unknown || Kind == CK_BitCast) 4053 CheckCastAlign(castExpr, castType, TyR); 4054 4055 return false; 4056} 4057 4058bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 4059 CastKind &Kind) { 4060 assert(VectorTy->isVectorType() && "Not a vector type!"); 4061 4062 if (Ty->isVectorType() || Ty->isIntegerType()) { 4063 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 4064 return Diag(R.getBegin(), 4065 Ty->isVectorType() ? 4066 diag::err_invalid_conversion_between_vectors : 4067 diag::err_invalid_conversion_between_vector_and_integer) 4068 << VectorTy << Ty << R; 4069 } else 4070 return Diag(R.getBegin(), 4071 diag::err_invalid_conversion_between_vector_and_scalar) 4072 << VectorTy << Ty << R; 4073 4074 Kind = CK_BitCast; 4075 return false; 4076} 4077 4078bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr, 4079 CastKind &Kind) { 4080 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 4081 4082 QualType SrcTy = CastExpr->getType(); 4083 4084 // If SrcTy is a VectorType, the total size must match to explicitly cast to 4085 // an ExtVectorType. 4086 if (SrcTy->isVectorType()) { 4087 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 4088 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 4089 << DestTy << SrcTy << R; 4090 Kind = CK_BitCast; 4091 return false; 4092 } 4093 4094 // All non-pointer scalars can be cast to ExtVector type. The appropriate 4095 // conversion will take place first from scalar to elt type, and then 4096 // splat from elt type to vector. 4097 if (SrcTy->isPointerType()) 4098 return Diag(R.getBegin(), 4099 diag::err_invalid_conversion_between_vector_and_scalar) 4100 << DestTy << SrcTy << R; 4101 4102 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 4103 ImpCastExprToType(CastExpr, DestElemTy, 4104 getScalarCastKind(Context, SrcTy, DestElemTy)); 4105 4106 Kind = CK_VectorSplat; 4107 return false; 4108} 4109 4110ExprResult 4111Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty, 4112 SourceLocation RParenLoc, Expr *castExpr) { 4113 assert((Ty != 0) && (castExpr != 0) && 4114 "ActOnCastExpr(): missing type or expr"); 4115 4116 TypeSourceInfo *castTInfo; 4117 QualType castType = GetTypeFromParser(Ty, &castTInfo); 4118 if (!castTInfo) 4119 castTInfo = Context.getTrivialTypeSourceInfo(castType); 4120 4121 // If the Expr being casted is a ParenListExpr, handle it specially. 4122 if (isa<ParenListExpr>(castExpr)) 4123 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr, 4124 castTInfo); 4125 4126 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr); 4127} 4128 4129ExprResult 4130Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, 4131 SourceLocation RParenLoc, Expr *castExpr) { 4132 CastKind Kind = CK_Unknown; 4133 CXXCastPath BasePath; 4134 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr, 4135 Kind, BasePath)) 4136 return ExprError(); 4137 4138 return Owned(CStyleCastExpr::Create(Context, 4139 Ty->getType().getNonLValueExprType(Context), 4140 Kind, castExpr, &BasePath, Ty, 4141 LParenLoc, RParenLoc)); 4142} 4143 4144/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence 4145/// of comma binary operators. 4146ExprResult 4147Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) { 4148 ParenListExpr *E = dyn_cast<ParenListExpr>(expr); 4149 if (!E) 4150 return Owned(expr); 4151 4152 ExprResult Result(E->getExpr(0)); 4153 4154 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 4155 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 4156 E->getExpr(i)); 4157 4158 if (Result.isInvalid()) return ExprError(); 4159 4160 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 4161} 4162 4163ExprResult 4164Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc, 4165 SourceLocation RParenLoc, Expr *Op, 4166 TypeSourceInfo *TInfo) { 4167 ParenListExpr *PE = cast<ParenListExpr>(Op); 4168 QualType Ty = TInfo->getType(); 4169 bool isAltiVecLiteral = false; 4170 4171 // Check for an altivec literal, 4172 // i.e. all the elements are integer constants. 4173 if (getLangOptions().AltiVec && Ty->isVectorType()) { 4174 if (PE->getNumExprs() == 0) { 4175 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer); 4176 return ExprError(); 4177 } 4178 if (PE->getNumExprs() == 1) { 4179 if (!PE->getExpr(0)->getType()->isVectorType()) 4180 isAltiVecLiteral = true; 4181 } 4182 else 4183 isAltiVecLiteral = true; 4184 } 4185 4186 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')' 4187 // then handle it as such. 4188 if (isAltiVecLiteral) { 4189 llvm::SmallVector<Expr *, 8> initExprs; 4190 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i) 4191 initExprs.push_back(PE->getExpr(i)); 4192 4193 // FIXME: This means that pretty-printing the final AST will produce curly 4194 // braces instead of the original commas. 4195 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc, 4196 &initExprs[0], 4197 initExprs.size(), RParenLoc); 4198 E->setType(Ty); 4199 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E); 4200 } else { 4201 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 4202 // sequence of BinOp comma operators. 4203 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op); 4204 if (Result.isInvalid()) return ExprError(); 4205 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take()); 4206 } 4207} 4208 4209ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L, 4210 SourceLocation R, 4211 MultiExprArg Val, 4212 ParsedType TypeOfCast) { 4213 unsigned nexprs = Val.size(); 4214 Expr **exprs = reinterpret_cast<Expr**>(Val.release()); 4215 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list"); 4216 Expr *expr; 4217 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast)) 4218 expr = new (Context) ParenExpr(L, R, exprs[0]); 4219 else 4220 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R); 4221 return Owned(expr); 4222} 4223 4224/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension. 4225/// In that case, lhs = cond. 4226/// C99 6.5.15 4227QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS, 4228 Expr *&SAVE, 4229 SourceLocation QuestionLoc) { 4230 // C++ is sufficiently different to merit its own checker. 4231 if (getLangOptions().CPlusPlus) 4232 return CXXCheckConditionalOperands(Cond, LHS, RHS, SAVE, QuestionLoc); 4233 4234 UsualUnaryConversions(Cond); 4235 if (SAVE) { 4236 SAVE = LHS = Cond; 4237 } 4238 else 4239 UsualUnaryConversions(LHS); 4240 UsualUnaryConversions(RHS); 4241 QualType CondTy = Cond->getType(); 4242 QualType LHSTy = LHS->getType(); 4243 QualType RHSTy = RHS->getType(); 4244 4245 // first, check the condition. 4246 if (!CondTy->isScalarType()) { // C99 6.5.15p2 4247 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar. 4248 // Throw an error if its not either. 4249 if (getLangOptions().OpenCL) { 4250 if (!CondTy->isVectorType()) { 4251 Diag(Cond->getLocStart(), 4252 diag::err_typecheck_cond_expect_scalar_or_vector) 4253 << CondTy; 4254 return QualType(); 4255 } 4256 } 4257 else { 4258 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) 4259 << CondTy; 4260 return QualType(); 4261 } 4262 } 4263 4264 // Now check the two expressions. 4265 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 4266 return CheckVectorOperands(QuestionLoc, LHS, RHS); 4267 4268 // OpenCL: If the condition is a vector, and both operands are scalar, 4269 // attempt to implicity convert them to the vector type to act like the 4270 // built in select. 4271 if (getLangOptions().OpenCL && CondTy->isVectorType()) { 4272 // Both operands should be of scalar type. 4273 if (!LHSTy->isScalarType()) { 4274 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar) 4275 << CondTy; 4276 return QualType(); 4277 } 4278 if (!RHSTy->isScalarType()) { 4279 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar) 4280 << CondTy; 4281 return QualType(); 4282 } 4283 // Implicity convert these scalars to the type of the condition. 4284 ImpCastExprToType(LHS, CondTy, CK_IntegralCast); 4285 ImpCastExprToType(RHS, CondTy, CK_IntegralCast); 4286 } 4287 4288 // If both operands have arithmetic type, do the usual arithmetic conversions 4289 // to find a common type: C99 6.5.15p3,5. 4290 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 4291 UsualArithmeticConversions(LHS, RHS); 4292 return LHS->getType(); 4293 } 4294 4295 // If both operands are the same structure or union type, the result is that 4296 // type. 4297 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 4298 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 4299 if (LHSRT->getDecl() == RHSRT->getDecl()) 4300 // "If both the operands have structure or union type, the result has 4301 // that type." This implies that CV qualifiers are dropped. 4302 return LHSTy.getUnqualifiedType(); 4303 // FIXME: Type of conditional expression must be complete in C mode. 4304 } 4305 4306 // C99 6.5.15p5: "If both operands have void type, the result has void type." 4307 // The following || allows only one side to be void (a GCC-ism). 4308 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 4309 if (!LHSTy->isVoidType()) 4310 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void) 4311 << RHS->getSourceRange(); 4312 if (!RHSTy->isVoidType()) 4313 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void) 4314 << LHS->getSourceRange(); 4315 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid); 4316 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid); 4317 return Context.VoidTy; 4318 } 4319 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 4320 // the type of the other operand." 4321 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) && 4322 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 4323 // promote the null to a pointer. 4324 ImpCastExprToType(RHS, LHSTy, CK_Unknown); 4325 return LHSTy; 4326 } 4327 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) && 4328 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 4329 ImpCastExprToType(LHS, RHSTy, CK_Unknown); 4330 return RHSTy; 4331 } 4332 4333 // All objective-c pointer type analysis is done here. 4334 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 4335 QuestionLoc); 4336 if (!compositeType.isNull()) 4337 return compositeType; 4338 4339 4340 // Handle block pointer types. 4341 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 4342 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 4343 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 4344 QualType destType = Context.getPointerType(Context.VoidTy); 4345 ImpCastExprToType(LHS, destType, CK_BitCast); 4346 ImpCastExprToType(RHS, destType, CK_BitCast); 4347 return destType; 4348 } 4349 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 4350 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 4351 return QualType(); 4352 } 4353 // We have 2 block pointer types. 4354 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 4355 // Two identical block pointer types are always compatible. 4356 return LHSTy; 4357 } 4358 // The block pointer types aren't identical, continue checking. 4359 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType(); 4360 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType(); 4361 4362 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 4363 rhptee.getUnqualifiedType())) { 4364 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers) 4365 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 4366 // In this situation, we assume void* type. No especially good 4367 // reason, but this is what gcc does, and we do have to pick 4368 // to get a consistent AST. 4369 QualType incompatTy = Context.getPointerType(Context.VoidTy); 4370 ImpCastExprToType(LHS, incompatTy, CK_BitCast); 4371 ImpCastExprToType(RHS, incompatTy, CK_BitCast); 4372 return incompatTy; 4373 } 4374 // The block pointer types are compatible. 4375 ImpCastExprToType(LHS, LHSTy, CK_BitCast); 4376 ImpCastExprToType(RHS, LHSTy, CK_BitCast); 4377 return LHSTy; 4378 } 4379 4380 // Check constraints for C object pointers types (C99 6.5.15p3,6). 4381 if (LHSTy->isPointerType() && RHSTy->isPointerType()) { 4382 // get the "pointed to" types 4383 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 4384 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 4385 4386 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 4387 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 4388 // Figure out necessary qualifiers (C99 6.5.15p6) 4389 QualType destPointee 4390 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 4391 QualType destType = Context.getPointerType(destPointee); 4392 // Add qualifiers if necessary. 4393 ImpCastExprToType(LHS, destType, CK_NoOp); 4394 // Promote to void*. 4395 ImpCastExprToType(RHS, destType, CK_BitCast); 4396 return destType; 4397 } 4398 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 4399 QualType destPointee 4400 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 4401 QualType destType = Context.getPointerType(destPointee); 4402 // Add qualifiers if necessary. 4403 ImpCastExprToType(RHS, destType, CK_NoOp); 4404 // Promote to void*. 4405 ImpCastExprToType(LHS, destType, CK_BitCast); 4406 return destType; 4407 } 4408 4409 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 4410 // Two identical pointer types are always compatible. 4411 return LHSTy; 4412 } 4413 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 4414 rhptee.getUnqualifiedType())) { 4415 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers) 4416 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 4417 // In this situation, we assume void* type. No especially good 4418 // reason, but this is what gcc does, and we do have to pick 4419 // to get a consistent AST. 4420 QualType incompatTy = Context.getPointerType(Context.VoidTy); 4421 ImpCastExprToType(LHS, incompatTy, CK_BitCast); 4422 ImpCastExprToType(RHS, incompatTy, CK_BitCast); 4423 return incompatTy; 4424 } 4425 // The pointer types are compatible. 4426 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to 4427 // differently qualified versions of compatible types, the result type is 4428 // a pointer to an appropriately qualified version of the *composite* 4429 // type. 4430 // FIXME: Need to calculate the composite type. 4431 // FIXME: Need to add qualifiers 4432 ImpCastExprToType(LHS, LHSTy, CK_BitCast); 4433 ImpCastExprToType(RHS, LHSTy, CK_BitCast); 4434 return LHSTy; 4435 } 4436 4437 // GCC compatibility: soften pointer/integer mismatch. 4438 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) { 4439 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch) 4440 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 4441 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer); 4442 return RHSTy; 4443 } 4444 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) { 4445 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch) 4446 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 4447 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer); 4448 return LHSTy; 4449 } 4450 4451 // Otherwise, the operands are not compatible. 4452 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 4453 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange(); 4454 return QualType(); 4455} 4456 4457/// FindCompositeObjCPointerType - Helper method to find composite type of 4458/// two objective-c pointer types of the two input expressions. 4459QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS, 4460 SourceLocation QuestionLoc) { 4461 QualType LHSTy = LHS->getType(); 4462 QualType RHSTy = RHS->getType(); 4463 4464 // Handle things like Class and struct objc_class*. Here we case the result 4465 // to the pseudo-builtin, because that will be implicitly cast back to the 4466 // redefinition type if an attempt is made to access its fields. 4467 if (LHSTy->isObjCClassType() && 4468 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) { 4469 ImpCastExprToType(RHS, LHSTy, CK_BitCast); 4470 return LHSTy; 4471 } 4472 if (RHSTy->isObjCClassType() && 4473 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) { 4474 ImpCastExprToType(LHS, RHSTy, CK_BitCast); 4475 return RHSTy; 4476 } 4477 // And the same for struct objc_object* / id 4478 if (LHSTy->isObjCIdType() && 4479 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) { 4480 ImpCastExprToType(RHS, LHSTy, CK_BitCast); 4481 return LHSTy; 4482 } 4483 if (RHSTy->isObjCIdType() && 4484 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) { 4485 ImpCastExprToType(LHS, RHSTy, CK_BitCast); 4486 return RHSTy; 4487 } 4488 // And the same for struct objc_selector* / SEL 4489 if (Context.isObjCSelType(LHSTy) && 4490 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) { 4491 ImpCastExprToType(RHS, LHSTy, CK_BitCast); 4492 return LHSTy; 4493 } 4494 if (Context.isObjCSelType(RHSTy) && 4495 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) { 4496 ImpCastExprToType(LHS, RHSTy, CK_BitCast); 4497 return RHSTy; 4498 } 4499 // Check constraints for Objective-C object pointers types. 4500 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 4501 4502 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 4503 // Two identical object pointer types are always compatible. 4504 return LHSTy; 4505 } 4506 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>(); 4507 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>(); 4508 QualType compositeType = LHSTy; 4509 4510 // If both operands are interfaces and either operand can be 4511 // assigned to the other, use that type as the composite 4512 // type. This allows 4513 // xxx ? (A*) a : (B*) b 4514 // where B is a subclass of A. 4515 // 4516 // Additionally, as for assignment, if either type is 'id' 4517 // allow silent coercion. Finally, if the types are 4518 // incompatible then make sure to use 'id' as the composite 4519 // type so the result is acceptable for sending messages to. 4520 4521 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 4522 // It could return the composite type. 4523 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 4524 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 4525 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 4526 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 4527 } else if ((LHSTy->isObjCQualifiedIdType() || 4528 RHSTy->isObjCQualifiedIdType()) && 4529 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 4530 // Need to handle "id<xx>" explicitly. 4531 // GCC allows qualified id and any Objective-C type to devolve to 4532 // id. Currently localizing to here until clear this should be 4533 // part of ObjCQualifiedIdTypesAreCompatible. 4534 compositeType = Context.getObjCIdType(); 4535 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 4536 compositeType = Context.getObjCIdType(); 4537 } else if (!(compositeType = 4538 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 4539 ; 4540 else { 4541 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 4542 << LHSTy << RHSTy 4543 << LHS->getSourceRange() << RHS->getSourceRange(); 4544 QualType incompatTy = Context.getObjCIdType(); 4545 ImpCastExprToType(LHS, incompatTy, CK_BitCast); 4546 ImpCastExprToType(RHS, incompatTy, CK_BitCast); 4547 return incompatTy; 4548 } 4549 // The object pointer types are compatible. 4550 ImpCastExprToType(LHS, compositeType, CK_BitCast); 4551 ImpCastExprToType(RHS, compositeType, CK_BitCast); 4552 return compositeType; 4553 } 4554 // Check Objective-C object pointer types and 'void *' 4555 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 4556 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 4557 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 4558 QualType destPointee 4559 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 4560 QualType destType = Context.getPointerType(destPointee); 4561 // Add qualifiers if necessary. 4562 ImpCastExprToType(LHS, destType, CK_NoOp); 4563 // Promote to void*. 4564 ImpCastExprToType(RHS, destType, CK_BitCast); 4565 return destType; 4566 } 4567 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 4568 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 4569 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 4570 QualType destPointee 4571 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 4572 QualType destType = Context.getPointerType(destPointee); 4573 // Add qualifiers if necessary. 4574 ImpCastExprToType(RHS, destType, CK_NoOp); 4575 // Promote to void*. 4576 ImpCastExprToType(LHS, destType, CK_BitCast); 4577 return destType; 4578 } 4579 return QualType(); 4580} 4581 4582/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 4583/// in the case of a the GNU conditional expr extension. 4584ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 4585 SourceLocation ColonLoc, 4586 Expr *CondExpr, Expr *LHSExpr, 4587 Expr *RHSExpr) { 4588 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 4589 // was the condition. 4590 bool isLHSNull = LHSExpr == 0; 4591 Expr *SAVEExpr = 0; 4592 if (isLHSNull) { 4593 LHSExpr = SAVEExpr = CondExpr; 4594 } 4595 4596 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr, 4597 SAVEExpr, QuestionLoc); 4598 if (result.isNull()) 4599 return ExprError(); 4600 4601 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc, 4602 LHSExpr, ColonLoc, 4603 RHSExpr, SAVEExpr, 4604 result)); 4605} 4606 4607// CheckPointerTypesForAssignment - This is a very tricky routine (despite 4608// being closely modeled after the C99 spec:-). The odd characteristic of this 4609// routine is it effectively iqnores the qualifiers on the top level pointee. 4610// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 4611// FIXME: add a couple examples in this comment. 4612Sema::AssignConvertType 4613Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) { 4614 QualType lhptee, rhptee; 4615 4616 if ((lhsType->isObjCClassType() && 4617 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) || 4618 (rhsType->isObjCClassType() && 4619 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) { 4620 return Compatible; 4621 } 4622 4623 // get the "pointed to" type (ignoring qualifiers at the top level) 4624 lhptee = lhsType->getAs<PointerType>()->getPointeeType(); 4625 rhptee = rhsType->getAs<PointerType>()->getPointeeType(); 4626 4627 // make sure we operate on the canonical type 4628 lhptee = Context.getCanonicalType(lhptee); 4629 rhptee = Context.getCanonicalType(rhptee); 4630 4631 AssignConvertType ConvTy = Compatible; 4632 4633 // C99 6.5.16.1p1: This following citation is common to constraints 4634 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 4635 // qualifiers of the type *pointed to* by the right; 4636 // FIXME: Handle ExtQualType 4637 if (!lhptee.isAtLeastAsQualifiedAs(rhptee)) 4638 ConvTy = CompatiblePointerDiscardsQualifiers; 4639 4640 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 4641 // incomplete type and the other is a pointer to a qualified or unqualified 4642 // version of void... 4643 if (lhptee->isVoidType()) { 4644 if (rhptee->isIncompleteOrObjectType()) 4645 return ConvTy; 4646 4647 // As an extension, we allow cast to/from void* to function pointer. 4648 assert(rhptee->isFunctionType()); 4649 return FunctionVoidPointer; 4650 } 4651 4652 if (rhptee->isVoidType()) { 4653 if (lhptee->isIncompleteOrObjectType()) 4654 return ConvTy; 4655 4656 // As an extension, we allow cast to/from void* to function pointer. 4657 assert(lhptee->isFunctionType()); 4658 return FunctionVoidPointer; 4659 } 4660 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 4661 // unqualified versions of compatible types, ... 4662 lhptee = lhptee.getUnqualifiedType(); 4663 rhptee = rhptee.getUnqualifiedType(); 4664 if (!Context.typesAreCompatible(lhptee, rhptee)) { 4665 // Check if the pointee types are compatible ignoring the sign. 4666 // We explicitly check for char so that we catch "char" vs 4667 // "unsigned char" on systems where "char" is unsigned. 4668 if (lhptee->isCharType()) 4669 lhptee = Context.UnsignedCharTy; 4670 else if (lhptee->hasSignedIntegerRepresentation()) 4671 lhptee = Context.getCorrespondingUnsignedType(lhptee); 4672 4673 if (rhptee->isCharType()) 4674 rhptee = Context.UnsignedCharTy; 4675 else if (rhptee->hasSignedIntegerRepresentation()) 4676 rhptee = Context.getCorrespondingUnsignedType(rhptee); 4677 4678 if (lhptee == rhptee) { 4679 // Types are compatible ignoring the sign. Qualifier incompatibility 4680 // takes priority over sign incompatibility because the sign 4681 // warning can be disabled. 4682 if (ConvTy != Compatible) 4683 return ConvTy; 4684 return IncompatiblePointerSign; 4685 } 4686 4687 // If we are a multi-level pointer, it's possible that our issue is simply 4688 // one of qualification - e.g. char ** -> const char ** is not allowed. If 4689 // the eventual target type is the same and the pointers have the same 4690 // level of indirection, this must be the issue. 4691 if (lhptee->isPointerType() && rhptee->isPointerType()) { 4692 do { 4693 lhptee = lhptee->getAs<PointerType>()->getPointeeType(); 4694 rhptee = rhptee->getAs<PointerType>()->getPointeeType(); 4695 4696 lhptee = Context.getCanonicalType(lhptee); 4697 rhptee = Context.getCanonicalType(rhptee); 4698 } while (lhptee->isPointerType() && rhptee->isPointerType()); 4699 4700 if (Context.hasSameUnqualifiedType(lhptee, rhptee)) 4701 return IncompatibleNestedPointerQualifiers; 4702 } 4703 4704 // General pointer incompatibility takes priority over qualifiers. 4705 return IncompatiblePointer; 4706 } 4707 return ConvTy; 4708} 4709 4710/// CheckBlockPointerTypesForAssignment - This routine determines whether two 4711/// block pointer types are compatible or whether a block and normal pointer 4712/// are compatible. It is more restrict than comparing two function pointer 4713// types. 4714Sema::AssignConvertType 4715Sema::CheckBlockPointerTypesForAssignment(QualType lhsType, 4716 QualType rhsType) { 4717 QualType lhptee, rhptee; 4718 4719 // get the "pointed to" type (ignoring qualifiers at the top level) 4720 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType(); 4721 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType(); 4722 4723 // make sure we operate on the canonical type 4724 lhptee = Context.getCanonicalType(lhptee); 4725 rhptee = Context.getCanonicalType(rhptee); 4726 4727 AssignConvertType ConvTy = Compatible; 4728 4729 // For blocks we enforce that qualifiers are identical. 4730 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers()) 4731 ConvTy = CompatiblePointerDiscardsQualifiers; 4732 4733 if (!getLangOptions().CPlusPlus) { 4734 if (!Context.typesAreBlockPointerCompatible(lhsType, rhsType)) 4735 return IncompatibleBlockPointer; 4736 } 4737 else if (!Context.typesAreCompatible(lhptee, rhptee)) 4738 return IncompatibleBlockPointer; 4739 return ConvTy; 4740} 4741 4742/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types 4743/// for assignment compatibility. 4744Sema::AssignConvertType 4745Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) { 4746 if (lhsType->isObjCBuiltinType()) { 4747 // Class is not compatible with ObjC object pointers. 4748 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() && 4749 !rhsType->isObjCQualifiedClassType()) 4750 return IncompatiblePointer; 4751 return Compatible; 4752 } 4753 if (rhsType->isObjCBuiltinType()) { 4754 // Class is not compatible with ObjC object pointers. 4755 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() && 4756 !lhsType->isObjCQualifiedClassType()) 4757 return IncompatiblePointer; 4758 return Compatible; 4759 } 4760 QualType lhptee = 4761 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType(); 4762 QualType rhptee = 4763 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType(); 4764 // make sure we operate on the canonical type 4765 lhptee = Context.getCanonicalType(lhptee); 4766 rhptee = Context.getCanonicalType(rhptee); 4767 if (!lhptee.isAtLeastAsQualifiedAs(rhptee)) 4768 return CompatiblePointerDiscardsQualifiers; 4769 4770 if (Context.typesAreCompatible(lhsType, rhsType)) 4771 return Compatible; 4772 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) 4773 return IncompatibleObjCQualifiedId; 4774 return IncompatiblePointer; 4775} 4776 4777/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 4778/// has code to accommodate several GCC extensions when type checking 4779/// pointers. Here are some objectionable examples that GCC considers warnings: 4780/// 4781/// int a, *pint; 4782/// short *pshort; 4783/// struct foo *pfoo; 4784/// 4785/// pint = pshort; // warning: assignment from incompatible pointer type 4786/// a = pint; // warning: assignment makes integer from pointer without a cast 4787/// pint = a; // warning: assignment makes pointer from integer without a cast 4788/// pint = pfoo; // warning: assignment from incompatible pointer type 4789/// 4790/// As a result, the code for dealing with pointers is more complex than the 4791/// C99 spec dictates. 4792/// 4793Sema::AssignConvertType 4794Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) { 4795 // Get canonical types. We're not formatting these types, just comparing 4796 // them. 4797 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType(); 4798 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType(); 4799 4800 if (lhsType == rhsType) 4801 return Compatible; // Common case: fast path an exact match. 4802 4803 if ((lhsType->isObjCClassType() && 4804 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) || 4805 (rhsType->isObjCClassType() && 4806 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) { 4807 return Compatible; 4808 } 4809 4810 // If the left-hand side is a reference type, then we are in a 4811 // (rare!) case where we've allowed the use of references in C, 4812 // e.g., as a parameter type in a built-in function. In this case, 4813 // just make sure that the type referenced is compatible with the 4814 // right-hand side type. The caller is responsible for adjusting 4815 // lhsType so that the resulting expression does not have reference 4816 // type. 4817 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) { 4818 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) 4819 return Compatible; 4820 return Incompatible; 4821 } 4822 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 4823 // to the same ExtVector type. 4824 if (lhsType->isExtVectorType()) { 4825 if (rhsType->isExtVectorType()) 4826 return lhsType == rhsType ? Compatible : Incompatible; 4827 if (rhsType->isArithmeticType()) 4828 return Compatible; 4829 } 4830 4831 if (lhsType->isVectorType() || rhsType->isVectorType()) { 4832 if (lhsType->isVectorType() && rhsType->isVectorType()) { 4833 // If we are allowing lax vector conversions, and LHS and RHS are both 4834 // vectors, the total size only needs to be the same. This is a bitcast; 4835 // no bits are changed but the result type is different. 4836 if (getLangOptions().LaxVectorConversions && 4837 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) 4838 return IncompatibleVectors; 4839 4840 // Allow assignments of an AltiVec vector type to an equivalent GCC 4841 // vector type and vice versa 4842 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) 4843 return Compatible; 4844 } 4845 return Incompatible; 4846 } 4847 4848 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() && 4849 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) 4850 return Compatible; 4851 4852 if (isa<PointerType>(lhsType)) { 4853 if (rhsType->isIntegerType()) 4854 return IntToPointer; 4855 4856 if (isa<PointerType>(rhsType)) 4857 return CheckPointerTypesForAssignment(lhsType, rhsType); 4858 4859 // In general, C pointers are not compatible with ObjC object pointers. 4860 if (isa<ObjCObjectPointerType>(rhsType)) { 4861 if (lhsType->isVoidPointerType()) // an exception to the rule. 4862 return Compatible; 4863 return IncompatiblePointer; 4864 } 4865 if (rhsType->getAs<BlockPointerType>()) { 4866 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) 4867 return Compatible; 4868 4869 // Treat block pointers as objects. 4870 if (getLangOptions().ObjC1 && lhsType->isObjCIdType()) 4871 return Compatible; 4872 } 4873 return Incompatible; 4874 } 4875 4876 if (isa<BlockPointerType>(lhsType)) { 4877 if (rhsType->isIntegerType()) 4878 return IntToBlockPointer; 4879 4880 // Treat block pointers as objects. 4881 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) 4882 return Compatible; 4883 4884 if (rhsType->isBlockPointerType()) 4885 return CheckBlockPointerTypesForAssignment(lhsType, rhsType); 4886 4887 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) { 4888 if (RHSPT->getPointeeType()->isVoidType()) 4889 return Compatible; 4890 } 4891 return Incompatible; 4892 } 4893 4894 if (isa<ObjCObjectPointerType>(lhsType)) { 4895 if (rhsType->isIntegerType()) 4896 return IntToPointer; 4897 4898 // In general, C pointers are not compatible with ObjC object pointers. 4899 if (isa<PointerType>(rhsType)) { 4900 if (rhsType->isVoidPointerType()) // an exception to the rule. 4901 return Compatible; 4902 return IncompatiblePointer; 4903 } 4904 if (rhsType->isObjCObjectPointerType()) { 4905 return CheckObjCPointerTypesForAssignment(lhsType, rhsType); 4906 } 4907 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) { 4908 if (RHSPT->getPointeeType()->isVoidType()) 4909 return Compatible; 4910 } 4911 // Treat block pointers as objects. 4912 if (rhsType->isBlockPointerType()) 4913 return Compatible; 4914 return Incompatible; 4915 } 4916 if (isa<PointerType>(rhsType)) { 4917 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer. 4918 if (lhsType == Context.BoolTy) 4919 return Compatible; 4920 4921 if (lhsType->isIntegerType()) 4922 return PointerToInt; 4923 4924 if (isa<PointerType>(lhsType)) 4925 return CheckPointerTypesForAssignment(lhsType, rhsType); 4926 4927 if (isa<BlockPointerType>(lhsType) && 4928 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) 4929 return Compatible; 4930 return Incompatible; 4931 } 4932 if (isa<ObjCObjectPointerType>(rhsType)) { 4933 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer. 4934 if (lhsType == Context.BoolTy) 4935 return Compatible; 4936 4937 if (lhsType->isIntegerType()) 4938 return PointerToInt; 4939 4940 // In general, C pointers are not compatible with ObjC object pointers. 4941 if (isa<PointerType>(lhsType)) { 4942 if (lhsType->isVoidPointerType()) // an exception to the rule. 4943 return Compatible; 4944 return IncompatiblePointer; 4945 } 4946 if (isa<BlockPointerType>(lhsType) && 4947 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType()) 4948 return Compatible; 4949 return Incompatible; 4950 } 4951 4952 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) { 4953 if (Context.typesAreCompatible(lhsType, rhsType)) 4954 return Compatible; 4955 } 4956 return Incompatible; 4957} 4958 4959/// \brief Constructs a transparent union from an expression that is 4960/// used to initialize the transparent union. 4961static void ConstructTransparentUnion(ASTContext &C, Expr *&E, 4962 QualType UnionType, FieldDecl *Field) { 4963 // Build an initializer list that designates the appropriate member 4964 // of the transparent union. 4965 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 4966 &E, 1, 4967 SourceLocation()); 4968 Initializer->setType(UnionType); 4969 Initializer->setInitializedFieldInUnion(Field); 4970 4971 // Build a compound literal constructing a value of the transparent 4972 // union type from this initializer list. 4973 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 4974 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 4975 Initializer, false); 4976} 4977 4978Sema::AssignConvertType 4979Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) { 4980 QualType FromType = rExpr->getType(); 4981 4982 // If the ArgType is a Union type, we want to handle a potential 4983 // transparent_union GCC extension. 4984 const RecordType *UT = ArgType->getAsUnionType(); 4985 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4986 return Incompatible; 4987 4988 // The field to initialize within the transparent union. 4989 RecordDecl *UD = UT->getDecl(); 4990 FieldDecl *InitField = 0; 4991 // It's compatible if the expression matches any of the fields. 4992 for (RecordDecl::field_iterator it = UD->field_begin(), 4993 itend = UD->field_end(); 4994 it != itend; ++it) { 4995 if (it->getType()->isPointerType()) { 4996 // If the transparent union contains a pointer type, we allow: 4997 // 1) void pointer 4998 // 2) null pointer constant 4999 if (FromType->isPointerType()) 5000 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 5001 ImpCastExprToType(rExpr, it->getType(), CK_BitCast); 5002 InitField = *it; 5003 break; 5004 } 5005 5006 if (rExpr->isNullPointerConstant(Context, 5007 Expr::NPC_ValueDependentIsNull)) { 5008 ImpCastExprToType(rExpr, it->getType(), CK_IntegralToPointer); 5009 InitField = *it; 5010 break; 5011 } 5012 } 5013 5014 if (CheckAssignmentConstraints(it->getType(), rExpr->getType()) 5015 == Compatible) { 5016 ImpCastExprToType(rExpr, it->getType(), CK_Unknown); 5017 InitField = *it; 5018 break; 5019 } 5020 } 5021 5022 if (!InitField) 5023 return Incompatible; 5024 5025 ConstructTransparentUnion(Context, rExpr, ArgType, InitField); 5026 return Compatible; 5027} 5028 5029Sema::AssignConvertType 5030Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) { 5031 if (getLangOptions().CPlusPlus) { 5032 if (!lhsType->isRecordType()) { 5033 // C++ 5.17p3: If the left operand is not of class type, the 5034 // expression is implicitly converted (C++ 4) to the 5035 // cv-unqualified type of the left operand. 5036 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(), 5037 AA_Assigning)) 5038 return Incompatible; 5039 return Compatible; 5040 } 5041 5042 // FIXME: Currently, we fall through and treat C++ classes like C 5043 // structures. 5044 } 5045 5046 // C99 6.5.16.1p1: the left operand is a pointer and the right is 5047 // a null pointer constant. 5048 if ((lhsType->isPointerType() || 5049 lhsType->isObjCObjectPointerType() || 5050 lhsType->isBlockPointerType()) 5051 && rExpr->isNullPointerConstant(Context, 5052 Expr::NPC_ValueDependentIsNull)) { 5053 ImpCastExprToType(rExpr, lhsType, CK_Unknown); 5054 return Compatible; 5055 } 5056 5057 // This check seems unnatural, however it is necessary to ensure the proper 5058 // conversion of functions/arrays. If the conversion were done for all 5059 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 5060 // expressions that suppress this implicit conversion (&, sizeof). 5061 // 5062 // Suppress this for references: C++ 8.5.3p5. 5063 if (!lhsType->isReferenceType()) 5064 DefaultFunctionArrayLvalueConversion(rExpr); 5065 5066 Sema::AssignConvertType result = 5067 CheckAssignmentConstraints(lhsType, rExpr->getType()); 5068 5069 // C99 6.5.16.1p2: The value of the right operand is converted to the 5070 // type of the assignment expression. 5071 // CheckAssignmentConstraints allows the left-hand side to be a reference, 5072 // so that we can use references in built-in functions even in C. 5073 // The getNonReferenceType() call makes sure that the resulting expression 5074 // does not have reference type. 5075 if (result != Incompatible && rExpr->getType() != lhsType) 5076 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), 5077 CK_Unknown); 5078 return result; 5079} 5080 5081QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) { 5082 Diag(Loc, diag::err_typecheck_invalid_operands) 5083 << lex->getType() << rex->getType() 5084 << lex->getSourceRange() << rex->getSourceRange(); 5085 return QualType(); 5086} 5087 5088QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) { 5089 // For conversion purposes, we ignore any qualifiers. 5090 // For example, "const float" and "float" are equivalent. 5091 QualType lhsType = 5092 Context.getCanonicalType(lex->getType()).getUnqualifiedType(); 5093 QualType rhsType = 5094 Context.getCanonicalType(rex->getType()).getUnqualifiedType(); 5095 5096 // If the vector types are identical, return. 5097 if (lhsType == rhsType) 5098 return lhsType; 5099 5100 // Handle the case of a vector & extvector type of the same size and element 5101 // type. It would be nice if we only had one vector type someday. 5102 if (getLangOptions().LaxVectorConversions) { 5103 if (const VectorType *LV = lhsType->getAs<VectorType>()) { 5104 if (const VectorType *RV = rhsType->getAs<VectorType>()) { 5105 if (LV->getElementType() == RV->getElementType() && 5106 LV->getNumElements() == RV->getNumElements()) { 5107 if (lhsType->isExtVectorType()) { 5108 ImpCastExprToType(rex, lhsType, CK_BitCast); 5109 return lhsType; 5110 } 5111 5112 ImpCastExprToType(lex, rhsType, CK_BitCast); 5113 return rhsType; 5114 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){ 5115 // If we are allowing lax vector conversions, and LHS and RHS are both 5116 // vectors, the total size only needs to be the same. This is a 5117 // bitcast; no bits are changed but the result type is different. 5118 ImpCastExprToType(rex, lhsType, CK_BitCast); 5119 return lhsType; 5120 } 5121 } 5122 } 5123 } 5124 5125 // Handle the case of equivalent AltiVec and GCC vector types 5126 if (lhsType->isVectorType() && rhsType->isVectorType() && 5127 Context.areCompatibleVectorTypes(lhsType, rhsType)) { 5128 ImpCastExprToType(lex, rhsType, CK_BitCast); 5129 return rhsType; 5130 } 5131 5132 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can 5133 // swap back (so that we don't reverse the inputs to a subtract, for instance. 5134 bool swapped = false; 5135 if (rhsType->isExtVectorType()) { 5136 swapped = true; 5137 std::swap(rex, lex); 5138 std::swap(rhsType, lhsType); 5139 } 5140 5141 // Handle the case of an ext vector and scalar. 5142 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) { 5143 QualType EltTy = LV->getElementType(); 5144 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) { 5145 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) { 5146 ImpCastExprToType(rex, lhsType, CK_IntegralCast); 5147 if (swapped) std::swap(rex, lex); 5148 return lhsType; 5149 } 5150 } 5151 if (EltTy->isRealFloatingType() && rhsType->isScalarType() && 5152 rhsType->isRealFloatingType()) { 5153 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) { 5154 ImpCastExprToType(rex, lhsType, CK_FloatingCast); 5155 if (swapped) std::swap(rex, lex); 5156 return lhsType; 5157 } 5158 } 5159 } 5160 5161 // Vectors of different size or scalar and non-ext-vector are errors. 5162 Diag(Loc, diag::err_typecheck_vector_not_convertable) 5163 << lex->getType() << rex->getType() 5164 << lex->getSourceRange() << rex->getSourceRange(); 5165 return QualType(); 5166} 5167 5168QualType Sema::CheckMultiplyDivideOperands( 5169 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) { 5170 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 5171 return CheckVectorOperands(Loc, lex, rex); 5172 5173 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 5174 5175 if (!lex->getType()->isArithmeticType() || 5176 !rex->getType()->isArithmeticType()) 5177 return InvalidOperands(Loc, lex, rex); 5178 5179 // Check for division by zero. 5180 if (isDiv && 5181 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull)) 5182 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero) 5183 << rex->getSourceRange()); 5184 5185 return compType; 5186} 5187 5188QualType Sema::CheckRemainderOperands( 5189 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) { 5190 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { 5191 if (lex->getType()->hasIntegerRepresentation() && 5192 rex->getType()->hasIntegerRepresentation()) 5193 return CheckVectorOperands(Loc, lex, rex); 5194 return InvalidOperands(Loc, lex, rex); 5195 } 5196 5197 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 5198 5199 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType()) 5200 return InvalidOperands(Loc, lex, rex); 5201 5202 // Check for remainder by zero. 5203 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull)) 5204 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero) 5205 << rex->getSourceRange()); 5206 5207 return compType; 5208} 5209 5210QualType Sema::CheckAdditionOperands( // C99 6.5.6 5211 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) { 5212 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { 5213 QualType compType = CheckVectorOperands(Loc, lex, rex); 5214 if (CompLHSTy) *CompLHSTy = compType; 5215 return compType; 5216 } 5217 5218 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy); 5219 5220 // handle the common case first (both operands are arithmetic). 5221 if (lex->getType()->isArithmeticType() && 5222 rex->getType()->isArithmeticType()) { 5223 if (CompLHSTy) *CompLHSTy = compType; 5224 return compType; 5225 } 5226 5227 // Put any potential pointer into PExp 5228 Expr* PExp = lex, *IExp = rex; 5229 if (IExp->getType()->isAnyPointerType()) 5230 std::swap(PExp, IExp); 5231 5232 if (PExp->getType()->isAnyPointerType()) { 5233 5234 if (IExp->getType()->isIntegerType()) { 5235 QualType PointeeTy = PExp->getType()->getPointeeType(); 5236 5237 // Check for arithmetic on pointers to incomplete types. 5238 if (PointeeTy->isVoidType()) { 5239 if (getLangOptions().CPlusPlus) { 5240 Diag(Loc, diag::err_typecheck_pointer_arith_void_type) 5241 << lex->getSourceRange() << rex->getSourceRange(); 5242 return QualType(); 5243 } 5244 5245 // GNU extension: arithmetic on pointer to void 5246 Diag(Loc, diag::ext_gnu_void_ptr) 5247 << lex->getSourceRange() << rex->getSourceRange(); 5248 } else if (PointeeTy->isFunctionType()) { 5249 if (getLangOptions().CPlusPlus) { 5250 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 5251 << lex->getType() << lex->getSourceRange(); 5252 return QualType(); 5253 } 5254 5255 // GNU extension: arithmetic on pointer to function 5256 Diag(Loc, diag::ext_gnu_ptr_func_arith) 5257 << lex->getType() << lex->getSourceRange(); 5258 } else { 5259 // Check if we require a complete type. 5260 if (((PExp->getType()->isPointerType() && 5261 !PExp->getType()->isDependentType()) || 5262 PExp->getType()->isObjCObjectPointerType()) && 5263 RequireCompleteType(Loc, PointeeTy, 5264 PDiag(diag::err_typecheck_arithmetic_incomplete_type) 5265 << PExp->getSourceRange() 5266 << PExp->getType())) 5267 return QualType(); 5268 } 5269 // Diagnose bad cases where we step over interface counts. 5270 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) { 5271 Diag(Loc, diag::err_arithmetic_nonfragile_interface) 5272 << PointeeTy << PExp->getSourceRange(); 5273 return QualType(); 5274 } 5275 5276 if (CompLHSTy) { 5277 QualType LHSTy = Context.isPromotableBitField(lex); 5278 if (LHSTy.isNull()) { 5279 LHSTy = lex->getType(); 5280 if (LHSTy->isPromotableIntegerType()) 5281 LHSTy = Context.getPromotedIntegerType(LHSTy); 5282 } 5283 *CompLHSTy = LHSTy; 5284 } 5285 return PExp->getType(); 5286 } 5287 } 5288 5289 return InvalidOperands(Loc, lex, rex); 5290} 5291 5292// C99 6.5.6 5293QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex, 5294 SourceLocation Loc, QualType* CompLHSTy) { 5295 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { 5296 QualType compType = CheckVectorOperands(Loc, lex, rex); 5297 if (CompLHSTy) *CompLHSTy = compType; 5298 return compType; 5299 } 5300 5301 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy); 5302 5303 // Enforce type constraints: C99 6.5.6p3. 5304 5305 // Handle the common case first (both operands are arithmetic). 5306 if (lex->getType()->isArithmeticType() 5307 && rex->getType()->isArithmeticType()) { 5308 if (CompLHSTy) *CompLHSTy = compType; 5309 return compType; 5310 } 5311 5312 // Either ptr - int or ptr - ptr. 5313 if (lex->getType()->isAnyPointerType()) { 5314 QualType lpointee = lex->getType()->getPointeeType(); 5315 5316 // The LHS must be an completely-defined object type. 5317 5318 bool ComplainAboutVoid = false; 5319 Expr *ComplainAboutFunc = 0; 5320 if (lpointee->isVoidType()) { 5321 if (getLangOptions().CPlusPlus) { 5322 Diag(Loc, diag::err_typecheck_pointer_arith_void_type) 5323 << lex->getSourceRange() << rex->getSourceRange(); 5324 return QualType(); 5325 } 5326 5327 // GNU C extension: arithmetic on pointer to void 5328 ComplainAboutVoid = true; 5329 } else if (lpointee->isFunctionType()) { 5330 if (getLangOptions().CPlusPlus) { 5331 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 5332 << lex->getType() << lex->getSourceRange(); 5333 return QualType(); 5334 } 5335 5336 // GNU C extension: arithmetic on pointer to function 5337 ComplainAboutFunc = lex; 5338 } else if (!lpointee->isDependentType() && 5339 RequireCompleteType(Loc, lpointee, 5340 PDiag(diag::err_typecheck_sub_ptr_object) 5341 << lex->getSourceRange() 5342 << lex->getType())) 5343 return QualType(); 5344 5345 // Diagnose bad cases where we step over interface counts. 5346 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) { 5347 Diag(Loc, diag::err_arithmetic_nonfragile_interface) 5348 << lpointee << lex->getSourceRange(); 5349 return QualType(); 5350 } 5351 5352 // The result type of a pointer-int computation is the pointer type. 5353 if (rex->getType()->isIntegerType()) { 5354 if (ComplainAboutVoid) 5355 Diag(Loc, diag::ext_gnu_void_ptr) 5356 << lex->getSourceRange() << rex->getSourceRange(); 5357 if (ComplainAboutFunc) 5358 Diag(Loc, diag::ext_gnu_ptr_func_arith) 5359 << ComplainAboutFunc->getType() 5360 << ComplainAboutFunc->getSourceRange(); 5361 5362 if (CompLHSTy) *CompLHSTy = lex->getType(); 5363 return lex->getType(); 5364 } 5365 5366 // Handle pointer-pointer subtractions. 5367 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) { 5368 QualType rpointee = RHSPTy->getPointeeType(); 5369 5370 // RHS must be a completely-type object type. 5371 // Handle the GNU void* extension. 5372 if (rpointee->isVoidType()) { 5373 if (getLangOptions().CPlusPlus) { 5374 Diag(Loc, diag::err_typecheck_pointer_arith_void_type) 5375 << lex->getSourceRange() << rex->getSourceRange(); 5376 return QualType(); 5377 } 5378 5379 ComplainAboutVoid = true; 5380 } else if (rpointee->isFunctionType()) { 5381 if (getLangOptions().CPlusPlus) { 5382 Diag(Loc, diag::err_typecheck_pointer_arith_function_type) 5383 << rex->getType() << rex->getSourceRange(); 5384 return QualType(); 5385 } 5386 5387 // GNU extension: arithmetic on pointer to function 5388 if (!ComplainAboutFunc) 5389 ComplainAboutFunc = rex; 5390 } else if (!rpointee->isDependentType() && 5391 RequireCompleteType(Loc, rpointee, 5392 PDiag(diag::err_typecheck_sub_ptr_object) 5393 << rex->getSourceRange() 5394 << rex->getType())) 5395 return QualType(); 5396 5397 if (getLangOptions().CPlusPlus) { 5398 // Pointee types must be the same: C++ [expr.add] 5399 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 5400 Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 5401 << lex->getType() << rex->getType() 5402 << lex->getSourceRange() << rex->getSourceRange(); 5403 return QualType(); 5404 } 5405 } else { 5406 // Pointee types must be compatible C99 6.5.6p3 5407 if (!Context.typesAreCompatible( 5408 Context.getCanonicalType(lpointee).getUnqualifiedType(), 5409 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 5410 Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 5411 << lex->getType() << rex->getType() 5412 << lex->getSourceRange() << rex->getSourceRange(); 5413 return QualType(); 5414 } 5415 } 5416 5417 if (ComplainAboutVoid) 5418 Diag(Loc, diag::ext_gnu_void_ptr) 5419 << lex->getSourceRange() << rex->getSourceRange(); 5420 if (ComplainAboutFunc) 5421 Diag(Loc, diag::ext_gnu_ptr_func_arith) 5422 << ComplainAboutFunc->getType() 5423 << ComplainAboutFunc->getSourceRange(); 5424 5425 if (CompLHSTy) *CompLHSTy = lex->getType(); 5426 return Context.getPointerDiffType(); 5427 } 5428 } 5429 5430 return InvalidOperands(Loc, lex, rex); 5431} 5432 5433static bool isScopedEnumerationType(QualType T) { 5434 if (const EnumType *ET = dyn_cast<EnumType>(T)) 5435 return ET->getDecl()->isScoped(); 5436 return false; 5437} 5438 5439// C99 6.5.7 5440QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, 5441 bool isCompAssign) { 5442 // C99 6.5.7p2: Each of the operands shall have integer type. 5443 if (!lex->getType()->hasIntegerRepresentation() || 5444 !rex->getType()->hasIntegerRepresentation()) 5445 return InvalidOperands(Loc, lex, rex); 5446 5447 // C++0x: Don't allow scoped enums. FIXME: Use something better than 5448 // hasIntegerRepresentation() above instead of this. 5449 if (isScopedEnumerationType(lex->getType()) || 5450 isScopedEnumerationType(rex->getType())) { 5451 return InvalidOperands(Loc, lex, rex); 5452 } 5453 5454 // Vector shifts promote their scalar inputs to vector type. 5455 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 5456 return CheckVectorOperands(Loc, lex, rex); 5457 5458 // Shifts don't perform usual arithmetic conversions, they just do integer 5459 // promotions on each operand. C99 6.5.7p3 5460 QualType LHSTy = Context.isPromotableBitField(lex); 5461 if (LHSTy.isNull()) { 5462 LHSTy = lex->getType(); 5463 if (LHSTy->isPromotableIntegerType()) 5464 LHSTy = Context.getPromotedIntegerType(LHSTy); 5465 } 5466 if (!isCompAssign) 5467 ImpCastExprToType(lex, LHSTy, CK_IntegralCast); 5468 5469 UsualUnaryConversions(rex); 5470 5471 // Sanity-check shift operands 5472 llvm::APSInt Right; 5473 // Check right/shifter operand 5474 if (!rex->isValueDependent() && 5475 rex->isIntegerConstantExpr(Right, Context)) { 5476 if (Right.isNegative()) 5477 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange(); 5478 else { 5479 llvm::APInt LeftBits(Right.getBitWidth(), 5480 Context.getTypeSize(lex->getType())); 5481 if (Right.uge(LeftBits)) 5482 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange(); 5483 } 5484 } 5485 5486 // "The type of the result is that of the promoted left operand." 5487 return LHSTy; 5488} 5489 5490static bool IsWithinTemplateSpecialization(Decl *D) { 5491 if (DeclContext *DC = D->getDeclContext()) { 5492 if (isa<ClassTemplateSpecializationDecl>(DC)) 5493 return true; 5494 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 5495 return FD->isFunctionTemplateSpecialization(); 5496 } 5497 return false; 5498} 5499 5500// C99 6.5.8, C++ [expr.rel] 5501QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, 5502 unsigned OpaqueOpc, bool isRelational) { 5503 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 5504 5505 // Handle vector comparisons separately. 5506 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 5507 return CheckVectorCompareOperands(lex, rex, Loc, isRelational); 5508 5509 QualType lType = lex->getType(); 5510 QualType rType = rex->getType(); 5511 5512 if (!lType->hasFloatingRepresentation() && 5513 !(lType->isBlockPointerType() && isRelational) && 5514 !lex->getLocStart().isMacroID() && 5515 !rex->getLocStart().isMacroID()) { 5516 // For non-floating point types, check for self-comparisons of the form 5517 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 5518 // often indicate logic errors in the program. 5519 // 5520 // NOTE: Don't warn about comparison expressions resulting from macro 5521 // expansion. Also don't warn about comparisons which are only self 5522 // comparisons within a template specialization. The warnings should catch 5523 // obvious cases in the definition of the template anyways. The idea is to 5524 // warn when the typed comparison operator will always evaluate to the same 5525 // result. 5526 Expr *LHSStripped = lex->IgnoreParens(); 5527 Expr *RHSStripped = rex->IgnoreParens(); 5528 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) { 5529 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) { 5530 if (DRL->getDecl() == DRR->getDecl() && 5531 !IsWithinTemplateSpecialization(DRL->getDecl())) { 5532 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always) 5533 << 0 // self- 5534 << (Opc == BO_EQ 5535 || Opc == BO_LE 5536 || Opc == BO_GE)); 5537 } else if (lType->isArrayType() && rType->isArrayType() && 5538 !DRL->getDecl()->getType()->isReferenceType() && 5539 !DRR->getDecl()->getType()->isReferenceType()) { 5540 // what is it always going to eval to? 5541 char always_evals_to; 5542 switch(Opc) { 5543 case BO_EQ: // e.g. array1 == array2 5544 always_evals_to = 0; // false 5545 break; 5546 case BO_NE: // e.g. array1 != array2 5547 always_evals_to = 1; // true 5548 break; 5549 default: 5550 // best we can say is 'a constant' 5551 always_evals_to = 2; // e.g. array1 <= array2 5552 break; 5553 } 5554 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always) 5555 << 1 // array 5556 << always_evals_to); 5557 } 5558 } 5559 } 5560 5561 if (isa<CastExpr>(LHSStripped)) 5562 LHSStripped = LHSStripped->IgnoreParenCasts(); 5563 if (isa<CastExpr>(RHSStripped)) 5564 RHSStripped = RHSStripped->IgnoreParenCasts(); 5565 5566 // Warn about comparisons against a string constant (unless the other 5567 // operand is null), the user probably wants strcmp. 5568 Expr *literalString = 0; 5569 Expr *literalStringStripped = 0; 5570 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 5571 !RHSStripped->isNullPointerConstant(Context, 5572 Expr::NPC_ValueDependentIsNull)) { 5573 literalString = lex; 5574 literalStringStripped = LHSStripped; 5575 } else if ((isa<StringLiteral>(RHSStripped) || 5576 isa<ObjCEncodeExpr>(RHSStripped)) && 5577 !LHSStripped->isNullPointerConstant(Context, 5578 Expr::NPC_ValueDependentIsNull)) { 5579 literalString = rex; 5580 literalStringStripped = RHSStripped; 5581 } 5582 5583 if (literalString) { 5584 std::string resultComparison; 5585 switch (Opc) { 5586 case BO_LT: resultComparison = ") < 0"; break; 5587 case BO_GT: resultComparison = ") > 0"; break; 5588 case BO_LE: resultComparison = ") <= 0"; break; 5589 case BO_GE: resultComparison = ") >= 0"; break; 5590 case BO_EQ: resultComparison = ") == 0"; break; 5591 case BO_NE: resultComparison = ") != 0"; break; 5592 default: assert(false && "Invalid comparison operator"); 5593 } 5594 5595 DiagRuntimeBehavior(Loc, 5596 PDiag(diag::warn_stringcompare) 5597 << isa<ObjCEncodeExpr>(literalStringStripped) 5598 << literalString->getSourceRange()); 5599 } 5600 } 5601 5602 // C99 6.5.8p3 / C99 6.5.9p4 5603 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 5604 UsualArithmeticConversions(lex, rex); 5605 else { 5606 UsualUnaryConversions(lex); 5607 UsualUnaryConversions(rex); 5608 } 5609 5610 lType = lex->getType(); 5611 rType = rex->getType(); 5612 5613 // The result of comparisons is 'bool' in C++, 'int' in C. 5614 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy; 5615 5616 if (isRelational) { 5617 if (lType->isRealType() && rType->isRealType()) 5618 return ResultTy; 5619 } else { 5620 // Check for comparisons of floating point operands using != and ==. 5621 if (lType->hasFloatingRepresentation()) 5622 CheckFloatComparison(Loc,lex,rex); 5623 5624 if (lType->isArithmeticType() && rType->isArithmeticType()) 5625 return ResultTy; 5626 } 5627 5628 bool LHSIsNull = lex->isNullPointerConstant(Context, 5629 Expr::NPC_ValueDependentIsNull); 5630 bool RHSIsNull = rex->isNullPointerConstant(Context, 5631 Expr::NPC_ValueDependentIsNull); 5632 5633 // All of the following pointer-related warnings are GCC extensions, except 5634 // when handling null pointer constants. 5635 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2 5636 QualType LCanPointeeTy = 5637 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType()); 5638 QualType RCanPointeeTy = 5639 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType()); 5640 5641 if (getLangOptions().CPlusPlus) { 5642 if (LCanPointeeTy == RCanPointeeTy) 5643 return ResultTy; 5644 if (!isRelational && 5645 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 5646 // Valid unless comparison between non-null pointer and function pointer 5647 // This is a gcc extension compatibility comparison. 5648 // In a SFINAE context, we treat this as a hard error to maintain 5649 // conformance with the C++ standard. 5650 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 5651 && !LHSIsNull && !RHSIsNull) { 5652 Diag(Loc, 5653 isSFINAEContext()? 5654 diag::err_typecheck_comparison_of_fptr_to_void 5655 : diag::ext_typecheck_comparison_of_fptr_to_void) 5656 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5657 5658 if (isSFINAEContext()) 5659 return QualType(); 5660 5661 ImpCastExprToType(rex, lType, CK_BitCast); 5662 return ResultTy; 5663 } 5664 } 5665 // C++ [expr.rel]p2: 5666 // [...] Pointer conversions (4.10) and qualification 5667 // conversions (4.4) are performed on pointer operands (or on 5668 // a pointer operand and a null pointer constant) to bring 5669 // them to their composite pointer type. [...] 5670 // 5671 // C++ [expr.eq]p1 uses the same notion for (in)equality 5672 // comparisons of pointers. 5673 bool NonStandardCompositeType = false; 5674 QualType T = FindCompositePointerType(Loc, lex, rex, 5675 isSFINAEContext()? 0 : &NonStandardCompositeType); 5676 if (T.isNull()) { 5677 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers) 5678 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5679 return QualType(); 5680 } else if (NonStandardCompositeType) { 5681 Diag(Loc, 5682 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 5683 << lType << rType << T 5684 << lex->getSourceRange() << rex->getSourceRange(); 5685 } 5686 5687 ImpCastExprToType(lex, T, CK_BitCast); 5688 ImpCastExprToType(rex, T, CK_BitCast); 5689 return ResultTy; 5690 } 5691 // C99 6.5.9p2 and C99 6.5.8p2 5692 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 5693 RCanPointeeTy.getUnqualifiedType())) { 5694 // Valid unless a relational comparison of function pointers 5695 if (isRelational && LCanPointeeTy->isFunctionType()) { 5696 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 5697 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5698 } 5699 } else if (!isRelational && 5700 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 5701 // Valid unless comparison between non-null pointer and function pointer 5702 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 5703 && !LHSIsNull && !RHSIsNull) { 5704 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void) 5705 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5706 } 5707 } else { 5708 // Invalid 5709 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 5710 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5711 } 5712 if (LCanPointeeTy != RCanPointeeTy) 5713 ImpCastExprToType(rex, lType, CK_BitCast); 5714 return ResultTy; 5715 } 5716 5717 if (getLangOptions().CPlusPlus) { 5718 // Comparison of pointers with null pointer constants and equality 5719 // comparisons of member pointers to null pointer constants. 5720 if (RHSIsNull && 5721 (lType->isPointerType() || 5722 (!isRelational && lType->isMemberPointerType()))) { 5723 ImpCastExprToType(rex, lType, 5724 lType->isMemberPointerType() 5725 ? CK_NullToMemberPointer 5726 : CK_IntegralToPointer); 5727 return ResultTy; 5728 } 5729 if (LHSIsNull && 5730 (rType->isPointerType() || 5731 (!isRelational && rType->isMemberPointerType()))) { 5732 ImpCastExprToType(lex, rType, 5733 rType->isMemberPointerType() 5734 ? CK_NullToMemberPointer 5735 : CK_IntegralToPointer); 5736 return ResultTy; 5737 } 5738 5739 // Comparison of member pointers. 5740 if (!isRelational && 5741 lType->isMemberPointerType() && rType->isMemberPointerType()) { 5742 // C++ [expr.eq]p2: 5743 // In addition, pointers to members can be compared, or a pointer to 5744 // member and a null pointer constant. Pointer to member conversions 5745 // (4.11) and qualification conversions (4.4) are performed to bring 5746 // them to a common type. If one operand is a null pointer constant, 5747 // the common type is the type of the other operand. Otherwise, the 5748 // common type is a pointer to member type similar (4.4) to the type 5749 // of one of the operands, with a cv-qualification signature (4.4) 5750 // that is the union of the cv-qualification signatures of the operand 5751 // types. 5752 bool NonStandardCompositeType = false; 5753 QualType T = FindCompositePointerType(Loc, lex, rex, 5754 isSFINAEContext()? 0 : &NonStandardCompositeType); 5755 if (T.isNull()) { 5756 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers) 5757 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5758 return QualType(); 5759 } else if (NonStandardCompositeType) { 5760 Diag(Loc, 5761 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 5762 << lType << rType << T 5763 << lex->getSourceRange() << rex->getSourceRange(); 5764 } 5765 5766 ImpCastExprToType(lex, T, CK_BitCast); 5767 ImpCastExprToType(rex, T, CK_BitCast); 5768 return ResultTy; 5769 } 5770 5771 // Comparison of nullptr_t with itself. 5772 if (lType->isNullPtrType() && rType->isNullPtrType()) 5773 return ResultTy; 5774 } 5775 5776 // Handle block pointer types. 5777 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) { 5778 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType(); 5779 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType(); 5780 5781 if (!LHSIsNull && !RHSIsNull && 5782 !Context.typesAreCompatible(lpointee, rpointee)) { 5783 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 5784 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5785 } 5786 ImpCastExprToType(rex, lType, CK_BitCast); 5787 return ResultTy; 5788 } 5789 // Allow block pointers to be compared with null pointer constants. 5790 if (!isRelational 5791 && ((lType->isBlockPointerType() && rType->isPointerType()) 5792 || (lType->isPointerType() && rType->isBlockPointerType()))) { 5793 if (!LHSIsNull && !RHSIsNull) { 5794 if (!((rType->isPointerType() && rType->getAs<PointerType>() 5795 ->getPointeeType()->isVoidType()) 5796 || (lType->isPointerType() && lType->getAs<PointerType>() 5797 ->getPointeeType()->isVoidType()))) 5798 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 5799 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5800 } 5801 ImpCastExprToType(rex, lType, CK_BitCast); 5802 return ResultTy; 5803 } 5804 5805 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) { 5806 if (lType->isPointerType() || rType->isPointerType()) { 5807 const PointerType *LPT = lType->getAs<PointerType>(); 5808 const PointerType *RPT = rType->getAs<PointerType>(); 5809 bool LPtrToVoid = LPT ? 5810 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false; 5811 bool RPtrToVoid = RPT ? 5812 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false; 5813 5814 if (!LPtrToVoid && !RPtrToVoid && 5815 !Context.typesAreCompatible(lType, rType)) { 5816 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 5817 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5818 } 5819 ImpCastExprToType(rex, lType, CK_BitCast); 5820 return ResultTy; 5821 } 5822 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) { 5823 if (!Context.areComparableObjCPointerTypes(lType, rType)) 5824 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 5825 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5826 ImpCastExprToType(rex, lType, CK_BitCast); 5827 return ResultTy; 5828 } 5829 } 5830 if ((lType->isAnyPointerType() && rType->isIntegerType()) || 5831 (lType->isIntegerType() && rType->isAnyPointerType())) { 5832 unsigned DiagID = 0; 5833 bool isError = false; 5834 if ((LHSIsNull && lType->isIntegerType()) || 5835 (RHSIsNull && rType->isIntegerType())) { 5836 if (isRelational && !getLangOptions().CPlusPlus) 5837 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 5838 } else if (isRelational && !getLangOptions().CPlusPlus) 5839 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 5840 else if (getLangOptions().CPlusPlus) { 5841 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 5842 isError = true; 5843 } else 5844 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 5845 5846 if (DiagID) { 5847 Diag(Loc, DiagID) 5848 << lType << rType << lex->getSourceRange() << rex->getSourceRange(); 5849 if (isError) 5850 return QualType(); 5851 } 5852 5853 if (lType->isIntegerType()) 5854 ImpCastExprToType(lex, rType, CK_IntegralToPointer); 5855 else 5856 ImpCastExprToType(rex, lType, CK_IntegralToPointer); 5857 return ResultTy; 5858 } 5859 5860 // Handle block pointers. 5861 if (!isRelational && RHSIsNull 5862 && lType->isBlockPointerType() && rType->isIntegerType()) { 5863 ImpCastExprToType(rex, lType, CK_IntegralToPointer); 5864 return ResultTy; 5865 } 5866 if (!isRelational && LHSIsNull 5867 && lType->isIntegerType() && rType->isBlockPointerType()) { 5868 ImpCastExprToType(lex, rType, CK_IntegralToPointer); 5869 return ResultTy; 5870 } 5871 return InvalidOperands(Loc, lex, rex); 5872} 5873 5874/// CheckVectorCompareOperands - vector comparisons are a clang extension that 5875/// operates on extended vector types. Instead of producing an IntTy result, 5876/// like a scalar comparison, a vector comparison produces a vector of integer 5877/// types. 5878QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex, 5879 SourceLocation Loc, 5880 bool isRelational) { 5881 // Check to make sure we're operating on vectors of the same type and width, 5882 // Allowing one side to be a scalar of element type. 5883 QualType vType = CheckVectorOperands(Loc, lex, rex); 5884 if (vType.isNull()) 5885 return vType; 5886 5887 QualType lType = lex->getType(); 5888 QualType rType = rex->getType(); 5889 5890 // For non-floating point types, check for self-comparisons of the form 5891 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 5892 // often indicate logic errors in the program. 5893 if (!lType->hasFloatingRepresentation()) { 5894 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens())) 5895 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens())) 5896 if (DRL->getDecl() == DRR->getDecl()) 5897 DiagRuntimeBehavior(Loc, 5898 PDiag(diag::warn_comparison_always) 5899 << 0 // self- 5900 << 2 // "a constant" 5901 ); 5902 } 5903 5904 // Check for comparisons of floating point operands using != and ==. 5905 if (!isRelational && lType->hasFloatingRepresentation()) { 5906 assert (rType->hasFloatingRepresentation()); 5907 CheckFloatComparison(Loc,lex,rex); 5908 } 5909 5910 // Return the type for the comparison, which is the same as vector type for 5911 // integer vectors, or an integer type of identical size and number of 5912 // elements for floating point vectors. 5913 if (lType->hasIntegerRepresentation()) 5914 return lType; 5915 5916 const VectorType *VTy = lType->getAs<VectorType>(); 5917 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 5918 if (TypeSize == Context.getTypeSize(Context.IntTy)) 5919 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 5920 if (TypeSize == Context.getTypeSize(Context.LongTy)) 5921 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 5922 5923 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 5924 "Unhandled vector element size in vector compare"); 5925 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 5926} 5927 5928inline QualType Sema::CheckBitwiseOperands( 5929 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) { 5930 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) { 5931 if (lex->getType()->hasIntegerRepresentation() && 5932 rex->getType()->hasIntegerRepresentation()) 5933 return CheckVectorOperands(Loc, lex, rex); 5934 5935 return InvalidOperands(Loc, lex, rex); 5936 } 5937 5938 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 5939 5940 if (lex->getType()->isIntegralOrUnscopedEnumerationType() && 5941 rex->getType()->isIntegralOrUnscopedEnumerationType()) 5942 return compType; 5943 return InvalidOperands(Loc, lex, rex); 5944} 5945 5946inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 5947 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) { 5948 5949 // Diagnose cases where the user write a logical and/or but probably meant a 5950 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 5951 // is a constant. 5952 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() && 5953 rex->getType()->isIntegerType() && !rex->isValueDependent() && 5954 // Don't warn in macros. 5955 !Loc.isMacroID()) { 5956 // If the RHS can be constant folded, and if it constant folds to something 5957 // that isn't 0 or 1 (which indicate a potential logical operation that 5958 // happened to fold to true/false) then warn. 5959 Expr::EvalResult Result; 5960 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects && 5961 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) { 5962 Diag(Loc, diag::warn_logical_instead_of_bitwise) 5963 << rex->getSourceRange() 5964 << (Opc == BO_LAnd ? "&&" : "||") 5965 << (Opc == BO_LAnd ? "&" : "|"); 5966 } 5967 } 5968 5969 if (!Context.getLangOptions().CPlusPlus) { 5970 UsualUnaryConversions(lex); 5971 UsualUnaryConversions(rex); 5972 5973 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType()) 5974 return InvalidOperands(Loc, lex, rex); 5975 5976 return Context.IntTy; 5977 } 5978 5979 // The following is safe because we only use this method for 5980 // non-overloadable operands. 5981 5982 // C++ [expr.log.and]p1 5983 // C++ [expr.log.or]p1 5984 // The operands are both contextually converted to type bool. 5985 if (PerformContextuallyConvertToBool(lex) || 5986 PerformContextuallyConvertToBool(rex)) 5987 return InvalidOperands(Loc, lex, rex); 5988 5989 // C++ [expr.log.and]p2 5990 // C++ [expr.log.or]p2 5991 // The result is a bool. 5992 return Context.BoolTy; 5993} 5994 5995/// IsReadonlyProperty - Verify that otherwise a valid l-value expression 5996/// is a read-only property; return true if so. A readonly property expression 5997/// depends on various declarations and thus must be treated specially. 5998/// 5999static bool IsReadonlyProperty(Expr *E, Sema &S) { 6000 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) { 6001 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E); 6002 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) { 6003 QualType BaseType = PropExpr->getBase()->getType(); 6004 if (const ObjCObjectPointerType *OPT = 6005 BaseType->getAsObjCInterfacePointerType()) 6006 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl()) 6007 if (S.isPropertyReadonly(PDecl, IFace)) 6008 return true; 6009 } 6010 } 6011 return false; 6012} 6013 6014/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 6015/// emit an error and return true. If so, return false. 6016static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 6017 SourceLocation OrigLoc = Loc; 6018 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 6019 &Loc); 6020 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S)) 6021 IsLV = Expr::MLV_ReadonlyProperty; 6022 if (IsLV == Expr::MLV_Valid) 6023 return false; 6024 6025 unsigned Diag = 0; 6026 bool NeedType = false; 6027 switch (IsLV) { // C99 6.5.16p2 6028 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break; 6029 case Expr::MLV_ArrayType: 6030 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 6031 NeedType = true; 6032 break; 6033 case Expr::MLV_NotObjectType: 6034 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 6035 NeedType = true; 6036 break; 6037 case Expr::MLV_LValueCast: 6038 Diag = diag::err_typecheck_lvalue_casts_not_supported; 6039 break; 6040 case Expr::MLV_Valid: 6041 llvm_unreachable("did not take early return for MLV_Valid"); 6042 case Expr::MLV_InvalidExpression: 6043 case Expr::MLV_MemberFunction: 6044 case Expr::MLV_ClassTemporary: 6045 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 6046 break; 6047 case Expr::MLV_IncompleteType: 6048 case Expr::MLV_IncompleteVoidType: 6049 return S.RequireCompleteType(Loc, E->getType(), 6050 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue) 6051 << E->getSourceRange()); 6052 case Expr::MLV_DuplicateVectorComponents: 6053 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 6054 break; 6055 case Expr::MLV_NotBlockQualified: 6056 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 6057 break; 6058 case Expr::MLV_ReadonlyProperty: 6059 Diag = diag::error_readonly_property_assignment; 6060 break; 6061 case Expr::MLV_NoSetterProperty: 6062 Diag = diag::error_nosetter_property_assignment; 6063 break; 6064 case Expr::MLV_SubObjCPropertySetting: 6065 Diag = diag::error_no_subobject_property_setting; 6066 break; 6067 } 6068 6069 SourceRange Assign; 6070 if (Loc != OrigLoc) 6071 Assign = SourceRange(OrigLoc, OrigLoc); 6072 if (NeedType) 6073 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 6074 else 6075 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 6076 return true; 6077} 6078 6079 6080 6081// C99 6.5.16.1 6082QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS, 6083 SourceLocation Loc, 6084 QualType CompoundType) { 6085 // Verify that LHS is a modifiable lvalue, and emit error if not. 6086 if (CheckForModifiableLvalue(LHS, Loc, *this)) 6087 return QualType(); 6088 6089 QualType LHSType = LHS->getType(); 6090 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType; 6091 AssignConvertType ConvTy; 6092 if (CompoundType.isNull()) { 6093 QualType LHSTy(LHSType); 6094 // Simple assignment "x = y". 6095 ConvertPropertyAssignment(LHS, RHS, LHSTy); 6096 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 6097 // Special case of NSObject attributes on c-style pointer types. 6098 if (ConvTy == IncompatiblePointer && 6099 ((Context.isObjCNSObjectType(LHSType) && 6100 RHSType->isObjCObjectPointerType()) || 6101 (Context.isObjCNSObjectType(RHSType) && 6102 LHSType->isObjCObjectPointerType()))) 6103 ConvTy = Compatible; 6104 6105 // If the RHS is a unary plus or minus, check to see if they = and + are 6106 // right next to each other. If so, the user may have typo'd "x =+ 4" 6107 // instead of "x += 4". 6108 Expr *RHSCheck = RHS; 6109 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 6110 RHSCheck = ICE->getSubExpr(); 6111 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 6112 if ((UO->getOpcode() == UO_Plus || 6113 UO->getOpcode() == UO_Minus) && 6114 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 6115 // Only if the two operators are exactly adjacent. 6116 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() && 6117 // And there is a space or other character before the subexpr of the 6118 // unary +/-. We don't want to warn on "x=-1". 6119 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 6120 UO->getSubExpr()->getLocStart().isFileID()) { 6121 Diag(Loc, diag::warn_not_compound_assign) 6122 << (UO->getOpcode() == UO_Plus ? "+" : "-") 6123 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 6124 } 6125 } 6126 } else { 6127 // Compound assignment "x += y" 6128 ConvTy = CheckAssignmentConstraints(LHSType, RHSType); 6129 } 6130 6131 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 6132 RHS, AA_Assigning)) 6133 return QualType(); 6134 6135 6136 // Check to see if the destination operand is a dereferenced null pointer. If 6137 // so, and if not volatile-qualified, this is undefined behavior that the 6138 // optimizer will delete, so warn about it. People sometimes try to use this 6139 // to get a deterministic trap and are surprised by clang's behavior. This 6140 // only handles the pattern "*null = whatever", which is a very syntactic 6141 // check. 6142 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts())) 6143 if (UO->getOpcode() == UO_Deref && 6144 UO->getSubExpr()->IgnoreParenCasts()-> 6145 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) && 6146 !UO->getType().isVolatileQualified()) { 6147 Diag(UO->getOperatorLoc(), diag::warn_indirection_through_null) 6148 << UO->getSubExpr()->getSourceRange(); 6149 Diag(UO->getOperatorLoc(), diag::note_indirection_through_null); 6150 } 6151 6152 // C99 6.5.16p3: The type of an assignment expression is the type of the 6153 // left operand unless the left operand has qualified type, in which case 6154 // it is the unqualified version of the type of the left operand. 6155 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 6156 // is converted to the type of the assignment expression (above). 6157 // C++ 5.17p1: the type of the assignment expression is that of its left 6158 // operand. 6159 return (getLangOptions().CPlusPlus 6160 ? LHSType : LHSType.getUnqualifiedType()); 6161} 6162 6163// C99 6.5.17 6164QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) { 6165 DiagnoseUnusedExprResult(LHS); 6166 6167 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 6168 // operands, but not unary promotions. 6169 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 6170 if (!getLangOptions().CPlusPlus) { 6171 DefaultFunctionArrayLvalueConversion(LHS); 6172 if (!LHS->getType()->isVoidType()) 6173 RequireCompleteType(Loc, LHS->getType(), diag::err_incomplete_type); 6174 6175 DefaultFunctionArrayLvalueConversion(RHS); 6176 if (!RHS->getType()->isVoidType()) 6177 RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type); 6178 } 6179 6180 return RHS->getType(); 6181} 6182 6183/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 6184/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 6185QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc, 6186 bool isInc, bool isPrefix) { 6187 if (Op->isTypeDependent()) 6188 return Context.DependentTy; 6189 6190 QualType ResType = Op->getType(); 6191 assert(!ResType.isNull() && "no type for increment/decrement expression"); 6192 6193 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) { 6194 // Decrement of bool is not allowed. 6195 if (!isInc) { 6196 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 6197 return QualType(); 6198 } 6199 // Increment of bool sets it to true, but is deprecated. 6200 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 6201 } else if (ResType->isRealType()) { 6202 // OK! 6203 } else if (ResType->isAnyPointerType()) { 6204 QualType PointeeTy = ResType->getPointeeType(); 6205 6206 // C99 6.5.2.4p2, 6.5.6p2 6207 if (PointeeTy->isVoidType()) { 6208 if (getLangOptions().CPlusPlus) { 6209 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type) 6210 << Op->getSourceRange(); 6211 return QualType(); 6212 } 6213 6214 // Pointer to void is a GNU extension in C. 6215 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange(); 6216 } else if (PointeeTy->isFunctionType()) { 6217 if (getLangOptions().CPlusPlus) { 6218 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type) 6219 << Op->getType() << Op->getSourceRange(); 6220 return QualType(); 6221 } 6222 6223 Diag(OpLoc, diag::ext_gnu_ptr_func_arith) 6224 << ResType << Op->getSourceRange(); 6225 } else if (RequireCompleteType(OpLoc, PointeeTy, 6226 PDiag(diag::err_typecheck_arithmetic_incomplete_type) 6227 << Op->getSourceRange() 6228 << ResType)) 6229 return QualType(); 6230 // Diagnose bad cases where we step over interface counts. 6231 else if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) { 6232 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface) 6233 << PointeeTy << Op->getSourceRange(); 6234 return QualType(); 6235 } 6236 } else if (ResType->isAnyComplexType()) { 6237 // C99 does not support ++/-- on complex types, we allow as an extension. 6238 Diag(OpLoc, diag::ext_integer_increment_complex) 6239 << ResType << Op->getSourceRange(); 6240 } else if (ResType->isPlaceholderType()) { 6241 ExprResult PR = CheckPlaceholderExpr(Op, OpLoc); 6242 if (PR.isInvalid()) return QualType(); 6243 return CheckIncrementDecrementOperand(PR.take(), OpLoc, isInc, isPrefix); 6244 } else { 6245 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 6246 << ResType << int(isInc) << Op->getSourceRange(); 6247 return QualType(); 6248 } 6249 // At this point, we know we have a real, complex or pointer type. 6250 // Now make sure the operand is a modifiable lvalue. 6251 if (CheckForModifiableLvalue(Op, OpLoc, *this)) 6252 return QualType(); 6253 // In C++, a prefix increment is the same type as the operand. Otherwise 6254 // (in C or with postfix), the increment is the unqualified type of the 6255 // operand. 6256 return isPrefix && getLangOptions().CPlusPlus 6257 ? ResType : ResType.getUnqualifiedType(); 6258} 6259 6260void Sema::ConvertPropertyAssignment(Expr *LHS, Expr *&RHS, QualType& LHSTy) { 6261 bool copyInit = false; 6262 if (const ObjCImplicitSetterGetterRefExpr *OISGE = 6263 dyn_cast<ObjCImplicitSetterGetterRefExpr>(LHS)) { 6264 // If using property-dot syntax notation for assignment, and there is a 6265 // setter, RHS expression is being passed to the setter argument. So, 6266 // type conversion (and comparison) is RHS to setter's argument type. 6267 if (const ObjCMethodDecl *SetterMD = OISGE->getSetterMethod()) { 6268 ObjCMethodDecl::param_iterator P = SetterMD->param_begin(); 6269 LHSTy = (*P)->getType(); 6270 } 6271 copyInit = (getLangOptions().CPlusPlus && LHSTy->isRecordType()); 6272 } 6273 else 6274 copyInit = (getLangOptions().CPlusPlus && isa<ObjCPropertyRefExpr>(LHS) && 6275 LHSTy->isRecordType()); 6276 if (copyInit) { 6277 InitializedEntity Entity = 6278 InitializedEntity::InitializeParameter(Context, LHSTy); 6279 Expr *Arg = RHS; 6280 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), 6281 Owned(Arg)); 6282 if (!ArgE.isInvalid()) 6283 RHS = ArgE.takeAs<Expr>(); 6284 } 6285} 6286 6287 6288/// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 6289/// This routine allows us to typecheck complex/recursive expressions 6290/// where the declaration is needed for type checking. We only need to 6291/// handle cases when the expression references a function designator 6292/// or is an lvalue. Here are some examples: 6293/// - &(x) => x 6294/// - &*****f => f for f a function designator. 6295/// - &s.xx => s 6296/// - &s.zz[1].yy -> s, if zz is an array 6297/// - *(x + 1) -> x, if x is an array 6298/// - &"123"[2] -> 0 6299/// - & __real__ x -> x 6300static NamedDecl *getPrimaryDecl(Expr *E) { 6301 switch (E->getStmtClass()) { 6302 case Stmt::DeclRefExprClass: 6303 return cast<DeclRefExpr>(E)->getDecl(); 6304 case Stmt::MemberExprClass: 6305 // If this is an arrow operator, the address is an offset from 6306 // the base's value, so the object the base refers to is 6307 // irrelevant. 6308 if (cast<MemberExpr>(E)->isArrow()) 6309 return 0; 6310 // Otherwise, the expression refers to a part of the base 6311 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 6312 case Stmt::ArraySubscriptExprClass: { 6313 // FIXME: This code shouldn't be necessary! We should catch the implicit 6314 // promotion of register arrays earlier. 6315 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 6316 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 6317 if (ICE->getSubExpr()->getType()->isArrayType()) 6318 return getPrimaryDecl(ICE->getSubExpr()); 6319 } 6320 return 0; 6321 } 6322 case Stmt::UnaryOperatorClass: { 6323 UnaryOperator *UO = cast<UnaryOperator>(E); 6324 6325 switch(UO->getOpcode()) { 6326 case UO_Real: 6327 case UO_Imag: 6328 case UO_Extension: 6329 return getPrimaryDecl(UO->getSubExpr()); 6330 default: 6331 return 0; 6332 } 6333 } 6334 case Stmt::ParenExprClass: 6335 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 6336 case Stmt::ImplicitCastExprClass: 6337 // If the result of an implicit cast is an l-value, we care about 6338 // the sub-expression; otherwise, the result here doesn't matter. 6339 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 6340 default: 6341 return 0; 6342 } 6343} 6344 6345/// CheckAddressOfOperand - The operand of & must be either a function 6346/// designator or an lvalue designating an object. If it is an lvalue, the 6347/// object cannot be declared with storage class register or be a bit field. 6348/// Note: The usual conversions are *not* applied to the operand of the & 6349/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 6350/// In C++, the operand might be an overloaded function name, in which case 6351/// we allow the '&' but retain the overloaded-function type. 6352QualType Sema::CheckAddressOfOperand(Expr *OrigOp, SourceLocation OpLoc) { 6353 if (OrigOp->isTypeDependent()) 6354 return Context.DependentTy; 6355 if (OrigOp->getType() == Context.OverloadTy) 6356 return Context.OverloadTy; 6357 6358 ExprResult PR = CheckPlaceholderExpr(OrigOp, OpLoc); 6359 if (PR.isInvalid()) return QualType(); 6360 OrigOp = PR.take(); 6361 6362 // Make sure to ignore parentheses in subsequent checks 6363 Expr *op = OrigOp->IgnoreParens(); 6364 6365 if (getLangOptions().C99) { 6366 // Implement C99-only parts of addressof rules. 6367 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 6368 if (uOp->getOpcode() == UO_Deref) 6369 // Per C99 6.5.3.2, the address of a deref always returns a valid result 6370 // (assuming the deref expression is valid). 6371 return uOp->getSubExpr()->getType(); 6372 } 6373 // Technically, there should be a check for array subscript 6374 // expressions here, but the result of one is always an lvalue anyway. 6375 } 6376 NamedDecl *dcl = getPrimaryDecl(op); 6377 Expr::isLvalueResult lval = op->isLvalue(Context); 6378 6379 if (lval == Expr::LV_ClassTemporary) { 6380 Diag(OpLoc, isSFINAEContext()? diag::err_typecheck_addrof_class_temporary 6381 : diag::ext_typecheck_addrof_class_temporary) 6382 << op->getType() << op->getSourceRange(); 6383 if (isSFINAEContext()) 6384 return QualType(); 6385 } else if (isa<ObjCSelectorExpr>(op)) { 6386 return Context.getPointerType(op->getType()); 6387 } else if (lval == Expr::LV_MemberFunction) { 6388 // If it's an instance method, make a member pointer. 6389 // The expression must have exactly the form &A::foo. 6390 6391 // If the underlying expression isn't a decl ref, give up. 6392 if (!isa<DeclRefExpr>(op)) { 6393 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 6394 << OrigOp->getSourceRange(); 6395 return QualType(); 6396 } 6397 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 6398 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 6399 6400 // The id-expression was parenthesized. 6401 if (OrigOp != DRE) { 6402 Diag(OpLoc, diag::err_parens_pointer_member_function) 6403 << OrigOp->getSourceRange(); 6404 6405 // The method was named without a qualifier. 6406 } else if (!DRE->getQualifier()) { 6407 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 6408 << op->getSourceRange(); 6409 } 6410 6411 return Context.getMemberPointerType(op->getType(), 6412 Context.getTypeDeclType(MD->getParent()).getTypePtr()); 6413 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 6414 // C99 6.5.3.2p1 6415 // The operand must be either an l-value or a function designator 6416 if (!op->getType()->isFunctionType()) { 6417 // FIXME: emit more specific diag... 6418 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 6419 << op->getSourceRange(); 6420 return QualType(); 6421 } 6422 } else if (op->getBitField()) { // C99 6.5.3.2p1 6423 // The operand cannot be a bit-field 6424 Diag(OpLoc, diag::err_typecheck_address_of) 6425 << "bit-field" << op->getSourceRange(); 6426 return QualType(); 6427 } else if (op->refersToVectorElement()) { 6428 // The operand cannot be an element of a vector 6429 Diag(OpLoc, diag::err_typecheck_address_of) 6430 << "vector element" << op->getSourceRange(); 6431 return QualType(); 6432 } else if (isa<ObjCPropertyRefExpr>(op)) { 6433 // cannot take address of a property expression. 6434 Diag(OpLoc, diag::err_typecheck_address_of) 6435 << "property expression" << op->getSourceRange(); 6436 return QualType(); 6437 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) { 6438 // FIXME: Can LHS ever be null here? 6439 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull()) 6440 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc); 6441 } else if (dcl) { // C99 6.5.3.2p1 6442 // We have an lvalue with a decl. Make sure the decl is not declared 6443 // with the register storage-class specifier. 6444 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 6445 // in C++ it is not error to take address of a register 6446 // variable (c++03 7.1.1P3) 6447 if (vd->getStorageClass() == SC_Register && 6448 !getLangOptions().CPlusPlus) { 6449 Diag(OpLoc, diag::err_typecheck_address_of) 6450 << "register variable" << op->getSourceRange(); 6451 return QualType(); 6452 } 6453 } else if (isa<FunctionTemplateDecl>(dcl)) { 6454 return Context.OverloadTy; 6455 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) { 6456 // Okay: we can take the address of a field. 6457 // Could be a pointer to member, though, if there is an explicit 6458 // scope qualifier for the class. 6459 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 6460 DeclContext *Ctx = dcl->getDeclContext(); 6461 if (Ctx && Ctx->isRecord()) { 6462 if (FD->getType()->isReferenceType()) { 6463 Diag(OpLoc, 6464 diag::err_cannot_form_pointer_to_member_of_reference_type) 6465 << FD->getDeclName() << FD->getType(); 6466 return QualType(); 6467 } 6468 6469 return Context.getMemberPointerType(op->getType(), 6470 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 6471 } 6472 } 6473 } else if (!isa<FunctionDecl>(dcl)) 6474 assert(0 && "Unknown/unexpected decl type"); 6475 } 6476 6477 if (lval == Expr::LV_IncompleteVoidType) { 6478 // Taking the address of a void variable is technically illegal, but we 6479 // allow it in cases which are otherwise valid. 6480 // Example: "extern void x; void* y = &x;". 6481 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 6482 } 6483 6484 // If the operand has type "type", the result has type "pointer to type". 6485 if (op->getType()->isObjCObjectType()) 6486 return Context.getObjCObjectPointerType(op->getType()); 6487 return Context.getPointerType(op->getType()); 6488} 6489 6490/// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 6491QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) { 6492 if (Op->isTypeDependent()) 6493 return Context.DependentTy; 6494 6495 UsualUnaryConversions(Op); 6496 QualType OpTy = Op->getType(); 6497 QualType Result; 6498 6499 // Note that per both C89 and C99, indirection is always legal, even if OpTy 6500 // is an incomplete type or void. It would be possible to warn about 6501 // dereferencing a void pointer, but it's completely well-defined, and such a 6502 // warning is unlikely to catch any mistakes. 6503 if (const PointerType *PT = OpTy->getAs<PointerType>()) 6504 Result = PT->getPointeeType(); 6505 else if (const ObjCObjectPointerType *OPT = 6506 OpTy->getAs<ObjCObjectPointerType>()) 6507 Result = OPT->getPointeeType(); 6508 else { 6509 ExprResult PR = CheckPlaceholderExpr(Op, OpLoc); 6510 if (PR.isInvalid()) return QualType(); 6511 if (PR.take() != Op) return CheckIndirectionOperand(PR.take(), OpLoc); 6512 } 6513 6514 if (Result.isNull()) { 6515 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 6516 << OpTy << Op->getSourceRange(); 6517 return QualType(); 6518 } 6519 6520 return Result; 6521} 6522 6523static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode( 6524 tok::TokenKind Kind) { 6525 BinaryOperatorKind Opc; 6526 switch (Kind) { 6527 default: assert(0 && "Unknown binop!"); 6528 case tok::periodstar: Opc = BO_PtrMemD; break; 6529 case tok::arrowstar: Opc = BO_PtrMemI; break; 6530 case tok::star: Opc = BO_Mul; break; 6531 case tok::slash: Opc = BO_Div; break; 6532 case tok::percent: Opc = BO_Rem; break; 6533 case tok::plus: Opc = BO_Add; break; 6534 case tok::minus: Opc = BO_Sub; break; 6535 case tok::lessless: Opc = BO_Shl; break; 6536 case tok::greatergreater: Opc = BO_Shr; break; 6537 case tok::lessequal: Opc = BO_LE; break; 6538 case tok::less: Opc = BO_LT; break; 6539 case tok::greaterequal: Opc = BO_GE; break; 6540 case tok::greater: Opc = BO_GT; break; 6541 case tok::exclaimequal: Opc = BO_NE; break; 6542 case tok::equalequal: Opc = BO_EQ; break; 6543 case tok::amp: Opc = BO_And; break; 6544 case tok::caret: Opc = BO_Xor; break; 6545 case tok::pipe: Opc = BO_Or; break; 6546 case tok::ampamp: Opc = BO_LAnd; break; 6547 case tok::pipepipe: Opc = BO_LOr; break; 6548 case tok::equal: Opc = BO_Assign; break; 6549 case tok::starequal: Opc = BO_MulAssign; break; 6550 case tok::slashequal: Opc = BO_DivAssign; break; 6551 case tok::percentequal: Opc = BO_RemAssign; break; 6552 case tok::plusequal: Opc = BO_AddAssign; break; 6553 case tok::minusequal: Opc = BO_SubAssign; break; 6554 case tok::lesslessequal: Opc = BO_ShlAssign; break; 6555 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 6556 case tok::ampequal: Opc = BO_AndAssign; break; 6557 case tok::caretequal: Opc = BO_XorAssign; break; 6558 case tok::pipeequal: Opc = BO_OrAssign; break; 6559 case tok::comma: Opc = BO_Comma; break; 6560 } 6561 return Opc; 6562} 6563 6564static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 6565 tok::TokenKind Kind) { 6566 UnaryOperatorKind Opc; 6567 switch (Kind) { 6568 default: assert(0 && "Unknown unary op!"); 6569 case tok::plusplus: Opc = UO_PreInc; break; 6570 case tok::minusminus: Opc = UO_PreDec; break; 6571 case tok::amp: Opc = UO_AddrOf; break; 6572 case tok::star: Opc = UO_Deref; break; 6573 case tok::plus: Opc = UO_Plus; break; 6574 case tok::minus: Opc = UO_Minus; break; 6575 case tok::tilde: Opc = UO_Not; break; 6576 case tok::exclaim: Opc = UO_LNot; break; 6577 case tok::kw___real: Opc = UO_Real; break; 6578 case tok::kw___imag: Opc = UO_Imag; break; 6579 case tok::kw___extension__: Opc = UO_Extension; break; 6580 } 6581 return Opc; 6582} 6583 6584/// CreateBuiltinBinOp - Creates a new built-in binary operation with 6585/// operator @p Opc at location @c TokLoc. This routine only supports 6586/// built-in operations; ActOnBinOp handles overloaded operators. 6587ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 6588 unsigned Op, 6589 Expr *lhs, Expr *rhs) { 6590 QualType ResultTy; // Result type of the binary operator. 6591 BinaryOperatorKind Opc = (BinaryOperatorKind) Op; 6592 // The following two variables are used for compound assignment operators 6593 QualType CompLHSTy; // Type of LHS after promotions for computation 6594 QualType CompResultTy; // Type of computation result 6595 6596 switch (Opc) { 6597 case BO_Assign: 6598 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType()); 6599 break; 6600 case BO_PtrMemD: 6601 case BO_PtrMemI: 6602 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc, 6603 Opc == BO_PtrMemI); 6604 break; 6605 case BO_Mul: 6606 case BO_Div: 6607 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false, 6608 Opc == BO_Div); 6609 break; 6610 case BO_Rem: 6611 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc); 6612 break; 6613 case BO_Add: 6614 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc); 6615 break; 6616 case BO_Sub: 6617 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc); 6618 break; 6619 case BO_Shl: 6620 case BO_Shr: 6621 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc); 6622 break; 6623 case BO_LE: 6624 case BO_LT: 6625 case BO_GE: 6626 case BO_GT: 6627 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true); 6628 break; 6629 case BO_EQ: 6630 case BO_NE: 6631 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false); 6632 break; 6633 case BO_And: 6634 case BO_Xor: 6635 case BO_Or: 6636 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc); 6637 break; 6638 case BO_LAnd: 6639 case BO_LOr: 6640 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc); 6641 break; 6642 case BO_MulAssign: 6643 case BO_DivAssign: 6644 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true, 6645 Opc == BO_DivAssign); 6646 CompLHSTy = CompResultTy; 6647 if (!CompResultTy.isNull()) 6648 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 6649 break; 6650 case BO_RemAssign: 6651 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true); 6652 CompLHSTy = CompResultTy; 6653 if (!CompResultTy.isNull()) 6654 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 6655 break; 6656 case BO_AddAssign: 6657 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy); 6658 if (!CompResultTy.isNull()) 6659 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 6660 break; 6661 case BO_SubAssign: 6662 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy); 6663 if (!CompResultTy.isNull()) 6664 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 6665 break; 6666 case BO_ShlAssign: 6667 case BO_ShrAssign: 6668 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true); 6669 CompLHSTy = CompResultTy; 6670 if (!CompResultTy.isNull()) 6671 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 6672 break; 6673 case BO_AndAssign: 6674 case BO_XorAssign: 6675 case BO_OrAssign: 6676 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true); 6677 CompLHSTy = CompResultTy; 6678 if (!CompResultTy.isNull()) 6679 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy); 6680 break; 6681 case BO_Comma: 6682 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc); 6683 break; 6684 } 6685 if (ResultTy.isNull()) 6686 return ExprError(); 6687 if (ResultTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) { 6688 if (Opc >= BO_Assign && Opc <= BO_OrAssign) 6689 Diag(OpLoc, diag::err_assignment_requires_nonfragile_object) 6690 << ResultTy; 6691 } 6692 if (CompResultTy.isNull()) 6693 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc)); 6694 else 6695 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy, 6696 CompLHSTy, CompResultTy, 6697 OpLoc)); 6698} 6699 6700/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps 6701/// ParenRange in parentheses. 6702static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6703 const PartialDiagnostic &PD, 6704 const PartialDiagnostic &FirstNote, 6705 SourceRange FirstParenRange, 6706 const PartialDiagnostic &SecondNote, 6707 SourceRange SecondParenRange) { 6708 Self.Diag(Loc, PD); 6709 6710 if (!FirstNote.getDiagID()) 6711 return; 6712 6713 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd()); 6714 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) { 6715 // We can't display the parentheses, so just return. 6716 return; 6717 } 6718 6719 Self.Diag(Loc, FirstNote) 6720 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(") 6721 << FixItHint::CreateInsertion(EndLoc, ")"); 6722 6723 if (!SecondNote.getDiagID()) 6724 return; 6725 6726 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd()); 6727 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) { 6728 // We can't display the parentheses, so just dig the 6729 // warning/error and return. 6730 Self.Diag(Loc, SecondNote); 6731 return; 6732 } 6733 6734 Self.Diag(Loc, SecondNote) 6735 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(") 6736 << FixItHint::CreateInsertion(EndLoc, ")"); 6737} 6738 6739/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 6740/// operators are mixed in a way that suggests that the programmer forgot that 6741/// comparison operators have higher precedence. The most typical example of 6742/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 6743static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 6744 SourceLocation OpLoc,Expr *lhs,Expr *rhs){ 6745 typedef BinaryOperator BinOp; 6746 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1), 6747 rhsopc = static_cast<BinOp::Opcode>(-1); 6748 if (BinOp *BO = dyn_cast<BinOp>(lhs)) 6749 lhsopc = BO->getOpcode(); 6750 if (BinOp *BO = dyn_cast<BinOp>(rhs)) 6751 rhsopc = BO->getOpcode(); 6752 6753 // Subs are not binary operators. 6754 if (lhsopc == -1 && rhsopc == -1) 6755 return; 6756 6757 // Bitwise operations are sometimes used as eager logical ops. 6758 // Don't diagnose this. 6759 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) && 6760 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc))) 6761 return; 6762 6763 if (BinOp::isComparisonOp(lhsopc)) 6764 SuggestParentheses(Self, OpLoc, 6765 Self.PDiag(diag::warn_precedence_bitwise_rel) 6766 << SourceRange(lhs->getLocStart(), OpLoc) 6767 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc), 6768 Self.PDiag(diag::note_precedence_bitwise_first) 6769 << BinOp::getOpcodeStr(Opc), 6770 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()), 6771 Self.PDiag(diag::note_precedence_bitwise_silence) 6772 << BinOp::getOpcodeStr(lhsopc), 6773 lhs->getSourceRange()); 6774 else if (BinOp::isComparisonOp(rhsopc)) 6775 SuggestParentheses(Self, OpLoc, 6776 Self.PDiag(diag::warn_precedence_bitwise_rel) 6777 << SourceRange(OpLoc, rhs->getLocEnd()) 6778 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc), 6779 Self.PDiag(diag::note_precedence_bitwise_first) 6780 << BinOp::getOpcodeStr(Opc), 6781 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()), 6782 Self.PDiag(diag::note_precedence_bitwise_silence) 6783 << BinOp::getOpcodeStr(rhsopc), 6784 rhs->getSourceRange()); 6785} 6786 6787/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 6788/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3". 6789/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does. 6790static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 6791 SourceLocation OpLoc, Expr *lhs, Expr *rhs){ 6792 if (BinaryOperator::isBitwiseOp(Opc)) 6793 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs); 6794} 6795 6796// Binary Operators. 'Tok' is the token for the operator. 6797ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 6798 tok::TokenKind Kind, 6799 Expr *lhs, Expr *rhs) { 6800 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 6801 assert((lhs != 0) && "ActOnBinOp(): missing left expression"); 6802 assert((rhs != 0) && "ActOnBinOp(): missing right expression"); 6803 6804 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 6805 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs); 6806 6807 return BuildBinOp(S, TokLoc, Opc, lhs, rhs); 6808} 6809 6810ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 6811 BinaryOperatorKind Opc, 6812 Expr *lhs, Expr *rhs) { 6813 if (getLangOptions().CPlusPlus && 6814 ((!isa<ObjCImplicitSetterGetterRefExpr>(lhs) && 6815 !isa<ObjCPropertyRefExpr>(lhs)) 6816 || rhs->isTypeDependent() || Opc != BO_Assign) && 6817 (lhs->getType()->isOverloadableType() || 6818 rhs->getType()->isOverloadableType())) { 6819 // Find all of the overloaded operators visible from this 6820 // point. We perform both an operator-name lookup from the local 6821 // scope and an argument-dependent lookup based on the types of 6822 // the arguments. 6823 UnresolvedSet<16> Functions; 6824 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 6825 if (S && OverOp != OO_None) 6826 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(), 6827 Functions); 6828 6829 // Build the (potentially-overloaded, potentially-dependent) 6830 // binary operation. 6831 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs); 6832 } 6833 6834 // Build a built-in binary operation. 6835 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs); 6836} 6837 6838ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 6839 unsigned OpcIn, 6840 Expr *Input) { 6841 UnaryOperatorKind Opc = static_cast<UnaryOperatorKind>(OpcIn); 6842 6843 QualType resultType; 6844 switch (Opc) { 6845 case UO_PreInc: 6846 case UO_PreDec: 6847 case UO_PostInc: 6848 case UO_PostDec: 6849 resultType = CheckIncrementDecrementOperand(Input, OpLoc, 6850 Opc == UO_PreInc || 6851 Opc == UO_PostInc, 6852 Opc == UO_PreInc || 6853 Opc == UO_PreDec); 6854 break; 6855 case UO_AddrOf: 6856 resultType = CheckAddressOfOperand(Input, OpLoc); 6857 break; 6858 case UO_Deref: 6859 DefaultFunctionArrayLvalueConversion(Input); 6860 resultType = CheckIndirectionOperand(Input, OpLoc); 6861 break; 6862 case UO_Plus: 6863 case UO_Minus: 6864 UsualUnaryConversions(Input); 6865 resultType = Input->getType(); 6866 if (resultType->isDependentType()) 6867 break; 6868 if (resultType->isArithmeticType() || // C99 6.5.3.3p1 6869 resultType->isVectorType()) 6870 break; 6871 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7 6872 resultType->isEnumeralType()) 6873 break; 6874 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6 6875 Opc == UO_Plus && 6876 resultType->isPointerType()) 6877 break; 6878 else if (resultType->isPlaceholderType()) { 6879 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc); 6880 if (PR.isInvalid()) return ExprError(); 6881 return CreateBuiltinUnaryOp(OpLoc, OpcIn, PR.take()); 6882 } 6883 6884 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 6885 << resultType << Input->getSourceRange()); 6886 case UO_Not: // bitwise complement 6887 UsualUnaryConversions(Input); 6888 resultType = Input->getType(); 6889 if (resultType->isDependentType()) 6890 break; 6891 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 6892 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 6893 // C99 does not support '~' for complex conjugation. 6894 Diag(OpLoc, diag::ext_integer_complement_complex) 6895 << resultType << Input->getSourceRange(); 6896 else if (resultType->hasIntegerRepresentation()) 6897 break; 6898 else if (resultType->isPlaceholderType()) { 6899 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc); 6900 if (PR.isInvalid()) return ExprError(); 6901 return CreateBuiltinUnaryOp(OpLoc, OpcIn, PR.take()); 6902 } else { 6903 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 6904 << resultType << Input->getSourceRange()); 6905 } 6906 break; 6907 case UO_LNot: // logical negation 6908 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 6909 DefaultFunctionArrayLvalueConversion(Input); 6910 resultType = Input->getType(); 6911 if (resultType->isDependentType()) 6912 break; 6913 if (resultType->isScalarType()) { // C99 6.5.3.3p1 6914 // ok, fallthrough 6915 } else if (resultType->isPlaceholderType()) { 6916 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc); 6917 if (PR.isInvalid()) return ExprError(); 6918 return CreateBuiltinUnaryOp(OpLoc, OpcIn, PR.take()); 6919 } else { 6920 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 6921 << resultType << Input->getSourceRange()); 6922 } 6923 6924 // LNot always has type int. C99 6.5.3.3p5. 6925 // In C++, it's bool. C++ 5.3.1p8 6926 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy; 6927 break; 6928 case UO_Real: 6929 case UO_Imag: 6930 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UO_Real); 6931 break; 6932 case UO_Extension: 6933 resultType = Input->getType(); 6934 break; 6935 } 6936 if (resultType.isNull()) 6937 return ExprError(); 6938 6939 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc)); 6940} 6941 6942ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 6943 UnaryOperatorKind Opc, 6944 Expr *Input) { 6945 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() && 6946 UnaryOperator::getOverloadedOperator(Opc) != OO_None) { 6947 // Find all of the overloaded operators visible from this 6948 // point. We perform both an operator-name lookup from the local 6949 // scope and an argument-dependent lookup based on the types of 6950 // the arguments. 6951 UnresolvedSet<16> Functions; 6952 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 6953 if (S && OverOp != OO_None) 6954 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 6955 Functions); 6956 6957 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 6958 } 6959 6960 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 6961} 6962 6963// Unary Operators. 'Tok' is the token for the operator. 6964ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 6965 tok::TokenKind Op, Expr *Input) { 6966 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 6967} 6968 6969/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 6970ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, 6971 SourceLocation LabLoc, 6972 IdentifierInfo *LabelII) { 6973 // Look up the record for this label identifier. 6974 LabelStmt *&LabelDecl = getCurFunction()->LabelMap[LabelII]; 6975 6976 // If we haven't seen this label yet, create a forward reference. It 6977 // will be validated and/or cleaned up in ActOnFinishFunctionBody. 6978 if (LabelDecl == 0) 6979 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0); 6980 6981 LabelDecl->setUsed(); 6982 // Create the AST node. The address of a label always has type 'void*'. 6983 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl, 6984 Context.getPointerType(Context.VoidTy))); 6985} 6986 6987ExprResult 6988Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 6989 SourceLocation RPLoc) { // "({..})" 6990 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 6991 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 6992 6993 bool isFileScope 6994 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0); 6995 if (isFileScope) 6996 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 6997 6998 // FIXME: there are a variety of strange constraints to enforce here, for 6999 // example, it is not possible to goto into a stmt expression apparently. 7000 // More semantic analysis is needed. 7001 7002 // If there are sub stmts in the compound stmt, take the type of the last one 7003 // as the type of the stmtexpr. 7004 QualType Ty = Context.VoidTy; 7005 7006 if (!Compound->body_empty()) { 7007 Stmt *LastStmt = Compound->body_back(); 7008 // If LastStmt is a label, skip down through into the body. 7009 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) 7010 LastStmt = Label->getSubStmt(); 7011 7012 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) 7013 Ty = LastExpr->getType(); 7014 } 7015 7016 // FIXME: Check that expression type is complete/non-abstract; statement 7017 // expressions are not lvalues. 7018 7019 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc)); 7020} 7021 7022ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 7023 TypeSourceInfo *TInfo, 7024 OffsetOfComponent *CompPtr, 7025 unsigned NumComponents, 7026 SourceLocation RParenLoc) { 7027 QualType ArgTy = TInfo->getType(); 7028 bool Dependent = ArgTy->isDependentType(); 7029 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 7030 7031 // We must have at least one component that refers to the type, and the first 7032 // one is known to be a field designator. Verify that the ArgTy represents 7033 // a struct/union/class. 7034 if (!Dependent && !ArgTy->isRecordType()) 7035 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 7036 << ArgTy << TypeRange); 7037 7038 // Type must be complete per C99 7.17p3 because a declaring a variable 7039 // with an incomplete type would be ill-formed. 7040 if (!Dependent 7041 && RequireCompleteType(BuiltinLoc, ArgTy, 7042 PDiag(diag::err_offsetof_incomplete_type) 7043 << TypeRange)) 7044 return ExprError(); 7045 7046 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 7047 // GCC extension, diagnose them. 7048 // FIXME: This diagnostic isn't actually visible because the location is in 7049 // a system header! 7050 if (NumComponents != 1) 7051 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 7052 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 7053 7054 bool DidWarnAboutNonPOD = false; 7055 QualType CurrentType = ArgTy; 7056 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 7057 llvm::SmallVector<OffsetOfNode, 4> Comps; 7058 llvm::SmallVector<Expr*, 4> Exprs; 7059 for (unsigned i = 0; i != NumComponents; ++i) { 7060 const OffsetOfComponent &OC = CompPtr[i]; 7061 if (OC.isBrackets) { 7062 // Offset of an array sub-field. TODO: Should we allow vector elements? 7063 if (!CurrentType->isDependentType()) { 7064 const ArrayType *AT = Context.getAsArrayType(CurrentType); 7065 if(!AT) 7066 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 7067 << CurrentType); 7068 CurrentType = AT->getElementType(); 7069 } else 7070 CurrentType = Context.DependentTy; 7071 7072 // The expression must be an integral expression. 7073 // FIXME: An integral constant expression? 7074 Expr *Idx = static_cast<Expr*>(OC.U.E); 7075 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 7076 !Idx->getType()->isIntegerType()) 7077 return ExprError(Diag(Idx->getLocStart(), 7078 diag::err_typecheck_subscript_not_integer) 7079 << Idx->getSourceRange()); 7080 7081 // Record this array index. 7082 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 7083 Exprs.push_back(Idx); 7084 continue; 7085 } 7086 7087 // Offset of a field. 7088 if (CurrentType->isDependentType()) { 7089 // We have the offset of a field, but we can't look into the dependent 7090 // type. Just record the identifier of the field. 7091 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 7092 CurrentType = Context.DependentTy; 7093 continue; 7094 } 7095 7096 // We need to have a complete type to look into. 7097 if (RequireCompleteType(OC.LocStart, CurrentType, 7098 diag::err_offsetof_incomplete_type)) 7099 return ExprError(); 7100 7101 // Look for the designated field. 7102 const RecordType *RC = CurrentType->getAs<RecordType>(); 7103 if (!RC) 7104 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 7105 << CurrentType); 7106 RecordDecl *RD = RC->getDecl(); 7107 7108 // C++ [lib.support.types]p5: 7109 // The macro offsetof accepts a restricted set of type arguments in this 7110 // International Standard. type shall be a POD structure or a POD union 7111 // (clause 9). 7112 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 7113 if (!CRD->isPOD() && !DidWarnAboutNonPOD && 7114 DiagRuntimeBehavior(BuiltinLoc, 7115 PDiag(diag::warn_offsetof_non_pod_type) 7116 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 7117 << CurrentType)) 7118 DidWarnAboutNonPOD = true; 7119 } 7120 7121 // Look for the field. 7122 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 7123 LookupQualifiedName(R, RD); 7124 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 7125 if (!MemberDecl) 7126 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 7127 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 7128 OC.LocEnd)); 7129 7130 // C99 7.17p3: 7131 // (If the specified member is a bit-field, the behavior is undefined.) 7132 // 7133 // We diagnose this as an error. 7134 if (MemberDecl->getBitWidth()) { 7135 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 7136 << MemberDecl->getDeclName() 7137 << SourceRange(BuiltinLoc, RParenLoc); 7138 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 7139 return ExprError(); 7140 } 7141 7142 RecordDecl *Parent = MemberDecl->getParent(); 7143 bool AnonStructUnion = Parent->isAnonymousStructOrUnion(); 7144 if (AnonStructUnion) { 7145 do { 7146 Parent = cast<RecordDecl>(Parent->getParent()); 7147 } while (Parent->isAnonymousStructOrUnion()); 7148 } 7149 7150 // If the member was found in a base class, introduce OffsetOfNodes for 7151 // the base class indirections. 7152 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 7153 /*DetectVirtual=*/false); 7154 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 7155 CXXBasePath &Path = Paths.front(); 7156 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 7157 B != BEnd; ++B) 7158 Comps.push_back(OffsetOfNode(B->Base)); 7159 } 7160 7161 if (AnonStructUnion) { 7162 llvm::SmallVector<FieldDecl*, 4> Path; 7163 BuildAnonymousStructUnionMemberPath(MemberDecl, Path); 7164 unsigned n = Path.size(); 7165 for (int j = n - 1; j > -1; --j) 7166 Comps.push_back(OffsetOfNode(OC.LocStart, Path[j], OC.LocEnd)); 7167 } else { 7168 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 7169 } 7170 CurrentType = MemberDecl->getType().getNonReferenceType(); 7171 } 7172 7173 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 7174 TInfo, Comps.data(), Comps.size(), 7175 Exprs.data(), Exprs.size(), RParenLoc)); 7176} 7177 7178ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 7179 SourceLocation BuiltinLoc, 7180 SourceLocation TypeLoc, 7181 ParsedType argty, 7182 OffsetOfComponent *CompPtr, 7183 unsigned NumComponents, 7184 SourceLocation RPLoc) { 7185 7186 TypeSourceInfo *ArgTInfo; 7187 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo); 7188 if (ArgTy.isNull()) 7189 return ExprError(); 7190 7191 if (!ArgTInfo) 7192 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 7193 7194 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 7195 RPLoc); 7196} 7197 7198 7199ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc, 7200 ParsedType arg1, ParsedType arg2, 7201 SourceLocation RPLoc) { 7202 TypeSourceInfo *argTInfo1; 7203 QualType argT1 = GetTypeFromParser(arg1, &argTInfo1); 7204 TypeSourceInfo *argTInfo2; 7205 QualType argT2 = GetTypeFromParser(arg2, &argTInfo2); 7206 7207 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)"); 7208 7209 return BuildTypesCompatibleExpr(BuiltinLoc, argTInfo1, argTInfo2, RPLoc); 7210} 7211 7212ExprResult 7213Sema::BuildTypesCompatibleExpr(SourceLocation BuiltinLoc, 7214 TypeSourceInfo *argTInfo1, 7215 TypeSourceInfo *argTInfo2, 7216 SourceLocation RPLoc) { 7217 if (getLangOptions().CPlusPlus) { 7218 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus) 7219 << SourceRange(BuiltinLoc, RPLoc); 7220 return ExprError(); 7221 } 7222 7223 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, 7224 argTInfo1, argTInfo2, RPLoc)); 7225} 7226 7227 7228ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 7229 Expr *CondExpr, 7230 Expr *LHSExpr, Expr *RHSExpr, 7231 SourceLocation RPLoc) { 7232 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 7233 7234 QualType resType; 7235 bool ValueDependent = false; 7236 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 7237 resType = Context.DependentTy; 7238 ValueDependent = true; 7239 } else { 7240 // The conditional expression is required to be a constant expression. 7241 llvm::APSInt condEval(32); 7242 SourceLocation ExpLoc; 7243 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc)) 7244 return ExprError(Diag(ExpLoc, 7245 diag::err_typecheck_choose_expr_requires_constant) 7246 << CondExpr->getSourceRange()); 7247 7248 // If the condition is > zero, then the AST type is the same as the LSHExpr. 7249 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType(); 7250 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent() 7251 : RHSExpr->isValueDependent(); 7252 } 7253 7254 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 7255 resType, RPLoc, 7256 resType->isDependentType(), 7257 ValueDependent)); 7258} 7259 7260//===----------------------------------------------------------------------===// 7261// Clang Extensions. 7262//===----------------------------------------------------------------------===// 7263 7264/// ActOnBlockStart - This callback is invoked when a block literal is started. 7265void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) { 7266 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 7267 PushBlockScope(BlockScope, Block); 7268 CurContext->addDecl(Block); 7269 if (BlockScope) 7270 PushDeclContext(BlockScope, Block); 7271 else 7272 CurContext = Block; 7273} 7274 7275void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) { 7276 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!"); 7277 BlockScopeInfo *CurBlock = getCurBlock(); 7278 7279 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 7280 CurBlock->TheDecl->setSignatureAsWritten(Sig); 7281 QualType T = Sig->getType(); 7282 7283 bool isVariadic; 7284 QualType RetTy; 7285 if (const FunctionType *Fn = T->getAs<FunctionType>()) { 7286 CurBlock->FunctionType = T; 7287 RetTy = Fn->getResultType(); 7288 isVariadic = 7289 !isa<FunctionProtoType>(Fn) || cast<FunctionProtoType>(Fn)->isVariadic(); 7290 } else { 7291 RetTy = T; 7292 isVariadic = false; 7293 } 7294 7295 CurBlock->TheDecl->setIsVariadic(isVariadic); 7296 7297 // Don't allow returning an array by value. 7298 if (RetTy->isArrayType()) { 7299 Diag(ParamInfo.getSourceRange().getBegin(), diag::err_block_returns_array); 7300 return; 7301 } 7302 7303 // Don't allow returning a objc interface by value. 7304 if (RetTy->isObjCObjectType()) { 7305 Diag(ParamInfo.getSourceRange().getBegin(), 7306 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy; 7307 return; 7308 } 7309 7310 // Context.DependentTy is used as a placeholder for a missing block 7311 // return type. TODO: what should we do with declarators like: 7312 // ^ * { ... } 7313 // If the answer is "apply template argument deduction".... 7314 if (RetTy != Context.DependentTy) 7315 CurBlock->ReturnType = RetTy; 7316 7317 // Push block parameters from the declarator if we had them. 7318 llvm::SmallVector<ParmVarDecl*, 8> Params; 7319 if (isa<FunctionProtoType>(T)) { 7320 FunctionProtoTypeLoc TL = cast<FunctionProtoTypeLoc>(Sig->getTypeLoc()); 7321 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 7322 ParmVarDecl *Param = TL.getArg(I); 7323 if (Param->getIdentifier() == 0 && 7324 !Param->isImplicit() && 7325 !Param->isInvalidDecl() && 7326 !getLangOptions().CPlusPlus) 7327 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 7328 Params.push_back(Param); 7329 } 7330 7331 // Fake up parameter variables if we have a typedef, like 7332 // ^ fntype { ... } 7333 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 7334 for (FunctionProtoType::arg_type_iterator 7335 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) { 7336 ParmVarDecl *Param = 7337 BuildParmVarDeclForTypedef(CurBlock->TheDecl, 7338 ParamInfo.getSourceRange().getBegin(), 7339 *I); 7340 Params.push_back(Param); 7341 } 7342 } 7343 7344 // Set the parameters on the block decl. 7345 if (!Params.empty()) 7346 CurBlock->TheDecl->setParams(Params.data(), Params.size()); 7347 7348 // Finally we can process decl attributes. 7349 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 7350 7351 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) { 7352 Diag(ParamInfo.getAttributes()->getLoc(), 7353 diag::warn_attribute_sentinel_not_variadic) << 1; 7354 // FIXME: remove the attribute. 7355 } 7356 7357 // Put the parameter variables in scope. We can bail out immediately 7358 // if we don't have any. 7359 if (Params.empty()) 7360 return; 7361 7362 bool ShouldCheckShadow = 7363 Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored; 7364 7365 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 7366 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) { 7367 (*AI)->setOwningFunction(CurBlock->TheDecl); 7368 7369 // If this has an identifier, add it to the scope stack. 7370 if ((*AI)->getIdentifier()) { 7371 if (ShouldCheckShadow) 7372 CheckShadow(CurBlock->TheScope, *AI); 7373 7374 PushOnScopeChains(*AI, CurBlock->TheScope); 7375 } 7376 } 7377} 7378 7379/// ActOnBlockError - If there is an error parsing a block, this callback 7380/// is invoked to pop the information about the block from the action impl. 7381void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 7382 // Pop off CurBlock, handle nested blocks. 7383 PopDeclContext(); 7384 PopFunctionOrBlockScope(); 7385 // FIXME: Delete the ParmVarDecl objects as well??? 7386} 7387 7388/// ActOnBlockStmtExpr - This is called when the body of a block statement 7389/// literal was successfully completed. ^(int x){...} 7390ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 7391 Stmt *Body, Scope *CurScope) { 7392 // If blocks are disabled, emit an error. 7393 if (!LangOpts.Blocks) 7394 Diag(CaretLoc, diag::err_blocks_disable); 7395 7396 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 7397 7398 PopDeclContext(); 7399 7400 QualType RetTy = Context.VoidTy; 7401 if (!BSI->ReturnType.isNull()) 7402 RetTy = BSI->ReturnType; 7403 7404 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>(); 7405 QualType BlockTy; 7406 7407 // If the user wrote a function type in some form, try to use that. 7408 if (!BSI->FunctionType.isNull()) { 7409 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 7410 7411 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 7412 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 7413 7414 // Turn protoless block types into nullary block types. 7415 if (isa<FunctionNoProtoType>(FTy)) { 7416 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, 7417 false, false, 0, 0, Ext); 7418 7419 // Otherwise, if we don't need to change anything about the function type, 7420 // preserve its sugar structure. 7421 } else if (FTy->getResultType() == RetTy && 7422 (!NoReturn || FTy->getNoReturnAttr())) { 7423 BlockTy = BSI->FunctionType; 7424 7425 // Otherwise, make the minimal modifications to the function type. 7426 } else { 7427 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 7428 BlockTy = Context.getFunctionType(RetTy, 7429 FPT->arg_type_begin(), 7430 FPT->getNumArgs(), 7431 FPT->isVariadic(), 7432 /*quals*/ 0, 7433 FPT->hasExceptionSpec(), 7434 FPT->hasAnyExceptionSpec(), 7435 FPT->getNumExceptions(), 7436 FPT->exception_begin(), 7437 Ext); 7438 } 7439 7440 // If we don't have a function type, just build one from nothing. 7441 } else { 7442 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, 7443 false, false, 0, 0, 7444 FunctionType::ExtInfo(NoReturn, 0, CC_Default)); 7445 } 7446 7447 // FIXME: Check that return/parameter types are complete/non-abstract 7448 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 7449 BSI->TheDecl->param_end()); 7450 BlockTy = Context.getBlockPointerType(BlockTy); 7451 7452 // If needed, diagnose invalid gotos and switches in the block. 7453 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction()) 7454 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 7455 7456 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 7457 7458 bool Good = true; 7459 // Check goto/label use. 7460 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator 7461 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) { 7462 LabelStmt *L = I->second; 7463 7464 // Verify that we have no forward references left. If so, there was a goto 7465 // or address of a label taken, but no definition of it. 7466 if (L->getSubStmt() != 0) { 7467 if (!L->isUsed()) 7468 Diag(L->getIdentLoc(), diag::warn_unused_label) << L->getName(); 7469 continue; 7470 } 7471 7472 // Emit error. 7473 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName(); 7474 Good = false; 7475 } 7476 if (!Good) { 7477 PopFunctionOrBlockScope(); 7478 return ExprError(); 7479 } 7480 7481 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy, 7482 BSI->hasBlockDeclRefExprs); 7483 7484 // Issue any analysis-based warnings. 7485 const sema::AnalysisBasedWarnings::Policy &WP = 7486 AnalysisWarnings.getDefaultPolicy(); 7487 AnalysisWarnings.IssueWarnings(WP, Result); 7488 7489 PopFunctionOrBlockScope(); 7490 return Owned(Result); 7491} 7492 7493ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 7494 Expr *expr, ParsedType type, 7495 SourceLocation RPLoc) { 7496 TypeSourceInfo *TInfo; 7497 QualType T = GetTypeFromParser(type, &TInfo); 7498 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc); 7499} 7500 7501ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 7502 Expr *E, TypeSourceInfo *TInfo, 7503 SourceLocation RPLoc) { 7504 Expr *OrigExpr = E; 7505 7506 // Get the va_list type 7507 QualType VaListType = Context.getBuiltinVaListType(); 7508 if (VaListType->isArrayType()) { 7509 // Deal with implicit array decay; for example, on x86-64, 7510 // va_list is an array, but it's supposed to decay to 7511 // a pointer for va_arg. 7512 VaListType = Context.getArrayDecayedType(VaListType); 7513 // Make sure the input expression also decays appropriately. 7514 UsualUnaryConversions(E); 7515 } else { 7516 // Otherwise, the va_list argument must be an l-value because 7517 // it is modified by va_arg. 7518 if (!E->isTypeDependent() && 7519 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 7520 return ExprError(); 7521 } 7522 7523 if (!E->isTypeDependent() && 7524 !Context.hasSameType(VaListType, E->getType())) { 7525 return ExprError(Diag(E->getLocStart(), 7526 diag::err_first_argument_to_va_arg_not_of_type_va_list) 7527 << OrigExpr->getType() << E->getSourceRange()); 7528 } 7529 7530 // FIXME: Check that type is complete/non-abstract 7531 // FIXME: Warn if a non-POD type is passed in. 7532 7533 QualType T = TInfo->getType().getNonLValueExprType(Context); 7534 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T)); 7535} 7536 7537ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 7538 // The type of __null will be int or long, depending on the size of 7539 // pointers on the target. 7540 QualType Ty; 7541 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth()) 7542 Ty = Context.IntTy; 7543 else 7544 Ty = Context.LongTy; 7545 7546 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); 7547} 7548 7549static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType, 7550 Expr *SrcExpr, FixItHint &Hint) { 7551 if (!SemaRef.getLangOptions().ObjC1) 7552 return; 7553 7554 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 7555 if (!PT) 7556 return; 7557 7558 // Check if the destination is of type 'id'. 7559 if (!PT->isObjCIdType()) { 7560 // Check if the destination is the 'NSString' interface. 7561 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 7562 if (!ID || !ID->getIdentifier()->isStr("NSString")) 7563 return; 7564 } 7565 7566 // Strip off any parens and casts. 7567 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts()); 7568 if (!SL || SL->isWide()) 7569 return; 7570 7571 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@"); 7572} 7573 7574bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 7575 SourceLocation Loc, 7576 QualType DstType, QualType SrcType, 7577 Expr *SrcExpr, AssignmentAction Action, 7578 bool *Complained) { 7579 if (Complained) 7580 *Complained = false; 7581 7582 // Decode the result (notice that AST's are still created for extensions). 7583 bool isInvalid = false; 7584 unsigned DiagKind; 7585 FixItHint Hint; 7586 7587 switch (ConvTy) { 7588 default: assert(0 && "Unknown conversion type"); 7589 case Compatible: return false; 7590 case PointerToInt: 7591 DiagKind = diag::ext_typecheck_convert_pointer_int; 7592 break; 7593 case IntToPointer: 7594 DiagKind = diag::ext_typecheck_convert_int_pointer; 7595 break; 7596 case IncompatiblePointer: 7597 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint); 7598 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 7599 break; 7600 case IncompatiblePointerSign: 7601 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 7602 break; 7603 case FunctionVoidPointer: 7604 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 7605 break; 7606 case CompatiblePointerDiscardsQualifiers: 7607 // If the qualifiers lost were because we were applying the 7608 // (deprecated) C++ conversion from a string literal to a char* 7609 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 7610 // Ideally, this check would be performed in 7611 // CheckPointerTypesForAssignment. However, that would require a 7612 // bit of refactoring (so that the second argument is an 7613 // expression, rather than a type), which should be done as part 7614 // of a larger effort to fix CheckPointerTypesForAssignment for 7615 // C++ semantics. 7616 if (getLangOptions().CPlusPlus && 7617 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 7618 return false; 7619 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 7620 break; 7621 case IncompatibleNestedPointerQualifiers: 7622 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 7623 break; 7624 case IntToBlockPointer: 7625 DiagKind = diag::err_int_to_block_pointer; 7626 break; 7627 case IncompatibleBlockPointer: 7628 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 7629 break; 7630 case IncompatibleObjCQualifiedId: 7631 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 7632 // it can give a more specific diagnostic. 7633 DiagKind = diag::warn_incompatible_qualified_id; 7634 break; 7635 case IncompatibleVectors: 7636 DiagKind = diag::warn_incompatible_vectors; 7637 break; 7638 case Incompatible: 7639 DiagKind = diag::err_typecheck_convert_incompatible; 7640 isInvalid = true; 7641 break; 7642 } 7643 7644 QualType FirstType, SecondType; 7645 switch (Action) { 7646 case AA_Assigning: 7647 case AA_Initializing: 7648 // The destination type comes first. 7649 FirstType = DstType; 7650 SecondType = SrcType; 7651 break; 7652 7653 case AA_Returning: 7654 case AA_Passing: 7655 case AA_Converting: 7656 case AA_Sending: 7657 case AA_Casting: 7658 // The source type comes first. 7659 FirstType = SrcType; 7660 SecondType = DstType; 7661 break; 7662 } 7663 7664 Diag(Loc, DiagKind) << FirstType << SecondType << Action 7665 << SrcExpr->getSourceRange() << Hint; 7666 if (Complained) 7667 *Complained = true; 7668 return isInvalid; 7669} 7670 7671bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){ 7672 llvm::APSInt ICEResult; 7673 if (E->isIntegerConstantExpr(ICEResult, Context)) { 7674 if (Result) 7675 *Result = ICEResult; 7676 return false; 7677 } 7678 7679 Expr::EvalResult EvalResult; 7680 7681 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() || 7682 EvalResult.HasSideEffects) { 7683 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange(); 7684 7685 if (EvalResult.Diag) { 7686 // We only show the note if it's not the usual "invalid subexpression" 7687 // or if it's actually in a subexpression. 7688 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice || 7689 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens()) 7690 Diag(EvalResult.DiagLoc, EvalResult.Diag); 7691 } 7692 7693 return true; 7694 } 7695 7696 Diag(E->getExprLoc(), diag::ext_expr_not_ice) << 7697 E->getSourceRange(); 7698 7699 if (EvalResult.Diag && 7700 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored) 7701 Diag(EvalResult.DiagLoc, EvalResult.Diag); 7702 7703 if (Result) 7704 *Result = EvalResult.Val.getInt(); 7705 return false; 7706} 7707 7708void 7709Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) { 7710 ExprEvalContexts.push_back( 7711 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size())); 7712} 7713 7714void 7715Sema::PopExpressionEvaluationContext() { 7716 // Pop the current expression evaluation context off the stack. 7717 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back(); 7718 ExprEvalContexts.pop_back(); 7719 7720 if (Rec.Context == PotentiallyPotentiallyEvaluated) { 7721 if (Rec.PotentiallyReferenced) { 7722 // Mark any remaining declarations in the current position of the stack 7723 // as "referenced". If they were not meant to be referenced, semantic 7724 // analysis would have eliminated them (e.g., in ActOnCXXTypeId). 7725 for (PotentiallyReferencedDecls::iterator 7726 I = Rec.PotentiallyReferenced->begin(), 7727 IEnd = Rec.PotentiallyReferenced->end(); 7728 I != IEnd; ++I) 7729 MarkDeclarationReferenced(I->first, I->second); 7730 } 7731 7732 if (Rec.PotentiallyDiagnosed) { 7733 // Emit any pending diagnostics. 7734 for (PotentiallyEmittedDiagnostics::iterator 7735 I = Rec.PotentiallyDiagnosed->begin(), 7736 IEnd = Rec.PotentiallyDiagnosed->end(); 7737 I != IEnd; ++I) 7738 Diag(I->first, I->second); 7739 } 7740 } 7741 7742 // When are coming out of an unevaluated context, clear out any 7743 // temporaries that we may have created as part of the evaluation of 7744 // the expression in that context: they aren't relevant because they 7745 // will never be constructed. 7746 if (Rec.Context == Unevaluated && 7747 ExprTemporaries.size() > Rec.NumTemporaries) 7748 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries, 7749 ExprTemporaries.end()); 7750 7751 // Destroy the popped expression evaluation record. 7752 Rec.Destroy(); 7753} 7754 7755/// \brief Note that the given declaration was referenced in the source code. 7756/// 7757/// This routine should be invoke whenever a given declaration is referenced 7758/// in the source code, and where that reference occurred. If this declaration 7759/// reference means that the the declaration is used (C++ [basic.def.odr]p2, 7760/// C99 6.9p3), then the declaration will be marked as used. 7761/// 7762/// \param Loc the location where the declaration was referenced. 7763/// 7764/// \param D the declaration that has been referenced by the source code. 7765void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) { 7766 assert(D && "No declaration?"); 7767 7768 if (D->isUsed(false)) 7769 return; 7770 7771 // Mark a parameter or variable declaration "used", regardless of whether we're in a 7772 // template or not. The reason for this is that unevaluated expressions 7773 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and 7774 // -Wunused-parameters) 7775 if (isa<ParmVarDecl>(D) || 7776 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) { 7777 D->setUsed(true); 7778 return; 7779 } 7780 7781 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D)) 7782 return; 7783 7784 // Do not mark anything as "used" within a dependent context; wait for 7785 // an instantiation. 7786 if (CurContext->isDependentContext()) 7787 return; 7788 7789 switch (ExprEvalContexts.back().Context) { 7790 case Unevaluated: 7791 // We are in an expression that is not potentially evaluated; do nothing. 7792 return; 7793 7794 case PotentiallyEvaluated: 7795 // We are in a potentially-evaluated expression, so this declaration is 7796 // "used"; handle this below. 7797 break; 7798 7799 case PotentiallyPotentiallyEvaluated: 7800 // We are in an expression that may be potentially evaluated; queue this 7801 // declaration reference until we know whether the expression is 7802 // potentially evaluated. 7803 ExprEvalContexts.back().addReferencedDecl(Loc, D); 7804 return; 7805 7806 case PotentiallyEvaluatedIfUsed: 7807 // Referenced declarations will only be used if the construct in the 7808 // containing expression is used. 7809 return; 7810 } 7811 7812 // Note that this declaration has been used. 7813 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 7814 unsigned TypeQuals; 7815 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) { 7816 if (Constructor->getParent()->hasTrivialConstructor()) 7817 return; 7818 if (!Constructor->isUsed(false)) 7819 DefineImplicitDefaultConstructor(Loc, Constructor); 7820 } else if (Constructor->isImplicit() && 7821 Constructor->isCopyConstructor(TypeQuals)) { 7822 if (!Constructor->isUsed(false)) 7823 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals); 7824 } 7825 7826 MarkVTableUsed(Loc, Constructor->getParent()); 7827 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 7828 if (Destructor->isImplicit() && !Destructor->isUsed(false)) 7829 DefineImplicitDestructor(Loc, Destructor); 7830 if (Destructor->isVirtual()) 7831 MarkVTableUsed(Loc, Destructor->getParent()); 7832 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) { 7833 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() && 7834 MethodDecl->getOverloadedOperator() == OO_Equal) { 7835 if (!MethodDecl->isUsed(false)) 7836 DefineImplicitCopyAssignment(Loc, MethodDecl); 7837 } else if (MethodDecl->isVirtual()) 7838 MarkVTableUsed(Loc, MethodDecl->getParent()); 7839 } 7840 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 7841 // Implicit instantiation of function templates and member functions of 7842 // class templates. 7843 if (Function->isImplicitlyInstantiable()) { 7844 bool AlreadyInstantiated = false; 7845 if (FunctionTemplateSpecializationInfo *SpecInfo 7846 = Function->getTemplateSpecializationInfo()) { 7847 if (SpecInfo->getPointOfInstantiation().isInvalid()) 7848 SpecInfo->setPointOfInstantiation(Loc); 7849 else if (SpecInfo->getTemplateSpecializationKind() 7850 == TSK_ImplicitInstantiation) 7851 AlreadyInstantiated = true; 7852 } else if (MemberSpecializationInfo *MSInfo 7853 = Function->getMemberSpecializationInfo()) { 7854 if (MSInfo->getPointOfInstantiation().isInvalid()) 7855 MSInfo->setPointOfInstantiation(Loc); 7856 else if (MSInfo->getTemplateSpecializationKind() 7857 == TSK_ImplicitInstantiation) 7858 AlreadyInstantiated = true; 7859 } 7860 7861 if (!AlreadyInstantiated) { 7862 if (isa<CXXRecordDecl>(Function->getDeclContext()) && 7863 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass()) 7864 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function, 7865 Loc)); 7866 else 7867 PendingInstantiations.push_back(std::make_pair(Function, Loc)); 7868 } 7869 } else // Walk redefinitions, as some of them may be instantiable. 7870 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()), 7871 e(Function->redecls_end()); i != e; ++i) { 7872 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 7873 MarkDeclarationReferenced(Loc, *i); 7874 } 7875 7876 // FIXME: keep track of references to static functions 7877 7878 // Recursive functions should be marked when used from another function. 7879 if (CurContext != Function) 7880 Function->setUsed(true); 7881 7882 return; 7883 } 7884 7885 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 7886 // Implicit instantiation of static data members of class templates. 7887 if (Var->isStaticDataMember() && 7888 Var->getInstantiatedFromStaticDataMember()) { 7889 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 7890 assert(MSInfo && "Missing member specialization information?"); 7891 if (MSInfo->getPointOfInstantiation().isInvalid() && 7892 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) { 7893 MSInfo->setPointOfInstantiation(Loc); 7894 PendingInstantiations.push_back(std::make_pair(Var, Loc)); 7895 } 7896 } 7897 7898 // FIXME: keep track of references to static data? 7899 7900 D->setUsed(true); 7901 return; 7902 } 7903} 7904 7905namespace { 7906 // Mark all of the declarations referenced 7907 // FIXME: Not fully implemented yet! We need to have a better understanding 7908 // of when we're entering 7909 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 7910 Sema &S; 7911 SourceLocation Loc; 7912 7913 public: 7914 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 7915 7916 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 7917 7918 bool TraverseTemplateArgument(const TemplateArgument &Arg); 7919 bool TraverseRecordType(RecordType *T); 7920 }; 7921} 7922 7923bool MarkReferencedDecls::TraverseTemplateArgument( 7924 const TemplateArgument &Arg) { 7925 if (Arg.getKind() == TemplateArgument::Declaration) { 7926 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl()); 7927 } 7928 7929 return Inherited::TraverseTemplateArgument(Arg); 7930} 7931 7932bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 7933 if (ClassTemplateSpecializationDecl *Spec 7934 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 7935 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 7936 return TraverseTemplateArguments(Args.getFlatArgumentList(), 7937 Args.flat_size()); 7938 } 7939 7940 return true; 7941} 7942 7943void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 7944 MarkReferencedDecls Marker(*this, Loc); 7945 Marker.TraverseType(Context.getCanonicalType(T)); 7946} 7947 7948namespace { 7949 /// \brief Helper class that marks all of the declarations referenced by 7950 /// potentially-evaluated subexpressions as "referenced". 7951 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 7952 Sema &S; 7953 7954 public: 7955 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 7956 7957 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { } 7958 7959 void VisitDeclRefExpr(DeclRefExpr *E) { 7960 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl()); 7961 } 7962 7963 void VisitMemberExpr(MemberExpr *E) { 7964 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl()); 7965 Inherited::VisitMemberExpr(E); 7966 } 7967 7968 void VisitCXXNewExpr(CXXNewExpr *E) { 7969 if (E->getConstructor()) 7970 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor()); 7971 if (E->getOperatorNew()) 7972 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew()); 7973 if (E->getOperatorDelete()) 7974 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete()); 7975 Inherited::VisitCXXNewExpr(E); 7976 } 7977 7978 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 7979 if (E->getOperatorDelete()) 7980 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete()); 7981 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 7982 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 7983 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 7984 S.MarkDeclarationReferenced(E->getLocStart(), 7985 S.LookupDestructor(Record)); 7986 } 7987 7988 Inherited::VisitCXXDeleteExpr(E); 7989 } 7990 7991 void VisitCXXConstructExpr(CXXConstructExpr *E) { 7992 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor()); 7993 Inherited::VisitCXXConstructExpr(E); 7994 } 7995 7996 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) { 7997 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl()); 7998 } 7999 }; 8000} 8001 8002/// \brief Mark any declarations that appear within this expression or any 8003/// potentially-evaluated subexpressions as "referenced". 8004void Sema::MarkDeclarationsReferencedInExpr(Expr *E) { 8005 EvaluatedExprMarker(*this).Visit(E); 8006} 8007 8008/// \brief Emit a diagnostic that describes an effect on the run-time behavior 8009/// of the program being compiled. 8010/// 8011/// This routine emits the given diagnostic when the code currently being 8012/// type-checked is "potentially evaluated", meaning that there is a 8013/// possibility that the code will actually be executable. Code in sizeof() 8014/// expressions, code used only during overload resolution, etc., are not 8015/// potentially evaluated. This routine will suppress such diagnostics or, 8016/// in the absolutely nutty case of potentially potentially evaluated 8017/// expressions (C++ typeid), queue the diagnostic to potentially emit it 8018/// later. 8019/// 8020/// This routine should be used for all diagnostics that describe the run-time 8021/// behavior of a program, such as passing a non-POD value through an ellipsis. 8022/// Failure to do so will likely result in spurious diagnostics or failures 8023/// during overload resolution or within sizeof/alignof/typeof/typeid. 8024bool Sema::DiagRuntimeBehavior(SourceLocation Loc, 8025 const PartialDiagnostic &PD) { 8026 switch (ExprEvalContexts.back().Context ) { 8027 case Unevaluated: 8028 // The argument will never be evaluated, so don't complain. 8029 break; 8030 8031 case PotentiallyEvaluated: 8032 case PotentiallyEvaluatedIfUsed: 8033 Diag(Loc, PD); 8034 return true; 8035 8036 case PotentiallyPotentiallyEvaluated: 8037 ExprEvalContexts.back().addDiagnostic(Loc, PD); 8038 break; 8039 } 8040 8041 return false; 8042} 8043 8044bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 8045 CallExpr *CE, FunctionDecl *FD) { 8046 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 8047 return false; 8048 8049 PartialDiagnostic Note = 8050 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here) 8051 << FD->getDeclName() : PDiag(); 8052 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation(); 8053 8054 if (RequireCompleteType(Loc, ReturnType, 8055 FD ? 8056 PDiag(diag::err_call_function_incomplete_return) 8057 << CE->getSourceRange() << FD->getDeclName() : 8058 PDiag(diag::err_call_incomplete_return) 8059 << CE->getSourceRange(), 8060 std::make_pair(NoteLoc, Note))) 8061 return true; 8062 8063 return false; 8064} 8065 8066// Diagnose the common s/=/==/ typo. Note that adding parentheses 8067// will prevent this condition from triggering, which is what we want. 8068void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 8069 SourceLocation Loc; 8070 8071 unsigned diagnostic = diag::warn_condition_is_assignment; 8072 8073 if (isa<BinaryOperator>(E)) { 8074 BinaryOperator *Op = cast<BinaryOperator>(E); 8075 if (Op->getOpcode() != BO_Assign) 8076 return; 8077 8078 // Greylist some idioms by putting them into a warning subcategory. 8079 if (ObjCMessageExpr *ME 8080 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 8081 Selector Sel = ME->getSelector(); 8082 8083 // self = [<foo> init...] 8084 if (isSelfExpr(Op->getLHS()) 8085 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init")) 8086 diagnostic = diag::warn_condition_is_idiomatic_assignment; 8087 8088 // <foo> = [<bar> nextObject] 8089 else if (Sel.isUnarySelector() && 8090 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject") 8091 diagnostic = diag::warn_condition_is_idiomatic_assignment; 8092 } 8093 8094 Loc = Op->getOperatorLoc(); 8095 } else if (isa<CXXOperatorCallExpr>(E)) { 8096 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E); 8097 if (Op->getOperator() != OO_Equal) 8098 return; 8099 8100 Loc = Op->getOperatorLoc(); 8101 } else { 8102 // Not an assignment. 8103 return; 8104 } 8105 8106 SourceLocation Open = E->getSourceRange().getBegin(); 8107 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 8108 8109 Diag(Loc, diagnostic) << E->getSourceRange(); 8110 Diag(Loc, diag::note_condition_assign_to_comparison) 8111 << FixItHint::CreateReplacement(Loc, "=="); 8112 Diag(Loc, diag::note_condition_assign_silence) 8113 << FixItHint::CreateInsertion(Open, "(") 8114 << FixItHint::CreateInsertion(Close, ")"); 8115} 8116 8117bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) { 8118 DiagnoseAssignmentAsCondition(E); 8119 8120 if (!E->isTypeDependent()) { 8121 DefaultFunctionArrayLvalueConversion(E); 8122 8123 QualType T = E->getType(); 8124 8125 if (getLangOptions().CPlusPlus) { 8126 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4 8127 return true; 8128 } else if (!T->isScalarType()) { // C99 6.8.4.1p1 8129 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 8130 << T << E->getSourceRange(); 8131 return true; 8132 } 8133 } 8134 8135 return false; 8136} 8137 8138ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 8139 Expr *Sub) { 8140 if (!Sub) 8141 return ExprError(); 8142 8143 if (CheckBooleanCondition(Sub, Loc)) 8144 return ExprError(); 8145 8146 return Owned(Sub); 8147} 8148 8149/// Check for operands with placeholder types and complain if found. 8150/// Returns true if there was an error and no recovery was possible. 8151ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) { 8152 const BuiltinType *BT = E->getType()->getAs<BuiltinType>(); 8153 if (!BT || !BT->isPlaceholderType()) return Owned(E); 8154 8155 // If this is overload, check for a single overload. 8156 if (BT->getKind() == BuiltinType::Overload) { 8157 if (FunctionDecl *Specialization 8158 = ResolveSingleFunctionTemplateSpecialization(E)) { 8159 // The access doesn't really matter in this case. 8160 DeclAccessPair Found = DeclAccessPair::make(Specialization, 8161 Specialization->getAccess()); 8162 E = FixOverloadedFunctionReference(E, Found, Specialization); 8163 if (!E) return ExprError(); 8164 return Owned(E); 8165 } 8166 8167 Diag(Loc, diag::err_ovl_unresolvable) << E->getSourceRange(); 8168 return ExprError(); 8169 } 8170 8171 // Otherwise it's a use of undeduced auto. 8172 assert(BT->getKind() == BuiltinType::UndeducedAuto); 8173 8174 DeclRefExpr *DRE = cast<DeclRefExpr>(E->IgnoreParens()); 8175 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 8176 << DRE->getDecl() << E->getSourceRange(); 8177 return ExprError(); 8178} 8179