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