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