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