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