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