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