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