SemaExpr.cpp revision 7f3fec565aab6cad369f418dbcbe601d545c5ac0
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/Lex/Preprocessor.h" 20#include "clang/Lex/LiteralSupport.h" 21#include "clang/Basic/Diagnostic.h" 22#include "clang/Basic/SourceManager.h" 23#include "clang/Basic/TargetInfo.h" 24#include "clang/Parse/DeclSpec.h" 25#include "clang/Parse/Designator.h" 26#include "clang/Parse/Scope.h" 27using namespace clang; 28 29//===----------------------------------------------------------------------===// 30// Standard Promotions and Conversions 31//===----------------------------------------------------------------------===// 32 33/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 34void Sema::DefaultFunctionArrayConversion(Expr *&E) { 35 QualType Ty = E->getType(); 36 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 37 38 if (Ty->isFunctionType()) 39 ImpCastExprToType(E, Context.getPointerType(Ty)); 40 else if (Ty->isArrayType()) { 41 // In C90 mode, arrays only promote to pointers if the array expression is 42 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 43 // type 'array of type' is converted to an expression that has type 'pointer 44 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 45 // that has type 'array of type' ...". The relevant change is "an lvalue" 46 // (C90) to "an expression" (C99). 47 // 48 // C++ 4.2p1: 49 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 50 // T" can be converted to an rvalue of type "pointer to T". 51 // 52 if (getLangOptions().C99 || getLangOptions().CPlusPlus || 53 E->isLvalue(Context) == Expr::LV_Valid) 54 ImpCastExprToType(E, Context.getArrayDecayedType(Ty)); 55 } 56} 57 58/// UsualUnaryConversions - Performs various conversions that are common to most 59/// operators (C99 6.3). The conversions of array and function types are 60/// sometimes surpressed. For example, the array->pointer conversion doesn't 61/// apply if the array is an argument to the sizeof or address (&) operators. 62/// In these instances, this routine should *not* be called. 63Expr *Sema::UsualUnaryConversions(Expr *&Expr) { 64 QualType Ty = Expr->getType(); 65 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 66 67 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2 68 ImpCastExprToType(Expr, Context.IntTy); 69 else 70 DefaultFunctionArrayConversion(Expr); 71 72 return Expr; 73} 74 75/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 76/// do not have a prototype. Arguments that have type float are promoted to 77/// double. All other argument types are converted by UsualUnaryConversions(). 78void Sema::DefaultArgumentPromotion(Expr *&Expr) { 79 QualType Ty = Expr->getType(); 80 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 81 82 // If this is a 'float' (CVR qualified or typedef) promote to double. 83 if (const BuiltinType *BT = Ty->getAsBuiltinType()) 84 if (BT->getKind() == BuiltinType::Float) 85 return ImpCastExprToType(Expr, Context.DoubleTy); 86 87 UsualUnaryConversions(Expr); 88} 89 90/// UsualArithmeticConversions - Performs various conversions that are common to 91/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 92/// routine returns the first non-arithmetic type found. The client is 93/// responsible for emitting appropriate error diagnostics. 94/// FIXME: verify the conversion rules for "complex int" are consistent with 95/// GCC. 96QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr, 97 bool isCompAssign) { 98 if (!isCompAssign) { 99 UsualUnaryConversions(lhsExpr); 100 UsualUnaryConversions(rhsExpr); 101 } 102 103 // For conversion purposes, we ignore any qualifiers. 104 // For example, "const float" and "float" are equivalent. 105 QualType lhs = 106 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType(); 107 QualType rhs = 108 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType(); 109 110 // If both types are identical, no conversion is needed. 111 if (lhs == rhs) 112 return lhs; 113 114 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 115 // The caller can deal with this (e.g. pointer + int). 116 if (!lhs->isArithmeticType() || !rhs->isArithmeticType()) 117 return lhs; 118 119 QualType destType = UsualArithmeticConversionsType(lhs, rhs); 120 if (!isCompAssign) { 121 ImpCastExprToType(lhsExpr, destType); 122 ImpCastExprToType(rhsExpr, destType); 123 } 124 return destType; 125} 126 127QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) { 128 // Perform the usual unary conversions. We do this early so that 129 // integral promotions to "int" can allow us to exit early, in the 130 // lhs == rhs check. Also, for conversion purposes, we ignore any 131 // qualifiers. For example, "const float" and "float" are 132 // equivalent. 133 if (lhs->isPromotableIntegerType()) lhs = Context.IntTy; 134 else lhs = lhs.getUnqualifiedType(); 135 if (rhs->isPromotableIntegerType()) rhs = Context.IntTy; 136 else rhs = rhs.getUnqualifiedType(); 137 138 // If both types are identical, no conversion is needed. 139 if (lhs == rhs) 140 return lhs; 141 142 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 143 // The caller can deal with this (e.g. pointer + int). 144 if (!lhs->isArithmeticType() || !rhs->isArithmeticType()) 145 return lhs; 146 147 // At this point, we have two different arithmetic types. 148 149 // Handle complex types first (C99 6.3.1.8p1). 150 if (lhs->isComplexType() || rhs->isComplexType()) { 151 // if we have an integer operand, the result is the complex type. 152 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) { 153 // convert the rhs to the lhs complex type. 154 return lhs; 155 } 156 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) { 157 // convert the lhs to the rhs complex type. 158 return rhs; 159 } 160 // This handles complex/complex, complex/float, or float/complex. 161 // When both operands are complex, the shorter operand is converted to the 162 // type of the longer, and that is the type of the result. This corresponds 163 // to what is done when combining two real floating-point operands. 164 // The fun begins when size promotion occur across type domains. 165 // From H&S 6.3.4: When one operand is complex and the other is a real 166 // floating-point type, the less precise type is converted, within it's 167 // real or complex domain, to the precision of the other type. For example, 168 // when combining a "long double" with a "double _Complex", the 169 // "double _Complex" is promoted to "long double _Complex". 170 int result = Context.getFloatingTypeOrder(lhs, rhs); 171 172 if (result > 0) { // The left side is bigger, convert rhs. 173 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs); 174 } else if (result < 0) { // The right side is bigger, convert lhs. 175 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs); 176 } 177 // At this point, lhs and rhs have the same rank/size. Now, make sure the 178 // domains match. This is a requirement for our implementation, C99 179 // does not require this promotion. 180 if (lhs != rhs) { // Domains don't match, we have complex/float mix. 181 if (lhs->isRealFloatingType()) { // handle "double, _Complex double". 182 return rhs; 183 } else { // handle "_Complex double, double". 184 return lhs; 185 } 186 } 187 return lhs; // The domain/size match exactly. 188 } 189 // Now handle "real" floating types (i.e. float, double, long double). 190 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) { 191 // if we have an integer operand, the result is the real floating type. 192 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) { 193 // convert rhs to the lhs floating point type. 194 return lhs; 195 } 196 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) { 197 // convert lhs to the rhs floating point type. 198 return rhs; 199 } 200 // We have two real floating types, float/complex combos were handled above. 201 // Convert the smaller operand to the bigger result. 202 int result = Context.getFloatingTypeOrder(lhs, rhs); 203 204 if (result > 0) { // convert the rhs 205 return lhs; 206 } 207 if (result < 0) { // convert the lhs 208 return rhs; 209 } 210 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison"); 211 } 212 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) { 213 // Handle GCC complex int extension. 214 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType(); 215 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType(); 216 217 if (lhsComplexInt && rhsComplexInt) { 218 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(), 219 rhsComplexInt->getElementType()) >= 0) { 220 // convert the rhs 221 return lhs; 222 } 223 return rhs; 224 } else if (lhsComplexInt && rhs->isIntegerType()) { 225 // convert the rhs to the lhs complex type. 226 return lhs; 227 } else if (rhsComplexInt && lhs->isIntegerType()) { 228 // convert the lhs to the rhs complex type. 229 return rhs; 230 } 231 } 232 // Finally, we have two differing integer types. 233 // The rules for this case are in C99 6.3.1.8 234 int compare = Context.getIntegerTypeOrder(lhs, rhs); 235 bool lhsSigned = lhs->isSignedIntegerType(), 236 rhsSigned = rhs->isSignedIntegerType(); 237 QualType destType; 238 if (lhsSigned == rhsSigned) { 239 // Same signedness; use the higher-ranked type 240 destType = compare >= 0 ? lhs : rhs; 241 } else if (compare != (lhsSigned ? 1 : -1)) { 242 // The unsigned type has greater than or equal rank to the 243 // signed type, so use the unsigned type 244 destType = lhsSigned ? rhs : lhs; 245 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) { 246 // The two types are different widths; if we are here, that 247 // means the signed type is larger than the unsigned type, so 248 // use the signed type. 249 destType = lhsSigned ? lhs : rhs; 250 } else { 251 // The signed type is higher-ranked than the unsigned type, 252 // but isn't actually any bigger (like unsigned int and long 253 // on most 32-bit systems). Use the unsigned type corresponding 254 // to the signed type. 255 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs); 256 } 257 return destType; 258} 259 260//===----------------------------------------------------------------------===// 261// Semantic Analysis for various Expression Types 262//===----------------------------------------------------------------------===// 263 264 265/// ActOnStringLiteral - The specified tokens were lexed as pasted string 266/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 267/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 268/// multiple tokens. However, the common case is that StringToks points to one 269/// string. 270/// 271Action::ExprResult 272Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) { 273 assert(NumStringToks && "Must have at least one string!"); 274 275 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target); 276 if (Literal.hadError) 277 return ExprResult(true); 278 279 llvm::SmallVector<SourceLocation, 4> StringTokLocs; 280 for (unsigned i = 0; i != NumStringToks; ++i) 281 StringTokLocs.push_back(StringToks[i].getLocation()); 282 283 // Verify that pascal strings aren't too large. 284 if (Literal.Pascal && Literal.GetStringLength() > 256) 285 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long) 286 << SourceRange(StringToks[0].getLocation(), 287 StringToks[NumStringToks-1].getLocation()); 288 289 QualType StrTy = Context.CharTy; 290 if (Literal.AnyWide) StrTy = Context.getWCharType(); 291 if (Literal.Pascal) StrTy = Context.UnsignedCharTy; 292 293 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 294 if (getLangOptions().CPlusPlus) 295 StrTy.addConst(); 296 297 // Get an array type for the string, according to C99 6.4.5. This includes 298 // the nul terminator character as well as the string length for pascal 299 // strings. 300 StrTy = Context.getConstantArrayType(StrTy, 301 llvm::APInt(32, Literal.GetStringLength()+1), 302 ArrayType::Normal, 0); 303 304 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 305 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(), 306 Literal.AnyWide, StrTy, 307 StringToks[0].getLocation(), 308 StringToks[NumStringToks-1].getLocation()); 309} 310 311/// ShouldSnapshotBlockValueReference - Return true if a reference inside of 312/// CurBlock to VD should cause it to be snapshotted (as we do for auto 313/// variables defined outside the block) or false if this is not needed (e.g. 314/// for values inside the block or for globals). 315/// 316/// FIXME: This will create BlockDeclRefExprs for global variables, 317/// function references, etc which is suboptimal :) and breaks 318/// things like "integer constant expression" tests. 319static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock, 320 ValueDecl *VD) { 321 // If the value is defined inside the block, we couldn't snapshot it even if 322 // we wanted to. 323 if (CurBlock->TheDecl == VD->getDeclContext()) 324 return false; 325 326 // If this is an enum constant or function, it is constant, don't snapshot. 327 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD)) 328 return false; 329 330 // If this is a reference to an extern, static, or global variable, no need to 331 // snapshot it. 332 // FIXME: What about 'const' variables in C++? 333 if (const VarDecl *Var = dyn_cast<VarDecl>(VD)) 334 return Var->hasLocalStorage(); 335 336 return true; 337} 338 339 340 341/// ActOnIdentifierExpr - The parser read an identifier in expression context, 342/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this 343/// identifier is used in a function call context. 344/// LookupCtx is only used for a C++ qualified-id (foo::bar) to indicate the 345/// class or namespace that the identifier must be a member of. 346Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc, 347 IdentifierInfo &II, 348 bool HasTrailingLParen, 349 const CXXScopeSpec *SS) { 350 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS); 351} 352 353/// ActOnDeclarationNameExpr - The parser has read some kind of name 354/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine 355/// performs lookup on that name and returns an expression that refers 356/// to that name. This routine isn't directly called from the parser, 357/// because the parser doesn't know about DeclarationName. Rather, 358/// this routine is called by ActOnIdentifierExpr, 359/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr, 360/// which form the DeclarationName from the corresponding syntactic 361/// forms. 362/// 363/// HasTrailingLParen indicates whether this identifier is used in a 364/// function call context. LookupCtx is only used for a C++ 365/// qualified-id (foo::bar) to indicate the class or namespace that 366/// the identifier must be a member of. 367Sema::ExprResult Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc, 368 DeclarationName Name, 369 bool HasTrailingLParen, 370 const CXXScopeSpec *SS) { 371 // Could be enum-constant, value decl, instance variable, etc. 372 Decl *D; 373 if (SS && !SS->isEmpty()) { 374 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep()); 375 if (DC == 0) 376 return true; 377 D = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC); 378 } else 379 D = LookupDecl(Name, Decl::IDNS_Ordinary, S); 380 381 // If this reference is in an Objective-C method, then ivar lookup happens as 382 // well. 383 IdentifierInfo *II = Name.getAsIdentifierInfo(); 384 if (II && getCurMethodDecl()) { 385 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D); 386 // There are two cases to handle here. 1) scoped lookup could have failed, 387 // in which case we should look for an ivar. 2) scoped lookup could have 388 // found a decl, but that decl is outside the current method (i.e. a global 389 // variable). In these two cases, we do a lookup for an ivar with this 390 // name, if the lookup suceeds, we replace it our current decl. 391 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) { 392 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface(); 393 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) { 394 // FIXME: This should use a new expr for a direct reference, don't turn 395 // this into Self->ivar, just return a BareIVarExpr or something. 396 IdentifierInfo &II = Context.Idents.get("self"); 397 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false); 398 return new ObjCIvarRefExpr(IV, IV->getType(), Loc, 399 static_cast<Expr*>(SelfExpr.Val), true, true); 400 } 401 } 402 // Needed to implement property "super.method" notation. 403 if (SD == 0 && II->isStr("super")) { 404 QualType T = Context.getPointerType(Context.getObjCInterfaceType( 405 getCurMethodDecl()->getClassInterface())); 406 return new ObjCSuperExpr(Loc, T); 407 } 408 } 409 if (D == 0) { 410 // Otherwise, this could be an implicitly declared function reference (legal 411 // in C90, extension in C99). 412 if (HasTrailingLParen && II && 413 !getLangOptions().CPlusPlus) // Not in C++. 414 D = ImplicitlyDefineFunction(Loc, *II, S); 415 else { 416 // If this name wasn't predeclared and if this is not a function call, 417 // diagnose the problem. 418 if (SS && !SS->isEmpty()) 419 return Diag(Loc, diag::err_typecheck_no_member) 420 << Name.getAsString() << SS->getRange(); 421 else if (Name.getNameKind() == DeclarationName::CXXOperatorName || 422 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) 423 return Diag(Loc, diag::err_undeclared_use) << Name.getAsString(); 424 else 425 return Diag(Loc, diag::err_undeclared_var_use) << Name.getAsString(); 426 } 427 } 428 429 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) { 430 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { 431 if (MD->isStatic()) 432 // "invalid use of member 'x' in static member function" 433 return Diag(Loc, diag::err_invalid_member_use_in_static_method) 434 << FD->getName(); 435 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent()) 436 // "invalid use of nonstatic data member 'x'" 437 return Diag(Loc, diag::err_invalid_non_static_member_use) 438 << FD->getName(); 439 440 if (FD->isInvalidDecl()) 441 return true; 442 443 // FIXME: Handle 'mutable'. 444 return new DeclRefExpr(FD, 445 FD->getType().getWithAdditionalQualifiers(MD->getTypeQualifiers()),Loc); 446 } 447 448 return Diag(Loc, diag::err_invalid_non_static_member_use) << FD->getName(); 449 } 450 if (isa<TypedefDecl>(D)) 451 return Diag(Loc, diag::err_unexpected_typedef) << Name.getAsString(); 452 if (isa<ObjCInterfaceDecl>(D)) 453 return Diag(Loc, diag::err_unexpected_interface) << Name.getAsString(); 454 if (isa<NamespaceDecl>(D)) 455 return Diag(Loc, diag::err_unexpected_namespace) << Name.getAsString(); 456 457 // Make the DeclRefExpr or BlockDeclRefExpr for the decl. 458 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D)) 459 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc); 460 461 ValueDecl *VD = cast<ValueDecl>(D); 462 463 // check if referencing an identifier with __attribute__((deprecated)). 464 if (VD->getAttr<DeprecatedAttr>()) 465 Diag(Loc, diag::warn_deprecated) << VD->getName(); 466 467 // Only create DeclRefExpr's for valid Decl's. 468 if (VD->isInvalidDecl()) 469 return true; 470 471 // If the identifier reference is inside a block, and it refers to a value 472 // that is outside the block, create a BlockDeclRefExpr instead of a 473 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when 474 // the block is formed. 475 // 476 // We do not do this for things like enum constants, global variables, etc, 477 // as they do not get snapshotted. 478 // 479 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) { 480 // The BlocksAttr indicates the variable is bound by-reference. 481 if (VD->getAttr<BlocksAttr>()) 482 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(), 483 Loc, true); 484 485 // Variable will be bound by-copy, make it const within the closure. 486 VD->getType().addConst(); 487 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(), 488 Loc, false); 489 } 490 // If this reference is not in a block or if the referenced variable is 491 // within the block, create a normal DeclRefExpr. 492 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc); 493} 494 495Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, 496 tok::TokenKind Kind) { 497 PredefinedExpr::IdentType IT; 498 499 switch (Kind) { 500 default: assert(0 && "Unknown simple primary expr!"); 501 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 502 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 503 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 504 } 505 506 // Verify that this is in a function context. 507 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0) 508 return Diag(Loc, diag::err_predef_outside_function); 509 510 // Pre-defined identifiers are of type char[x], where x is the length of the 511 // string. 512 unsigned Length; 513 if (getCurFunctionDecl()) 514 Length = getCurFunctionDecl()->getIdentifier()->getLength(); 515 else 516 Length = getCurMethodDecl()->getSynthesizedMethodSize(); 517 518 llvm::APInt LengthI(32, Length + 1); 519 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const); 520 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 521 return new PredefinedExpr(Loc, ResTy, IT); 522} 523 524Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) { 525 llvm::SmallString<16> CharBuffer; 526 CharBuffer.resize(Tok.getLength()); 527 const char *ThisTokBegin = &CharBuffer[0]; 528 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin); 529 530 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 531 Tok.getLocation(), PP); 532 if (Literal.hadError()) 533 return ExprResult(true); 534 535 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy; 536 537 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type, 538 Tok.getLocation()); 539} 540 541Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) { 542 // fast path for a single digit (which is quite common). A single digit 543 // cannot have a trigraph, escaped newline, radix prefix, or type suffix. 544 if (Tok.getLength() == 1) { 545 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation()); 546 547 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy)); 548 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'), 549 Context.IntTy, 550 Tok.getLocation())); 551 } 552 llvm::SmallString<512> IntegerBuffer; 553 // Add padding so that NumericLiteralParser can overread by one character. 554 IntegerBuffer.resize(Tok.getLength()+1); 555 const char *ThisTokBegin = &IntegerBuffer[0]; 556 557 // Get the spelling of the token, which eliminates trigraphs, etc. 558 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin); 559 560 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 561 Tok.getLocation(), PP); 562 if (Literal.hadError) 563 return ExprResult(true); 564 565 Expr *Res; 566 567 if (Literal.isFloatingLiteral()) { 568 QualType Ty; 569 if (Literal.isFloat) 570 Ty = Context.FloatTy; 571 else if (!Literal.isLong) 572 Ty = Context.DoubleTy; 573 else 574 Ty = Context.LongDoubleTy; 575 576 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty); 577 578 // isExact will be set by GetFloatValue(). 579 bool isExact = false; 580 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact, 581 Ty, Tok.getLocation()); 582 583 } else if (!Literal.isIntegerLiteral()) { 584 return ExprResult(true); 585 } else { 586 QualType Ty; 587 588 // long long is a C99 feature. 589 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x && 590 Literal.isLongLong) 591 Diag(Tok.getLocation(), diag::ext_longlong); 592 593 // Get the value in the widest-possible width. 594 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0); 595 596 if (Literal.GetIntegerValue(ResultVal)) { 597 // If this value didn't fit into uintmax_t, warn and force to ull. 598 Diag(Tok.getLocation(), diag::warn_integer_too_large); 599 Ty = Context.UnsignedLongLongTy; 600 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 601 "long long is not intmax_t?"); 602 } else { 603 // If this value fits into a ULL, try to figure out what else it fits into 604 // according to the rules of C99 6.4.4.1p5. 605 606 // Octal, Hexadecimal, and integers with a U suffix are allowed to 607 // be an unsigned int. 608 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 609 610 // Check from smallest to largest, picking the smallest type we can. 611 unsigned Width = 0; 612 if (!Literal.isLong && !Literal.isLongLong) { 613 // Are int/unsigned possibilities? 614 unsigned IntSize = Context.Target.getIntWidth(); 615 616 // Does it fit in a unsigned int? 617 if (ResultVal.isIntN(IntSize)) { 618 // Does it fit in a signed int? 619 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 620 Ty = Context.IntTy; 621 else if (AllowUnsigned) 622 Ty = Context.UnsignedIntTy; 623 Width = IntSize; 624 } 625 } 626 627 // Are long/unsigned long possibilities? 628 if (Ty.isNull() && !Literal.isLongLong) { 629 unsigned LongSize = Context.Target.getLongWidth(); 630 631 // Does it fit in a unsigned long? 632 if (ResultVal.isIntN(LongSize)) { 633 // Does it fit in a signed long? 634 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 635 Ty = Context.LongTy; 636 else if (AllowUnsigned) 637 Ty = Context.UnsignedLongTy; 638 Width = LongSize; 639 } 640 } 641 642 // Finally, check long long if needed. 643 if (Ty.isNull()) { 644 unsigned LongLongSize = Context.Target.getLongLongWidth(); 645 646 // Does it fit in a unsigned long long? 647 if (ResultVal.isIntN(LongLongSize)) { 648 // Does it fit in a signed long long? 649 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0) 650 Ty = Context.LongLongTy; 651 else if (AllowUnsigned) 652 Ty = Context.UnsignedLongLongTy; 653 Width = LongLongSize; 654 } 655 } 656 657 // If we still couldn't decide a type, we probably have something that 658 // does not fit in a signed long long, but has no U suffix. 659 if (Ty.isNull()) { 660 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 661 Ty = Context.UnsignedLongLongTy; 662 Width = Context.Target.getLongLongWidth(); 663 } 664 665 if (ResultVal.getBitWidth() != Width) 666 ResultVal.trunc(Width); 667 } 668 669 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation()); 670 } 671 672 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 673 if (Literal.isImaginary) 674 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType())); 675 676 return Res; 677} 678 679Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, 680 ExprTy *Val) { 681 Expr *E = (Expr *)Val; 682 assert((E != 0) && "ActOnParenExpr() missing expr"); 683 return new ParenExpr(L, R, E); 684} 685 686/// The UsualUnaryConversions() function is *not* called by this routine. 687/// See C99 6.3.2.1p[2-4] for more details. 688bool Sema::CheckSizeOfAlignOfOperand(QualType exprType, 689 SourceLocation OpLoc, 690 const SourceRange &ExprRange, 691 bool isSizeof) { 692 // C99 6.5.3.4p1: 693 if (isa<FunctionType>(exprType) && isSizeof) 694 // alignof(function) is allowed. 695 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange; 696 else if (exprType->isVoidType()) 697 Diag(OpLoc, diag::ext_sizeof_void_type) 698 << (isSizeof ? "sizeof" : "__alignof") << ExprRange; 699 else if (exprType->isIncompleteType()) 700 return Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type : 701 diag::err_alignof_incomplete_type) 702 << exprType.getAsString() << ExprRange; 703 704 return false; 705} 706 707/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and 708/// the same for @c alignof and @c __alignof 709/// Note that the ArgRange is invalid if isType is false. 710Action::ExprResult 711Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType, 712 void *TyOrEx, const SourceRange &ArgRange) { 713 // If error parsing type, ignore. 714 if (TyOrEx == 0) return true; 715 716 QualType ArgTy; 717 SourceRange Range; 718 if (isType) { 719 ArgTy = QualType::getFromOpaquePtr(TyOrEx); 720 Range = ArgRange; 721 } else { 722 // Get the end location. 723 Expr *ArgEx = (Expr *)TyOrEx; 724 Range = ArgEx->getSourceRange(); 725 ArgTy = ArgEx->getType(); 726 } 727 728 // Verify that the operand is valid. 729 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof)) 730 return true; 731 732 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 733 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(), 734 OpLoc, Range.getEnd()); 735} 736 737QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) { 738 DefaultFunctionArrayConversion(V); 739 740 // These operators return the element type of a complex type. 741 if (const ComplexType *CT = V->getType()->getAsComplexType()) 742 return CT->getElementType(); 743 744 // Otherwise they pass through real integer and floating point types here. 745 if (V->getType()->isArithmeticType()) 746 return V->getType(); 747 748 // Reject anything else. 749 Diag(Loc, diag::err_realimag_invalid_type) << V->getType().getAsString(); 750 return QualType(); 751} 752 753 754 755Action::ExprResult Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 756 tok::TokenKind Kind, 757 ExprTy *Input) { 758 Expr *Arg = (Expr *)Input; 759 760 UnaryOperator::Opcode Opc; 761 switch (Kind) { 762 default: assert(0 && "Unknown unary op!"); 763 case tok::plusplus: Opc = UnaryOperator::PostInc; break; 764 case tok::minusminus: Opc = UnaryOperator::PostDec; break; 765 } 766 767 if (getLangOptions().CPlusPlus && 768 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) { 769 // Which overloaded operator? 770 OverloadedOperatorKind OverOp = 771 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus; 772 773 // C++ [over.inc]p1: 774 // 775 // [...] If the function is a member function with one 776 // parameter (which shall be of type int) or a non-member 777 // function with two parameters (the second of which shall be 778 // of type int), it defines the postfix increment operator ++ 779 // for objects of that type. When the postfix increment is 780 // called as a result of using the ++ operator, the int 781 // argument will have value zero. 782 Expr *Args[2] = { 783 Arg, 784 new IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0, 785 /*isSigned=*/true), 786 Context.IntTy, SourceLocation()) 787 }; 788 789 // Build the candidate set for overloading 790 OverloadCandidateSet CandidateSet; 791 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet); 792 793 // Perform overload resolution. 794 OverloadCandidateSet::iterator Best; 795 switch (BestViableFunction(CandidateSet, Best)) { 796 case OR_Success: { 797 // We found a built-in operator or an overloaded operator. 798 FunctionDecl *FnDecl = Best->Function; 799 800 if (FnDecl) { 801 // We matched an overloaded operator. Build a call to that 802 // operator. 803 804 // Convert the arguments. 805 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 806 if (PerformObjectArgumentInitialization(Arg, Method)) 807 return true; 808 } else { 809 // Convert the arguments. 810 if (PerformCopyInitialization(Arg, 811 FnDecl->getParamDecl(0)->getType(), 812 "passing")) 813 return true; 814 } 815 816 // Determine the result type 817 QualType ResultTy 818 = FnDecl->getType()->getAsFunctionType()->getResultType(); 819 ResultTy = ResultTy.getNonReferenceType(); 820 821 // Build the actual expression node. 822 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(), 823 SourceLocation()); 824 UsualUnaryConversions(FnExpr); 825 826 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, OpLoc); 827 } else { 828 // We matched a built-in operator. Convert the arguments, then 829 // break out so that we will build the appropriate built-in 830 // operator node. 831 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0], 832 "passing")) 833 return true; 834 835 break; 836 } 837 } 838 839 case OR_No_Viable_Function: 840 // No viable function; fall through to handling this as a 841 // built-in operator, which will produce an error message for us. 842 break; 843 844 case OR_Ambiguous: 845 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 846 << UnaryOperator::getOpcodeStr(Opc) 847 << Arg->getSourceRange(); 848 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 849 return true; 850 } 851 852 // Either we found no viable overloaded operator or we matched a 853 // built-in operator. In either case, fall through to trying to 854 // build a built-in operation. 855 } 856 857 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc); 858 if (result.isNull()) 859 return true; 860 return new UnaryOperator(Arg, Opc, result, OpLoc); 861} 862 863Action::ExprResult Sema:: 864ActOnArraySubscriptExpr(Scope *S, ExprTy *Base, SourceLocation LLoc, 865 ExprTy *Idx, SourceLocation RLoc) { 866 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx); 867 868 if (getLangOptions().CPlusPlus && 869 LHSExp->getType()->isRecordType() || 870 LHSExp->getType()->isEnumeralType() || 871 RHSExp->getType()->isRecordType() || 872 RHSExp->getType()->isRecordType()) { 873 // Add the appropriate overloaded operators (C++ [over.match.oper]) 874 // to the candidate set. 875 OverloadCandidateSet CandidateSet; 876 Expr *Args[2] = { LHSExp, RHSExp }; 877 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet); 878 879 // Perform overload resolution. 880 OverloadCandidateSet::iterator Best; 881 switch (BestViableFunction(CandidateSet, Best)) { 882 case OR_Success: { 883 // We found a built-in operator or an overloaded operator. 884 FunctionDecl *FnDecl = Best->Function; 885 886 if (FnDecl) { 887 // We matched an overloaded operator. Build a call to that 888 // operator. 889 890 // Convert the arguments. 891 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 892 if (PerformObjectArgumentInitialization(LHSExp, Method) || 893 PerformCopyInitialization(RHSExp, 894 FnDecl->getParamDecl(0)->getType(), 895 "passing")) 896 return true; 897 } else { 898 // Convert the arguments. 899 if (PerformCopyInitialization(LHSExp, 900 FnDecl->getParamDecl(0)->getType(), 901 "passing") || 902 PerformCopyInitialization(RHSExp, 903 FnDecl->getParamDecl(1)->getType(), 904 "passing")) 905 return true; 906 } 907 908 // Determine the result type 909 QualType ResultTy 910 = FnDecl->getType()->getAsFunctionType()->getResultType(); 911 ResultTy = ResultTy.getNonReferenceType(); 912 913 // Build the actual expression node. 914 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(), 915 SourceLocation()); 916 UsualUnaryConversions(FnExpr); 917 918 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, LLoc); 919 } else { 920 // We matched a built-in operator. Convert the arguments, then 921 // break out so that we will build the appropriate built-in 922 // operator node. 923 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0], 924 "passing") || 925 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1], 926 "passing")) 927 return true; 928 929 break; 930 } 931 } 932 933 case OR_No_Viable_Function: 934 // No viable function; fall through to handling this as a 935 // built-in operator, which will produce an error message for us. 936 break; 937 938 case OR_Ambiguous: 939 Diag(LLoc, diag::err_ovl_ambiguous_oper) 940 << "[]" 941 << LHSExp->getSourceRange() << RHSExp->getSourceRange(); 942 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 943 return true; 944 } 945 946 // Either we found no viable overloaded operator or we matched a 947 // built-in operator. In either case, fall through to trying to 948 // build a built-in operation. 949 } 950 951 // Perform default conversions. 952 DefaultFunctionArrayConversion(LHSExp); 953 DefaultFunctionArrayConversion(RHSExp); 954 955 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 956 957 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 958 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 959 // in the subscript position. As a result, we need to derive the array base 960 // and index from the expression types. 961 Expr *BaseExpr, *IndexExpr; 962 QualType ResultType; 963 if (const PointerType *PTy = LHSTy->getAsPointerType()) { 964 BaseExpr = LHSExp; 965 IndexExpr = RHSExp; 966 // FIXME: need to deal with const... 967 ResultType = PTy->getPointeeType(); 968 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) { 969 // Handle the uncommon case of "123[Ptr]". 970 BaseExpr = RHSExp; 971 IndexExpr = LHSExp; 972 // FIXME: need to deal with const... 973 ResultType = PTy->getPointeeType(); 974 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) { 975 BaseExpr = LHSExp; // vectors: V[123] 976 IndexExpr = RHSExp; 977 978 // Component access limited to variables (reject vec4.rg[1]). 979 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) && 980 !isa<ExtVectorElementExpr>(BaseExpr)) 981 return Diag(LLoc, diag::err_ext_vector_component_access) 982 << SourceRange(LLoc, RLoc); 983 // FIXME: need to deal with const... 984 ResultType = VTy->getElementType(); 985 } else { 986 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value) 987 << RHSExp->getSourceRange(); 988 } 989 // C99 6.5.2.1p1 990 if (!IndexExpr->getType()->isIntegerType()) 991 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript) 992 << IndexExpr->getSourceRange(); 993 994 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice, 995 // the following check catches trying to index a pointer to a function (e.g. 996 // void (*)(int)) and pointers to incomplete types. Functions are not 997 // objects in C99. 998 if (!ResultType->isObjectType()) 999 return Diag(BaseExpr->getLocStart(), 1000 diag::err_typecheck_subscript_not_object) 1001 << BaseExpr->getType().getAsString() << BaseExpr->getSourceRange(); 1002 1003 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc); 1004} 1005 1006QualType Sema:: 1007CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc, 1008 IdentifierInfo &CompName, SourceLocation CompLoc) { 1009 const ExtVectorType *vecType = baseType->getAsExtVectorType(); 1010 1011 // This flag determines whether or not the component is to be treated as a 1012 // special name, or a regular GLSL-style component access. 1013 bool SpecialComponent = false; 1014 1015 // The vector accessor can't exceed the number of elements. 1016 const char *compStr = CompName.getName(); 1017 if (strlen(compStr) > vecType->getNumElements()) { 1018 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length) 1019 << baseType.getAsString() << SourceRange(CompLoc); 1020 return QualType(); 1021 } 1022 1023 // Check that we've found one of the special components, or that the component 1024 // names must come from the same set. 1025 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") || 1026 !strcmp(compStr, "e") || !strcmp(compStr, "o")) { 1027 SpecialComponent = true; 1028 } else if (vecType->getPointAccessorIdx(*compStr) != -1) { 1029 do 1030 compStr++; 1031 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1); 1032 } else if (vecType->getColorAccessorIdx(*compStr) != -1) { 1033 do 1034 compStr++; 1035 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1); 1036 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) { 1037 do 1038 compStr++; 1039 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1); 1040 } 1041 1042 if (!SpecialComponent && *compStr) { 1043 // We didn't get to the end of the string. This means the component names 1044 // didn't come from the same set *or* we encountered an illegal name. 1045 Diag(OpLoc, diag::err_ext_vector_component_name_illegal) 1046 << std::string(compStr,compStr+1) << SourceRange(CompLoc); 1047 return QualType(); 1048 } 1049 // Each component accessor can't exceed the vector type. 1050 compStr = CompName.getName(); 1051 while (*compStr) { 1052 if (vecType->isAccessorWithinNumElements(*compStr)) 1053 compStr++; 1054 else 1055 break; 1056 } 1057 if (!SpecialComponent && *compStr) { 1058 // We didn't get to the end of the string. This means a component accessor 1059 // exceeds the number of elements in the vector. 1060 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length) 1061 << baseType.getAsString() << SourceRange(CompLoc); 1062 return QualType(); 1063 } 1064 1065 // If we have a special component name, verify that the current vector length 1066 // is an even number, since all special component names return exactly half 1067 // the elements. 1068 if (SpecialComponent && (vecType->getNumElements() & 1U)) { 1069 Diag(OpLoc, diag::err_ext_vector_component_requires_even) 1070 << baseType.getAsString() << SourceRange(CompLoc); 1071 return QualType(); 1072 } 1073 1074 // The component accessor looks fine - now we need to compute the actual type. 1075 // The vector type is implied by the component accessor. For example, 1076 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc. 1077 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2. 1078 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2 1079 : CompName.getLength(); 1080 if (CompSize == 1) 1081 return vecType->getElementType(); 1082 1083 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize); 1084 // Now look up the TypeDefDecl from the vector type. Without this, 1085 // diagostics look bad. We want extended vector types to appear built-in. 1086 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) { 1087 if (ExtVectorDecls[i]->getUnderlyingType() == VT) 1088 return Context.getTypedefType(ExtVectorDecls[i]); 1089 } 1090 return VT; // should never get here (a typedef type should always be found). 1091} 1092 1093/// constructSetterName - Return the setter name for the given 1094/// identifier, i.e. "set" + Name where the initial character of Name 1095/// has been capitalized. 1096// FIXME: Merge with same routine in Parser. But where should this 1097// live? 1098static IdentifierInfo *constructSetterName(IdentifierTable &Idents, 1099 const IdentifierInfo *Name) { 1100 llvm::SmallString<100> SelectorName; 1101 SelectorName = "set"; 1102 SelectorName.append(Name->getName(), Name->getName()+Name->getLength()); 1103 SelectorName[3] = toupper(SelectorName[3]); 1104 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]); 1105} 1106 1107Action::ExprResult Sema:: 1108ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc, 1109 tok::TokenKind OpKind, SourceLocation MemberLoc, 1110 IdentifierInfo &Member) { 1111 Expr *BaseExpr = static_cast<Expr *>(Base); 1112 assert(BaseExpr && "no record expression"); 1113 1114 // Perform default conversions. 1115 DefaultFunctionArrayConversion(BaseExpr); 1116 1117 QualType BaseType = BaseExpr->getType(); 1118 assert(!BaseType.isNull() && "no type for member expression"); 1119 1120 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr 1121 // must have pointer type, and the accessed type is the pointee. 1122 if (OpKind == tok::arrow) { 1123 if (const PointerType *PT = BaseType->getAsPointerType()) 1124 BaseType = PT->getPointeeType(); 1125 else if (getLangOptions().CPlusPlus && BaseType->isRecordType()) 1126 return BuildOverloadedArrowExpr(BaseExpr, OpLoc, MemberLoc, Member); 1127 else 1128 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow) 1129 << BaseType.getAsString() << BaseExpr->getSourceRange(); 1130 } 1131 1132 // Handle field access to simple records. This also handles access to fields 1133 // of the ObjC 'id' struct. 1134 if (const RecordType *RTy = BaseType->getAsRecordType()) { 1135 RecordDecl *RDecl = RTy->getDecl(); 1136 if (RTy->isIncompleteType()) 1137 return Diag(OpLoc, diag::err_typecheck_incomplete_tag) 1138 << RDecl->getName() << BaseExpr->getSourceRange(); 1139 // The record definition is complete, now make sure the member is valid. 1140 FieldDecl *MemberDecl = RDecl->getMember(&Member); 1141 if (!MemberDecl) 1142 return Diag(MemberLoc, diag::err_typecheck_no_member) 1143 << &Member << BaseExpr->getSourceRange(); 1144 1145 // Figure out the type of the member; see C99 6.5.2.3p3 1146 // FIXME: Handle address space modifiers 1147 QualType MemberType = MemberDecl->getType(); 1148 unsigned combinedQualifiers = 1149 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers(); 1150 if (CXXFieldDecl *CXXMember = dyn_cast<CXXFieldDecl>(MemberDecl)) { 1151 if (CXXMember->isMutable()) 1152 combinedQualifiers &= ~QualType::Const; 1153 } 1154 MemberType = MemberType.getQualifiedType(combinedQualifiers); 1155 1156 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl, 1157 MemberLoc, MemberType); 1158 } 1159 1160 // Handle access to Objective-C instance variables, such as "Obj->ivar" and 1161 // (*Obj).ivar. 1162 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) { 1163 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) 1164 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr, 1165 OpKind == tok::arrow); 1166 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar) 1167 << IFTy->getDecl()->getName() << &Member 1168 << BaseExpr->getSourceRange(); 1169 } 1170 1171 // Handle Objective-C property access, which is "Obj.property" where Obj is a 1172 // pointer to a (potentially qualified) interface type. 1173 const PointerType *PTy; 1174 const ObjCInterfaceType *IFTy; 1175 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) && 1176 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) { 1177 ObjCInterfaceDecl *IFace = IFTy->getDecl(); 1178 1179 // Search for a declared property first. 1180 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) 1181 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr); 1182 1183 // Check protocols on qualified interfaces. 1184 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(), 1185 E = IFTy->qual_end(); I != E; ++I) 1186 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) 1187 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr); 1188 1189 // If that failed, look for an "implicit" property by seeing if the nullary 1190 // selector is implemented. 1191 1192 // FIXME: The logic for looking up nullary and unary selectors should be 1193 // shared with the code in ActOnInstanceMessage. 1194 1195 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member); 1196 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel); 1197 1198 // If this reference is in an @implementation, check for 'private' methods. 1199 if (!Getter) 1200 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) 1201 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) 1202 if (ObjCImplementationDecl *ImpDecl = 1203 ObjCImplementations[ClassDecl->getIdentifier()]) 1204 Getter = ImpDecl->getInstanceMethod(Sel); 1205 1206 // Look through local category implementations associated with the class. 1207 if (!Getter) { 1208 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) { 1209 if (ObjCCategoryImpls[i]->getClassInterface() == IFace) 1210 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel); 1211 } 1212 } 1213 if (Getter) { 1214 // If we found a getter then this may be a valid dot-reference, we 1215 // need to also look for the matching setter. 1216 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(), 1217 &Member); 1218 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName); 1219 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel); 1220 1221 if (!Setter) { 1222 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) 1223 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) 1224 if (ObjCImplementationDecl *ImpDecl = 1225 ObjCImplementations[ClassDecl->getIdentifier()]) 1226 Setter = ImpDecl->getInstanceMethod(SetterSel); 1227 } 1228 1229 // FIXME: There are some issues here. First, we are not 1230 // diagnosing accesses to read-only properties because we do not 1231 // know if this is a getter or setter yet. Second, we are 1232 // checking that the type of the setter matches the type we 1233 // expect. 1234 return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(), 1235 MemberLoc, BaseExpr); 1236 } 1237 } 1238 // Handle properties on qualified "id" protocols. 1239 const ObjCQualifiedIdType *QIdTy; 1240 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) { 1241 // Check protocols on qualified interfaces. 1242 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(), 1243 E = QIdTy->qual_end(); I != E; ++I) 1244 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) 1245 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr); 1246 } 1247 // Handle 'field access' to vectors, such as 'V.xx'. 1248 if (BaseType->isExtVectorType() && OpKind == tok::period) { 1249 // Component access limited to variables (reject vec4.rg.g). 1250 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) && 1251 !isa<ExtVectorElementExpr>(BaseExpr)) 1252 return Diag(MemberLoc, diag::err_ext_vector_component_access) 1253 << BaseExpr->getSourceRange(); 1254 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc); 1255 if (ret.isNull()) 1256 return true; 1257 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc); 1258 } 1259 1260 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union) 1261 << BaseType.getAsString() << BaseExpr->getSourceRange(); 1262} 1263 1264/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 1265/// This provides the location of the left/right parens and a list of comma 1266/// locations. 1267Action::ExprResult Sema:: 1268ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc, 1269 ExprTy **args, unsigned NumArgs, 1270 SourceLocation *CommaLocs, SourceLocation RParenLoc) { 1271 Expr *Fn = static_cast<Expr *>(fn); 1272 Expr **Args = reinterpret_cast<Expr**>(args); 1273 assert(Fn && "no function call expression"); 1274 FunctionDecl *FDecl = NULL; 1275 OverloadedFunctionDecl *Ovl = NULL; 1276 1277 // If we're directly calling a function or a set of overloaded 1278 // functions, get the appropriate declaration. 1279 { 1280 DeclRefExpr *DRExpr = NULL; 1281 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn)) 1282 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()); 1283 else 1284 DRExpr = dyn_cast<DeclRefExpr>(Fn); 1285 1286 if (DRExpr) { 1287 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()); 1288 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl()); 1289 } 1290 } 1291 1292 // If we have a set of overloaded functions, perform overload 1293 // resolution to pick the function. 1294 if (Ovl) { 1295 OverloadCandidateSet CandidateSet; 1296 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet); 1297 OverloadCandidateSet::iterator Best; 1298 switch (BestViableFunction(CandidateSet, Best)) { 1299 case OR_Success: 1300 { 1301 // Success! Let the remainder of this function build a call to 1302 // the function selected by overload resolution. 1303 FDecl = Best->Function; 1304 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(), 1305 Fn->getSourceRange().getBegin()); 1306 delete Fn; 1307 Fn = NewFn; 1308 } 1309 break; 1310 1311 case OR_No_Viable_Function: 1312 if (CandidateSet.empty()) 1313 Diag(Fn->getSourceRange().getBegin(), 1314 diag::err_ovl_no_viable_function_in_call) 1315 << Ovl->getName() << Fn->getSourceRange(); 1316 else { 1317 Diag(Fn->getSourceRange().getBegin(), 1318 diag::err_ovl_no_viable_function_in_call_with_cands) 1319 << Ovl->getName() << Fn->getSourceRange(); 1320 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 1321 } 1322 return true; 1323 1324 case OR_Ambiguous: 1325 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call) 1326 << Ovl->getName() << Fn->getSourceRange(); 1327 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 1328 return true; 1329 } 1330 } 1331 1332 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType()) 1333 return BuildCallToObjectOfClassType(Fn, LParenLoc, Args, NumArgs, 1334 CommaLocs, RParenLoc); 1335 1336 // Promote the function operand. 1337 UsualUnaryConversions(Fn); 1338 1339 // Make the call expr early, before semantic checks. This guarantees cleanup 1340 // of arguments and function on error. 1341 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs, 1342 Context.BoolTy, RParenLoc)); 1343 const FunctionType *FuncT; 1344 if (!Fn->getType()->isBlockPointerType()) { 1345 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 1346 // have type pointer to function". 1347 const PointerType *PT = Fn->getType()->getAsPointerType(); 1348 if (PT == 0) 1349 return Diag(LParenLoc, diag::err_typecheck_call_not_function) 1350 << Fn->getSourceRange(); 1351 FuncT = PT->getPointeeType()->getAsFunctionType(); 1352 } else { // This is a block call. 1353 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()-> 1354 getAsFunctionType(); 1355 } 1356 if (FuncT == 0) 1357 return Diag(LParenLoc, diag::err_typecheck_call_not_function) 1358 << Fn->getSourceRange(); 1359 1360 // We know the result type of the call, set it. 1361 TheCall->setType(FuncT->getResultType().getNonReferenceType()); 1362 1363 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) { 1364 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 1365 // assignment, to the types of the corresponding parameter, ... 1366 unsigned NumArgsInProto = Proto->getNumArgs(); 1367 unsigned NumArgsToCheck = NumArgs; 1368 1369 // If too few arguments are available (and we don't have default 1370 // arguments for the remaining parameters), don't make the call. 1371 if (NumArgs < NumArgsInProto) { 1372 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) { 1373 // Use default arguments for missing arguments 1374 NumArgsToCheck = NumArgsInProto; 1375 TheCall->setNumArgs(NumArgsInProto); 1376 } else 1377 return Diag(RParenLoc, 1378 !Fn->getType()->isBlockPointerType() 1379 ? diag::err_typecheck_call_too_few_args 1380 : diag::err_typecheck_block_too_few_args) 1381 << Fn->getSourceRange(); 1382 } 1383 1384 // If too many are passed and not variadic, error on the extras and drop 1385 // them. 1386 if (NumArgs > NumArgsInProto) { 1387 if (!Proto->isVariadic()) { 1388 Diag(Args[NumArgsInProto]->getLocStart(), 1389 !Fn->getType()->isBlockPointerType() 1390 ? diag::err_typecheck_call_too_many_args 1391 : diag::err_typecheck_block_too_many_args) 1392 << Fn->getSourceRange() 1393 << SourceRange(Args[NumArgsInProto]->getLocStart(), 1394 Args[NumArgs-1]->getLocEnd()); 1395 // This deletes the extra arguments. 1396 TheCall->setNumArgs(NumArgsInProto); 1397 } 1398 NumArgsToCheck = NumArgsInProto; 1399 } 1400 1401 // Continue to check argument types (even if we have too few/many args). 1402 for (unsigned i = 0; i != NumArgsToCheck; i++) { 1403 QualType ProtoArgType = Proto->getArgType(i); 1404 1405 Expr *Arg; 1406 if (i < NumArgs) 1407 Arg = Args[i]; 1408 else 1409 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i)); 1410 QualType ArgType = Arg->getType(); 1411 1412 // Pass the argument. 1413 if (PerformCopyInitialization(Arg, ProtoArgType, "passing")) 1414 return true; 1415 1416 TheCall->setArg(i, Arg); 1417 } 1418 1419 // If this is a variadic call, handle args passed through "...". 1420 if (Proto->isVariadic()) { 1421 // Promote the arguments (C99 6.5.2.2p7). 1422 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 1423 Expr *Arg = Args[i]; 1424 DefaultArgumentPromotion(Arg); 1425 TheCall->setArg(i, Arg); 1426 } 1427 } 1428 } else { 1429 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!"); 1430 1431 // Promote the arguments (C99 6.5.2.2p6). 1432 for (unsigned i = 0; i != NumArgs; i++) { 1433 Expr *Arg = Args[i]; 1434 DefaultArgumentPromotion(Arg); 1435 TheCall->setArg(i, Arg); 1436 } 1437 } 1438 1439 // Do special checking on direct calls to functions. 1440 if (FDecl) 1441 return CheckFunctionCall(FDecl, TheCall.take()); 1442 1443 return TheCall.take(); 1444} 1445 1446Action::ExprResult Sema:: 1447ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty, 1448 SourceLocation RParenLoc, ExprTy *InitExpr) { 1449 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type"); 1450 QualType literalType = QualType::getFromOpaquePtr(Ty); 1451 // FIXME: put back this assert when initializers are worked out. 1452 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 1453 Expr *literalExpr = static_cast<Expr*>(InitExpr); 1454 1455 if (literalType->isArrayType()) { 1456 if (literalType->isVariableArrayType()) 1457 return Diag(LParenLoc, diag::err_variable_object_no_init) 1458 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()); 1459 } else if (literalType->isIncompleteType()) { 1460 return Diag(LParenLoc, diag::err_typecheck_decl_incomplete_type) 1461 << literalType.getAsString() 1462 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()); 1463 } 1464 1465 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc, 1466 "temporary")) 1467 return true; 1468 1469 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl(); 1470 if (isFileScope) { // 6.5.2.5p3 1471 if (CheckForConstantInitializer(literalExpr, literalType)) 1472 return true; 1473 } 1474 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, 1475 isFileScope); 1476} 1477 1478Action::ExprResult Sema:: 1479ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit, 1480 InitListDesignations &Designators, 1481 SourceLocation RBraceLoc) { 1482 Expr **InitList = reinterpret_cast<Expr**>(initlist); 1483 1484 // Semantic analysis for initializers is done by ActOnDeclarator() and 1485 // CheckInitializer() - it requires knowledge of the object being intialized. 1486 1487 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc, 1488 Designators.hasAnyDesignators()); 1489 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 1490 return E; 1491} 1492 1493/// CheckCastTypes - Check type constraints for casting between types. 1494bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) { 1495 UsualUnaryConversions(castExpr); 1496 1497 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression 1498 // type needs to be scalar. 1499 if (castType->isVoidType()) { 1500 // Cast to void allows any expr type. 1501 } else if (!castType->isScalarType() && !castType->isVectorType()) { 1502 // GCC struct/union extension: allow cast to self. 1503 if (Context.getCanonicalType(castType) != 1504 Context.getCanonicalType(castExpr->getType()) || 1505 (!castType->isStructureType() && !castType->isUnionType())) { 1506 // Reject any other conversions to non-scalar types. 1507 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar) 1508 << castType.getAsString() << castExpr->getSourceRange(); 1509 } 1510 1511 // accept this, but emit an ext-warn. 1512 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar) 1513 << castType.getAsString() << castExpr->getSourceRange(); 1514 } else if (!castExpr->getType()->isScalarType() && 1515 !castExpr->getType()->isVectorType()) { 1516 return Diag(castExpr->getLocStart(), 1517 diag::err_typecheck_expect_scalar_operand) 1518 << castExpr->getType().getAsString() << castExpr->getSourceRange(); 1519 } else if (castExpr->getType()->isVectorType()) { 1520 if (CheckVectorCast(TyR, castExpr->getType(), castType)) 1521 return true; 1522 } else if (castType->isVectorType()) { 1523 if (CheckVectorCast(TyR, castType, castExpr->getType())) 1524 return true; 1525 } 1526 return false; 1527} 1528 1529bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) { 1530 assert(VectorTy->isVectorType() && "Not a vector type!"); 1531 1532 if (Ty->isVectorType() || Ty->isIntegerType()) { 1533 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 1534 return Diag(R.getBegin(), 1535 Ty->isVectorType() ? 1536 diag::err_invalid_conversion_between_vectors : 1537 diag::err_invalid_conversion_between_vector_and_integer) 1538 << VectorTy.getAsString() << Ty.getAsString() << R; 1539 } else 1540 return Diag(R.getBegin(), 1541 diag::err_invalid_conversion_between_vector_and_scalar) 1542 << VectorTy.getAsString() << Ty.getAsString() << R; 1543 1544 return false; 1545} 1546 1547Action::ExprResult Sema:: 1548ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty, 1549 SourceLocation RParenLoc, ExprTy *Op) { 1550 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr"); 1551 1552 Expr *castExpr = static_cast<Expr*>(Op); 1553 QualType castType = QualType::getFromOpaquePtr(Ty); 1554 1555 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr)) 1556 return true; 1557 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc); 1558} 1559 1560/// Note that lex is not null here, even if this is the gnu "x ?: y" extension. 1561/// In that case, lex = cond. 1562inline QualType Sema::CheckConditionalOperands( // C99 6.5.15 1563 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) { 1564 UsualUnaryConversions(cond); 1565 UsualUnaryConversions(lex); 1566 UsualUnaryConversions(rex); 1567 QualType condT = cond->getType(); 1568 QualType lexT = lex->getType(); 1569 QualType rexT = rex->getType(); 1570 1571 // first, check the condition. 1572 if (!condT->isScalarType()) { // C99 6.5.15p2 1573 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) 1574 << condT.getAsString(); 1575 return QualType(); 1576 } 1577 1578 // Now check the two expressions. 1579 1580 // If both operands have arithmetic type, do the usual arithmetic conversions 1581 // to find a common type: C99 6.5.15p3,5. 1582 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { 1583 UsualArithmeticConversions(lex, rex); 1584 return lex->getType(); 1585 } 1586 1587 // If both operands are the same structure or union type, the result is that 1588 // type. 1589 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3 1590 if (const RecordType *RHSRT = rexT->getAsRecordType()) 1591 if (LHSRT->getDecl() == RHSRT->getDecl()) 1592 // "If both the operands have structure or union type, the result has 1593 // that type." This implies that CV qualifiers are dropped. 1594 return lexT.getUnqualifiedType(); 1595 } 1596 1597 // C99 6.5.15p5: "If both operands have void type, the result has void type." 1598 // The following || allows only one side to be void (a GCC-ism). 1599 if (lexT->isVoidType() || rexT->isVoidType()) { 1600 if (!lexT->isVoidType()) 1601 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void) 1602 << rex->getSourceRange(); 1603 if (!rexT->isVoidType()) 1604 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void) 1605 << lex->getSourceRange(); 1606 ImpCastExprToType(lex, Context.VoidTy); 1607 ImpCastExprToType(rex, Context.VoidTy); 1608 return Context.VoidTy; 1609 } 1610 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 1611 // the type of the other operand." 1612 if ((lexT->isPointerType() || lexT->isBlockPointerType() || 1613 Context.isObjCObjectPointerType(lexT)) && 1614 rex->isNullPointerConstant(Context)) { 1615 ImpCastExprToType(rex, lexT); // promote the null to a pointer. 1616 return lexT; 1617 } 1618 if ((rexT->isPointerType() || rexT->isBlockPointerType() || 1619 Context.isObjCObjectPointerType(rexT)) && 1620 lex->isNullPointerConstant(Context)) { 1621 ImpCastExprToType(lex, rexT); // promote the null to a pointer. 1622 return rexT; 1623 } 1624 // Handle the case where both operands are pointers before we handle null 1625 // pointer constants in case both operands are null pointer constants. 1626 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6 1627 if (const PointerType *RHSPT = rexT->getAsPointerType()) { 1628 // get the "pointed to" types 1629 QualType lhptee = LHSPT->getPointeeType(); 1630 QualType rhptee = RHSPT->getPointeeType(); 1631 1632 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 1633 if (lhptee->isVoidType() && 1634 rhptee->isIncompleteOrObjectType()) { 1635 // Figure out necessary qualifiers (C99 6.5.15p6) 1636 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers()); 1637 QualType destType = Context.getPointerType(destPointee); 1638 ImpCastExprToType(lex, destType); // add qualifiers if necessary 1639 ImpCastExprToType(rex, destType); // promote to void* 1640 return destType; 1641 } 1642 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 1643 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers()); 1644 QualType destType = Context.getPointerType(destPointee); 1645 ImpCastExprToType(lex, destType); // add qualifiers if necessary 1646 ImpCastExprToType(rex, destType); // promote to void* 1647 return destType; 1648 } 1649 1650 QualType compositeType = lexT; 1651 1652 // If either type is an Objective-C object type then check 1653 // compatibility according to Objective-C. 1654 if (Context.isObjCObjectPointerType(lexT) || 1655 Context.isObjCObjectPointerType(rexT)) { 1656 // If both operands are interfaces and either operand can be 1657 // assigned to the other, use that type as the composite 1658 // type. This allows 1659 // xxx ? (A*) a : (B*) b 1660 // where B is a subclass of A. 1661 // 1662 // Additionally, as for assignment, if either type is 'id' 1663 // allow silent coercion. Finally, if the types are 1664 // incompatible then make sure to use 'id' as the composite 1665 // type so the result is acceptable for sending messages to. 1666 1667 // FIXME: This code should not be localized to here. Also this 1668 // should use a compatible check instead of abusing the 1669 // canAssignObjCInterfaces code. 1670 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType(); 1671 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType(); 1672 if (LHSIface && RHSIface && 1673 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) { 1674 compositeType = lexT; 1675 } else if (LHSIface && RHSIface && 1676 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) { 1677 compositeType = rexT; 1678 } else if (Context.isObjCIdType(lhptee) || 1679 Context.isObjCIdType(rhptee)) { 1680 // FIXME: This code looks wrong, because isObjCIdType checks 1681 // the struct but getObjCIdType returns the pointer to 1682 // struct. This is horrible and should be fixed. 1683 compositeType = Context.getObjCIdType(); 1684 } else { 1685 QualType incompatTy = Context.getObjCIdType(); 1686 ImpCastExprToType(lex, incompatTy); 1687 ImpCastExprToType(rex, incompatTy); 1688 return incompatTy; 1689 } 1690 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 1691 rhptee.getUnqualifiedType())) { 1692 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers) 1693 << lexT.getAsString() << rexT.getAsString() 1694 << lex->getSourceRange() << rex->getSourceRange(); 1695 // In this situation, we assume void* type. No especially good 1696 // reason, but this is what gcc does, and we do have to pick 1697 // to get a consistent AST. 1698 QualType incompatTy = Context.getPointerType(Context.VoidTy); 1699 ImpCastExprToType(lex, incompatTy); 1700 ImpCastExprToType(rex, incompatTy); 1701 return incompatTy; 1702 } 1703 // The pointer types are compatible. 1704 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to 1705 // differently qualified versions of compatible types, the result type is 1706 // a pointer to an appropriately qualified version of the *composite* 1707 // type. 1708 // FIXME: Need to calculate the composite type. 1709 // FIXME: Need to add qualifiers 1710 ImpCastExprToType(lex, compositeType); 1711 ImpCastExprToType(rex, compositeType); 1712 return compositeType; 1713 } 1714 } 1715 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type 1716 // evaluates to "struct objc_object *" (and is handled above when comparing 1717 // id with statically typed objects). 1718 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) { 1719 // GCC allows qualified id and any Objective-C type to devolve to 1720 // id. Currently localizing to here until clear this should be 1721 // part of ObjCQualifiedIdTypesAreCompatible. 1722 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) || 1723 (lexT->isObjCQualifiedIdType() && 1724 Context.isObjCObjectPointerType(rexT)) || 1725 (rexT->isObjCQualifiedIdType() && 1726 Context.isObjCObjectPointerType(lexT))) { 1727 // FIXME: This is not the correct composite type. This only 1728 // happens to work because id can more or less be used anywhere, 1729 // however this may change the type of method sends. 1730 // FIXME: gcc adds some type-checking of the arguments and emits 1731 // (confusing) incompatible comparison warnings in some 1732 // cases. Investigate. 1733 QualType compositeType = Context.getObjCIdType(); 1734 ImpCastExprToType(lex, compositeType); 1735 ImpCastExprToType(rex, compositeType); 1736 return compositeType; 1737 } 1738 } 1739 1740 // Selection between block pointer types is ok as long as they are the same. 1741 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() && 1742 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT)) 1743 return lexT; 1744 1745 // Otherwise, the operands are not compatible. 1746 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands) 1747 << lexT.getAsString() << rexT.getAsString() 1748 << lex->getSourceRange() << rex->getSourceRange(); 1749 return QualType(); 1750} 1751 1752/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 1753/// in the case of a the GNU conditional expr extension. 1754Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 1755 SourceLocation ColonLoc, 1756 ExprTy *Cond, ExprTy *LHS, 1757 ExprTy *RHS) { 1758 Expr *CondExpr = (Expr *) Cond; 1759 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS; 1760 1761 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 1762 // was the condition. 1763 bool isLHSNull = LHSExpr == 0; 1764 if (isLHSNull) 1765 LHSExpr = CondExpr; 1766 1767 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, 1768 RHSExpr, QuestionLoc); 1769 if (result.isNull()) 1770 return true; 1771 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr, 1772 RHSExpr, result); 1773} 1774 1775 1776// CheckPointerTypesForAssignment - This is a very tricky routine (despite 1777// being closely modeled after the C99 spec:-). The odd characteristic of this 1778// routine is it effectively iqnores the qualifiers on the top level pointee. 1779// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 1780// FIXME: add a couple examples in this comment. 1781Sema::AssignConvertType 1782Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) { 1783 QualType lhptee, rhptee; 1784 1785 // get the "pointed to" type (ignoring qualifiers at the top level) 1786 lhptee = lhsType->getAsPointerType()->getPointeeType(); 1787 rhptee = rhsType->getAsPointerType()->getPointeeType(); 1788 1789 // make sure we operate on the canonical type 1790 lhptee = Context.getCanonicalType(lhptee); 1791 rhptee = Context.getCanonicalType(rhptee); 1792 1793 AssignConvertType ConvTy = Compatible; 1794 1795 // C99 6.5.16.1p1: This following citation is common to constraints 1796 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 1797 // qualifiers of the type *pointed to* by the right; 1798 // FIXME: Handle ASQualType 1799 if (!lhptee.isAtLeastAsQualifiedAs(rhptee)) 1800 ConvTy = CompatiblePointerDiscardsQualifiers; 1801 1802 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 1803 // incomplete type and the other is a pointer to a qualified or unqualified 1804 // version of void... 1805 if (lhptee->isVoidType()) { 1806 if (rhptee->isIncompleteOrObjectType()) 1807 return ConvTy; 1808 1809 // As an extension, we allow cast to/from void* to function pointer. 1810 assert(rhptee->isFunctionType()); 1811 return FunctionVoidPointer; 1812 } 1813 1814 if (rhptee->isVoidType()) { 1815 if (lhptee->isIncompleteOrObjectType()) 1816 return ConvTy; 1817 1818 // As an extension, we allow cast to/from void* to function pointer. 1819 assert(lhptee->isFunctionType()); 1820 return FunctionVoidPointer; 1821 } 1822 1823 // Check for ObjC interfaces 1824 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType(); 1825 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType(); 1826 if (LHSIface && RHSIface && 1827 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) 1828 return ConvTy; 1829 1830 // ID acts sort of like void* for ObjC interfaces 1831 if (LHSIface && Context.isObjCIdType(rhptee)) 1832 return ConvTy; 1833 if (RHSIface && Context.isObjCIdType(lhptee)) 1834 return ConvTy; 1835 1836 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 1837 // unqualified versions of compatible types, ... 1838 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 1839 rhptee.getUnqualifiedType())) 1840 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers 1841 return ConvTy; 1842} 1843 1844/// CheckBlockPointerTypesForAssignment - This routine determines whether two 1845/// block pointer types are compatible or whether a block and normal pointer 1846/// are compatible. It is more restrict than comparing two function pointer 1847// types. 1848Sema::AssignConvertType 1849Sema::CheckBlockPointerTypesForAssignment(QualType lhsType, 1850 QualType rhsType) { 1851 QualType lhptee, rhptee; 1852 1853 // get the "pointed to" type (ignoring qualifiers at the top level) 1854 lhptee = lhsType->getAsBlockPointerType()->getPointeeType(); 1855 rhptee = rhsType->getAsBlockPointerType()->getPointeeType(); 1856 1857 // make sure we operate on the canonical type 1858 lhptee = Context.getCanonicalType(lhptee); 1859 rhptee = Context.getCanonicalType(rhptee); 1860 1861 AssignConvertType ConvTy = Compatible; 1862 1863 // For blocks we enforce that qualifiers are identical. 1864 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers()) 1865 ConvTy = CompatiblePointerDiscardsQualifiers; 1866 1867 if (!Context.typesAreBlockCompatible(lhptee, rhptee)) 1868 return IncompatibleBlockPointer; 1869 return ConvTy; 1870} 1871 1872/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 1873/// has code to accommodate several GCC extensions when type checking 1874/// pointers. Here are some objectionable examples that GCC considers warnings: 1875/// 1876/// int a, *pint; 1877/// short *pshort; 1878/// struct foo *pfoo; 1879/// 1880/// pint = pshort; // warning: assignment from incompatible pointer type 1881/// a = pint; // warning: assignment makes integer from pointer without a cast 1882/// pint = a; // warning: assignment makes pointer from integer without a cast 1883/// pint = pfoo; // warning: assignment from incompatible pointer type 1884/// 1885/// As a result, the code for dealing with pointers is more complex than the 1886/// C99 spec dictates. 1887/// 1888Sema::AssignConvertType 1889Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) { 1890 // Get canonical types. We're not formatting these types, just comparing 1891 // them. 1892 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType(); 1893 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType(); 1894 1895 if (lhsType == rhsType) 1896 return Compatible; // Common case: fast path an exact match. 1897 1898 // If the left-hand side is a reference type, then we are in a 1899 // (rare!) case where we've allowed the use of references in C, 1900 // e.g., as a parameter type in a built-in function. In this case, 1901 // just make sure that the type referenced is compatible with the 1902 // right-hand side type. The caller is responsible for adjusting 1903 // lhsType so that the resulting expression does not have reference 1904 // type. 1905 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) { 1906 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) 1907 return Compatible; 1908 return Incompatible; 1909 } 1910 1911 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) { 1912 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false)) 1913 return Compatible; 1914 // Relax integer conversions like we do for pointers below. 1915 if (rhsType->isIntegerType()) 1916 return IntToPointer; 1917 if (lhsType->isIntegerType()) 1918 return PointerToInt; 1919 return IncompatibleObjCQualifiedId; 1920 } 1921 1922 if (lhsType->isVectorType() || rhsType->isVectorType()) { 1923 // For ExtVector, allow vector splats; float -> <n x float> 1924 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) 1925 if (LV->getElementType() == rhsType) 1926 return Compatible; 1927 1928 // If we are allowing lax vector conversions, and LHS and RHS are both 1929 // vectors, the total size only needs to be the same. This is a bitcast; 1930 // no bits are changed but the result type is different. 1931 if (getLangOptions().LaxVectorConversions && 1932 lhsType->isVectorType() && rhsType->isVectorType()) { 1933 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) 1934 return Compatible; 1935 } 1936 return Incompatible; 1937 } 1938 1939 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) 1940 return Compatible; 1941 1942 if (isa<PointerType>(lhsType)) { 1943 if (rhsType->isIntegerType()) 1944 return IntToPointer; 1945 1946 if (isa<PointerType>(rhsType)) 1947 return CheckPointerTypesForAssignment(lhsType, rhsType); 1948 1949 if (rhsType->getAsBlockPointerType()) { 1950 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType()) 1951 return BlockVoidPointer; 1952 1953 // Treat block pointers as objects. 1954 if (getLangOptions().ObjC1 && 1955 lhsType == Context.getCanonicalType(Context.getObjCIdType())) 1956 return Compatible; 1957 } 1958 return Incompatible; 1959 } 1960 1961 if (isa<BlockPointerType>(lhsType)) { 1962 if (rhsType->isIntegerType()) 1963 return IntToPointer; 1964 1965 // Treat block pointers as objects. 1966 if (getLangOptions().ObjC1 && 1967 rhsType == Context.getCanonicalType(Context.getObjCIdType())) 1968 return Compatible; 1969 1970 if (rhsType->isBlockPointerType()) 1971 return CheckBlockPointerTypesForAssignment(lhsType, rhsType); 1972 1973 if (const PointerType *RHSPT = rhsType->getAsPointerType()) { 1974 if (RHSPT->getPointeeType()->isVoidType()) 1975 return BlockVoidPointer; 1976 } 1977 return Incompatible; 1978 } 1979 1980 if (isa<PointerType>(rhsType)) { 1981 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer. 1982 if (lhsType == Context.BoolTy) 1983 return Compatible; 1984 1985 if (lhsType->isIntegerType()) 1986 return PointerToInt; 1987 1988 if (isa<PointerType>(lhsType)) 1989 return CheckPointerTypesForAssignment(lhsType, rhsType); 1990 1991 if (isa<BlockPointerType>(lhsType) && 1992 rhsType->getAsPointerType()->getPointeeType()->isVoidType()) 1993 return BlockVoidPointer; 1994 return Incompatible; 1995 } 1996 1997 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) { 1998 if (Context.typesAreCompatible(lhsType, rhsType)) 1999 return Compatible; 2000 } 2001 return Incompatible; 2002} 2003 2004Sema::AssignConvertType 2005Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) { 2006 if (getLangOptions().CPlusPlus) { 2007 if (!lhsType->isRecordType()) { 2008 // C++ 5.17p3: If the left operand is not of class type, the 2009 // expression is implicitly converted (C++ 4) to the 2010 // cv-unqualified type of the left operand. 2011 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType())) 2012 return Incompatible; 2013 else 2014 return Compatible; 2015 } 2016 2017 // FIXME: Currently, we fall through and treat C++ classes like C 2018 // structures. 2019 } 2020 2021 // C99 6.5.16.1p1: the left operand is a pointer and the right is 2022 // a null pointer constant. 2023 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() || 2024 lhsType->isBlockPointerType()) 2025 && rExpr->isNullPointerConstant(Context)) { 2026 ImpCastExprToType(rExpr, lhsType); 2027 return Compatible; 2028 } 2029 2030 // We don't allow conversion of non-null-pointer constants to integers. 2031 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType()) 2032 return IntToBlockPointer; 2033 2034 // This check seems unnatural, however it is necessary to ensure the proper 2035 // conversion of functions/arrays. If the conversion were done for all 2036 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary 2037 // expressions that surpress this implicit conversion (&, sizeof). 2038 // 2039 // Suppress this for references: C++ 8.5.3p5. 2040 if (!lhsType->isReferenceType()) 2041 DefaultFunctionArrayConversion(rExpr); 2042 2043 Sema::AssignConvertType result = 2044 CheckAssignmentConstraints(lhsType, rExpr->getType()); 2045 2046 // C99 6.5.16.1p2: The value of the right operand is converted to the 2047 // type of the assignment expression. 2048 // CheckAssignmentConstraints allows the left-hand side to be a reference, 2049 // so that we can use references in built-in functions even in C. 2050 // The getNonReferenceType() call makes sure that the resulting expression 2051 // does not have reference type. 2052 if (rExpr->getType() != lhsType) 2053 ImpCastExprToType(rExpr, lhsType.getNonReferenceType()); 2054 return result; 2055} 2056 2057Sema::AssignConvertType 2058Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) { 2059 return CheckAssignmentConstraints(lhsType, rhsType); 2060} 2061 2062QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) { 2063 Diag(Loc, diag::err_typecheck_invalid_operands) 2064 << lex->getType().getAsString() << rex->getType().getAsString() 2065 << lex->getSourceRange() << rex->getSourceRange(); 2066 return QualType(); 2067} 2068 2069inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, 2070 Expr *&rex) { 2071 // For conversion purposes, we ignore any qualifiers. 2072 // For example, "const float" and "float" are equivalent. 2073 QualType lhsType = 2074 Context.getCanonicalType(lex->getType()).getUnqualifiedType(); 2075 QualType rhsType = 2076 Context.getCanonicalType(rex->getType()).getUnqualifiedType(); 2077 2078 // If the vector types are identical, return. 2079 if (lhsType == rhsType) 2080 return lhsType; 2081 2082 // Handle the case of a vector & extvector type of the same size and element 2083 // type. It would be nice if we only had one vector type someday. 2084 if (getLangOptions().LaxVectorConversions) 2085 if (const VectorType *LV = lhsType->getAsVectorType()) 2086 if (const VectorType *RV = rhsType->getAsVectorType()) 2087 if (LV->getElementType() == RV->getElementType() && 2088 LV->getNumElements() == RV->getNumElements()) 2089 return lhsType->isExtVectorType() ? lhsType : rhsType; 2090 2091 // If the lhs is an extended vector and the rhs is a scalar of the same type 2092 // or a literal, promote the rhs to the vector type. 2093 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) { 2094 QualType eltType = V->getElementType(); 2095 2096 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) || 2097 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) || 2098 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) { 2099 ImpCastExprToType(rex, lhsType); 2100 return lhsType; 2101 } 2102 } 2103 2104 // If the rhs is an extended vector and the lhs is a scalar of the same type, 2105 // promote the lhs to the vector type. 2106 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) { 2107 QualType eltType = V->getElementType(); 2108 2109 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) || 2110 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) || 2111 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) { 2112 ImpCastExprToType(lex, rhsType); 2113 return rhsType; 2114 } 2115 } 2116 2117 // You cannot convert between vector values of different size. 2118 Diag(Loc, diag::err_typecheck_vector_not_convertable) 2119 << lex->getType().getAsString() << rex->getType().getAsString() 2120 << lex->getSourceRange() << rex->getSourceRange(); 2121 return QualType(); 2122} 2123 2124inline QualType Sema::CheckMultiplyDivideOperands( 2125 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) 2126{ 2127 QualType lhsType = lex->getType(), rhsType = rex->getType(); 2128 2129 if (lhsType->isVectorType() || rhsType->isVectorType()) 2130 return CheckVectorOperands(Loc, lex, rex); 2131 2132 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 2133 2134 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 2135 return compType; 2136 return InvalidOperands(Loc, lex, rex); 2137} 2138 2139inline QualType Sema::CheckRemainderOperands( 2140 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) 2141{ 2142 QualType lhsType = lex->getType(), rhsType = rex->getType(); 2143 2144 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 2145 2146 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 2147 return compType; 2148 return InvalidOperands(Loc, lex, rex); 2149} 2150 2151inline QualType Sema::CheckAdditionOperands( // C99 6.5.6 2152 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) 2153{ 2154 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 2155 return CheckVectorOperands(Loc, lex, rex); 2156 2157 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 2158 2159 // handle the common case first (both operands are arithmetic). 2160 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 2161 return compType; 2162 2163 // Put any potential pointer into PExp 2164 Expr* PExp = lex, *IExp = rex; 2165 if (IExp->getType()->isPointerType()) 2166 std::swap(PExp, IExp); 2167 2168 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) { 2169 if (IExp->getType()->isIntegerType()) { 2170 // Check for arithmetic on pointers to incomplete types 2171 if (!PTy->getPointeeType()->isObjectType()) { 2172 if (PTy->getPointeeType()->isVoidType()) { 2173 Diag(Loc, diag::ext_gnu_void_ptr) 2174 << lex->getSourceRange() << rex->getSourceRange(); 2175 } else { 2176 Diag(Loc, diag::err_typecheck_arithmetic_incomplete_type) 2177 << lex->getType().getAsString() << lex->getSourceRange(); 2178 return QualType(); 2179 } 2180 } 2181 return PExp->getType(); 2182 } 2183 } 2184 2185 return InvalidOperands(Loc, lex, rex); 2186} 2187 2188// C99 6.5.6 2189QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex, 2190 SourceLocation Loc, bool isCompAssign) { 2191 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 2192 return CheckVectorOperands(Loc, lex, rex); 2193 2194 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 2195 2196 // Enforce type constraints: C99 6.5.6p3. 2197 2198 // Handle the common case first (both operands are arithmetic). 2199 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 2200 return compType; 2201 2202 // Either ptr - int or ptr - ptr. 2203 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) { 2204 QualType lpointee = LHSPTy->getPointeeType(); 2205 2206 // The LHS must be an object type, not incomplete, function, etc. 2207 if (!lpointee->isObjectType()) { 2208 // Handle the GNU void* extension. 2209 if (lpointee->isVoidType()) { 2210 Diag(Loc, diag::ext_gnu_void_ptr) 2211 << lex->getSourceRange() << rex->getSourceRange(); 2212 } else { 2213 Diag(Loc, diag::err_typecheck_sub_ptr_object) 2214 << lex->getType().getAsString() << lex->getSourceRange(); 2215 return QualType(); 2216 } 2217 } 2218 2219 // The result type of a pointer-int computation is the pointer type. 2220 if (rex->getType()->isIntegerType()) 2221 return lex->getType(); 2222 2223 // Handle pointer-pointer subtractions. 2224 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) { 2225 QualType rpointee = RHSPTy->getPointeeType(); 2226 2227 // RHS must be an object type, unless void (GNU). 2228 if (!rpointee->isObjectType()) { 2229 // Handle the GNU void* extension. 2230 if (rpointee->isVoidType()) { 2231 if (!lpointee->isVoidType()) 2232 Diag(Loc, diag::ext_gnu_void_ptr) 2233 << lex->getSourceRange() << rex->getSourceRange(); 2234 } else { 2235 Diag(Loc, diag::err_typecheck_sub_ptr_object) 2236 << rex->getType().getAsString() << rex->getSourceRange(); 2237 return QualType(); 2238 } 2239 } 2240 2241 // Pointee types must be compatible. 2242 if (!Context.typesAreCompatible( 2243 Context.getCanonicalType(lpointee).getUnqualifiedType(), 2244 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 2245 Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 2246 << lex->getType().getAsString() << rex->getType().getAsString() 2247 << lex->getSourceRange() << rex->getSourceRange(); 2248 return QualType(); 2249 } 2250 2251 return Context.getPointerDiffType(); 2252 } 2253 } 2254 2255 return InvalidOperands(Loc, lex, rex); 2256} 2257 2258// C99 6.5.7 2259QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, 2260 bool isCompAssign) { 2261 // C99 6.5.7p2: Each of the operands shall have integer type. 2262 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType()) 2263 return InvalidOperands(Loc, lex, rex); 2264 2265 // Shifts don't perform usual arithmetic conversions, they just do integer 2266 // promotions on each operand. C99 6.5.7p3 2267 if (!isCompAssign) 2268 UsualUnaryConversions(lex); 2269 UsualUnaryConversions(rex); 2270 2271 // "The type of the result is that of the promoted left operand." 2272 return lex->getType(); 2273} 2274 2275static bool areComparableObjCInterfaces(QualType LHS, QualType RHS, 2276 ASTContext& Context) { 2277 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType(); 2278 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType(); 2279 // ID acts sort of like void* for ObjC interfaces 2280 if (LHSIface && Context.isObjCIdType(RHS)) 2281 return true; 2282 if (RHSIface && Context.isObjCIdType(LHS)) 2283 return true; 2284 if (!LHSIface || !RHSIface) 2285 return false; 2286 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) || 2287 Context.canAssignObjCInterfaces(RHSIface, LHSIface); 2288} 2289 2290// C99 6.5.8 2291QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc, 2292 bool isRelational) { 2293 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 2294 return CheckVectorCompareOperands(lex, rex, Loc, isRelational); 2295 2296 // C99 6.5.8p3 / C99 6.5.9p4 2297 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 2298 UsualArithmeticConversions(lex, rex); 2299 else { 2300 UsualUnaryConversions(lex); 2301 UsualUnaryConversions(rex); 2302 } 2303 QualType lType = lex->getType(); 2304 QualType rType = rex->getType(); 2305 2306 // For non-floating point types, check for self-comparisons of the form 2307 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 2308 // often indicate logic errors in the program. 2309 if (!lType->isFloatingType()) { 2310 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens())) 2311 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens())) 2312 if (DRL->getDecl() == DRR->getDecl()) 2313 Diag(Loc, diag::warn_selfcomparison); 2314 } 2315 2316 // The result of comparisons is 'bool' in C++, 'int' in C. 2317 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy; 2318 2319 if (isRelational) { 2320 if (lType->isRealType() && rType->isRealType()) 2321 return ResultTy; 2322 } else { 2323 // Check for comparisons of floating point operands using != and ==. 2324 if (lType->isFloatingType()) { 2325 assert (rType->isFloatingType()); 2326 CheckFloatComparison(Loc,lex,rex); 2327 } 2328 2329 if (lType->isArithmeticType() && rType->isArithmeticType()) 2330 return ResultTy; 2331 } 2332 2333 bool LHSIsNull = lex->isNullPointerConstant(Context); 2334 bool RHSIsNull = rex->isNullPointerConstant(Context); 2335 2336 // All of the following pointer related warnings are GCC extensions, except 2337 // when handling null pointer constants. One day, we can consider making them 2338 // errors (when -pedantic-errors is enabled). 2339 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2 2340 QualType LCanPointeeTy = 2341 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType()); 2342 QualType RCanPointeeTy = 2343 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType()); 2344 2345 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2 2346 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() && 2347 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 2348 RCanPointeeTy.getUnqualifiedType()) && 2349 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) { 2350 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 2351 << lType.getAsString() << rType.getAsString() 2352 << lex->getSourceRange() << rex->getSourceRange(); 2353 } 2354 ImpCastExprToType(rex, lType); // promote the pointer to pointer 2355 return ResultTy; 2356 } 2357 // Handle block pointer types. 2358 if (lType->isBlockPointerType() && rType->isBlockPointerType()) { 2359 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType(); 2360 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType(); 2361 2362 if (!LHSIsNull && !RHSIsNull && 2363 !Context.typesAreBlockCompatible(lpointee, rpointee)) { 2364 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 2365 << lType.getAsString() << rType.getAsString() 2366 << lex->getSourceRange() << rex->getSourceRange(); 2367 } 2368 ImpCastExprToType(rex, lType); // promote the pointer to pointer 2369 return ResultTy; 2370 } 2371 // Allow block pointers to be compared with null pointer constants. 2372 if ((lType->isBlockPointerType() && rType->isPointerType()) || 2373 (lType->isPointerType() && rType->isBlockPointerType())) { 2374 if (!LHSIsNull && !RHSIsNull) { 2375 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 2376 << lType.getAsString() << rType.getAsString() 2377 << lex->getSourceRange() << rex->getSourceRange(); 2378 } 2379 ImpCastExprToType(rex, lType); // promote the pointer to pointer 2380 return ResultTy; 2381 } 2382 2383 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) { 2384 if (lType->isPointerType() || rType->isPointerType()) { 2385 const PointerType *LPT = lType->getAsPointerType(); 2386 const PointerType *RPT = rType->getAsPointerType(); 2387 bool LPtrToVoid = LPT ? 2388 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false; 2389 bool RPtrToVoid = RPT ? 2390 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false; 2391 2392 if (!LPtrToVoid && !RPtrToVoid && 2393 !Context.typesAreCompatible(lType, rType)) { 2394 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers) 2395 << lType.getAsString() << rType.getAsString() 2396 << lex->getSourceRange() << rex->getSourceRange(); 2397 ImpCastExprToType(rex, lType); 2398 return ResultTy; 2399 } 2400 ImpCastExprToType(rex, lType); 2401 return ResultTy; 2402 } 2403 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) { 2404 ImpCastExprToType(rex, lType); 2405 return ResultTy; 2406 } else { 2407 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) { 2408 Diag(Loc, diag::warn_incompatible_qualified_id_operands) 2409 << lType.getAsString() << rType.getAsString() 2410 << lex->getSourceRange() << rex->getSourceRange(); 2411 ImpCastExprToType(rex, lType); 2412 return ResultTy; 2413 } 2414 } 2415 } 2416 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) && 2417 rType->isIntegerType()) { 2418 if (!RHSIsNull) 2419 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer) 2420 << lType.getAsString() << rType.getAsString() 2421 << lex->getSourceRange() << rex->getSourceRange(); 2422 ImpCastExprToType(rex, lType); // promote the integer to pointer 2423 return ResultTy; 2424 } 2425 if (lType->isIntegerType() && 2426 (rType->isPointerType() || rType->isObjCQualifiedIdType())) { 2427 if (!LHSIsNull) 2428 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer) 2429 << lType.getAsString() << rType.getAsString() 2430 << lex->getSourceRange() << rex->getSourceRange(); 2431 ImpCastExprToType(lex, rType); // promote the integer to pointer 2432 return ResultTy; 2433 } 2434 // Handle block pointers. 2435 if (lType->isBlockPointerType() && rType->isIntegerType()) { 2436 if (!RHSIsNull) 2437 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer) 2438 << lType.getAsString() << rType.getAsString() 2439 << lex->getSourceRange() << rex->getSourceRange(); 2440 ImpCastExprToType(rex, lType); // promote the integer to pointer 2441 return ResultTy; 2442 } 2443 if (lType->isIntegerType() && rType->isBlockPointerType()) { 2444 if (!LHSIsNull) 2445 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer) 2446 << lType.getAsString() << rType.getAsString() 2447 << lex->getSourceRange() << rex->getSourceRange(); 2448 ImpCastExprToType(lex, rType); // promote the integer to pointer 2449 return ResultTy; 2450 } 2451 return InvalidOperands(Loc, lex, rex); 2452} 2453 2454/// CheckVectorCompareOperands - vector comparisons are a clang extension that 2455/// operates on extended vector types. Instead of producing an IntTy result, 2456/// like a scalar comparison, a vector comparison produces a vector of integer 2457/// types. 2458QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex, 2459 SourceLocation Loc, 2460 bool isRelational) { 2461 // Check to make sure we're operating on vectors of the same type and width, 2462 // Allowing one side to be a scalar of element type. 2463 QualType vType = CheckVectorOperands(Loc, lex, rex); 2464 if (vType.isNull()) 2465 return vType; 2466 2467 QualType lType = lex->getType(); 2468 QualType rType = rex->getType(); 2469 2470 // For non-floating point types, check for self-comparisons of the form 2471 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 2472 // often indicate logic errors in the program. 2473 if (!lType->isFloatingType()) { 2474 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens())) 2475 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens())) 2476 if (DRL->getDecl() == DRR->getDecl()) 2477 Diag(Loc, diag::warn_selfcomparison); 2478 } 2479 2480 // Check for comparisons of floating point operands using != and ==. 2481 if (!isRelational && lType->isFloatingType()) { 2482 assert (rType->isFloatingType()); 2483 CheckFloatComparison(Loc,lex,rex); 2484 } 2485 2486 // Return the type for the comparison, which is the same as vector type for 2487 // integer vectors, or an integer type of identical size and number of 2488 // elements for floating point vectors. 2489 if (lType->isIntegerType()) 2490 return lType; 2491 2492 const VectorType *VTy = lType->getAsVectorType(); 2493 2494 // FIXME: need to deal with non-32b int / non-64b long long 2495 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 2496 if (TypeSize == 32) { 2497 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 2498 } 2499 assert(TypeSize == 64 && "Unhandled vector element size in vector compare"); 2500 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 2501} 2502 2503inline QualType Sema::CheckBitwiseOperands( 2504 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) 2505{ 2506 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 2507 return CheckVectorOperands(Loc, lex, rex); 2508 2509 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 2510 2511 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 2512 return compType; 2513 return InvalidOperands(Loc, lex, rex); 2514} 2515 2516inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 2517 Expr *&lex, Expr *&rex, SourceLocation Loc) 2518{ 2519 UsualUnaryConversions(lex); 2520 UsualUnaryConversions(rex); 2521 2522 if (lex->getType()->isScalarType() && rex->getType()->isScalarType()) 2523 return Context.IntTy; 2524 return InvalidOperands(Loc, lex, rex); 2525} 2526 2527/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 2528/// emit an error and return true. If so, return false. 2529static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 2530 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context); 2531 if (IsLV == Expr::MLV_Valid) 2532 return false; 2533 2534 unsigned Diag = 0; 2535 bool NeedType = false; 2536 switch (IsLV) { // C99 6.5.16p2 2537 default: assert(0 && "Unknown result from isModifiableLvalue!"); 2538 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break; 2539 case Expr::MLV_ArrayType: 2540 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 2541 NeedType = true; 2542 break; 2543 case Expr::MLV_NotObjectType: 2544 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 2545 NeedType = true; 2546 break; 2547 case Expr::MLV_LValueCast: 2548 Diag = diag::err_typecheck_lvalue_casts_not_supported; 2549 break; 2550 case Expr::MLV_InvalidExpression: 2551 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 2552 break; 2553 case Expr::MLV_IncompleteType: 2554 case Expr::MLV_IncompleteVoidType: 2555 Diag = diag::err_typecheck_incomplete_type_not_modifiable_lvalue; 2556 NeedType = true; 2557 break; 2558 case Expr::MLV_DuplicateVectorComponents: 2559 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 2560 break; 2561 case Expr::MLV_NotBlockQualified: 2562 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 2563 break; 2564 } 2565 2566 if (NeedType) 2567 S.Diag(Loc, Diag) << E->getType().getAsString() << E->getSourceRange(); 2568 else 2569 S.Diag(Loc, Diag) << E->getSourceRange(); 2570 return true; 2571} 2572 2573 2574 2575// C99 6.5.16.1 2576QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS, 2577 SourceLocation Loc, 2578 QualType CompoundType) { 2579 // Verify that LHS is a modifiable lvalue, and emit error if not. 2580 if (CheckForModifiableLvalue(LHS, Loc, *this)) 2581 return QualType(); 2582 2583 QualType LHSType = LHS->getType(); 2584 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType; 2585 2586 AssignConvertType ConvTy; 2587 if (CompoundType.isNull()) { 2588 // Simple assignment "x = y". 2589 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS); 2590 2591 // If the RHS is a unary plus or minus, check to see if they = and + are 2592 // right next to each other. If so, the user may have typo'd "x =+ 4" 2593 // instead of "x += 4". 2594 Expr *RHSCheck = RHS; 2595 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 2596 RHSCheck = ICE->getSubExpr(); 2597 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 2598 if ((UO->getOpcode() == UnaryOperator::Plus || 2599 UO->getOpcode() == UnaryOperator::Minus) && 2600 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 2601 // Only if the two operators are exactly adjacent. 2602 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc()) 2603 Diag(Loc, diag::warn_not_compound_assign) 2604 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-") 2605 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 2606 } 2607 } else { 2608 // Compound assignment "x += y" 2609 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType); 2610 } 2611 2612 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 2613 RHS, "assigning")) 2614 return QualType(); 2615 2616 // C99 6.5.16p3: The type of an assignment expression is the type of the 2617 // left operand unless the left operand has qualified type, in which case 2618 // it is the unqualified version of the type of the left operand. 2619 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 2620 // is converted to the type of the assignment expression (above). 2621 // C++ 5.17p1: the type of the assignment expression is that of its left 2622 // oprdu. 2623 return LHSType.getUnqualifiedType(); 2624} 2625 2626// C99 6.5.17 2627QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) { 2628 // FIXME: what is required for LHS? 2629 2630 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions. 2631 DefaultFunctionArrayConversion(RHS); 2632 return RHS->getType(); 2633} 2634 2635/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 2636/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 2637QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) { 2638 QualType resType = op->getType(); 2639 assert(!resType.isNull() && "no type for increment/decrement expression"); 2640 2641 // C99 6.5.2.4p1: We allow complex as a GCC extension. 2642 if (const PointerType *pt = resType->getAsPointerType()) { 2643 if (pt->getPointeeType()->isVoidType()) { 2644 Diag(OpLoc, diag::ext_gnu_void_ptr) << op->getSourceRange(); 2645 } else if (!pt->getPointeeType()->isObjectType()) { 2646 // C99 6.5.2.4p2, 6.5.6p2 2647 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type) 2648 << resType.getAsString() << op->getSourceRange(); 2649 return QualType(); 2650 } 2651 } else if (!resType->isRealType()) { 2652 if (resType->isComplexType()) 2653 // C99 does not support ++/-- on complex types. 2654 Diag(OpLoc, diag::ext_integer_increment_complex) 2655 << resType.getAsString() << op->getSourceRange(); 2656 else { 2657 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 2658 << resType.getAsString() << op->getSourceRange(); 2659 return QualType(); 2660 } 2661 } 2662 // At this point, we know we have a real, complex or pointer type. 2663 // Now make sure the operand is a modifiable lvalue. 2664 if (CheckForModifiableLvalue(op, OpLoc, *this)) 2665 return QualType(); 2666 return resType; 2667} 2668 2669/// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 2670/// This routine allows us to typecheck complex/recursive expressions 2671/// where the declaration is needed for type checking. We only need to 2672/// handle cases when the expression references a function designator 2673/// or is an lvalue. Here are some examples: 2674/// - &(x) => x 2675/// - &*****f => f for f a function designator. 2676/// - &s.xx => s 2677/// - &s.zz[1].yy -> s, if zz is an array 2678/// - *(x + 1) -> x, if x is an array 2679/// - &"123"[2] -> 0 2680/// - & __real__ x -> x 2681static NamedDecl *getPrimaryDecl(Expr *E) { 2682 switch (E->getStmtClass()) { 2683 case Stmt::DeclRefExprClass: 2684 return cast<DeclRefExpr>(E)->getDecl(); 2685 case Stmt::MemberExprClass: 2686 // Fields cannot be declared with a 'register' storage class. 2687 // &X->f is always ok, even if X is declared register. 2688 if (cast<MemberExpr>(E)->isArrow()) 2689 return 0; 2690 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 2691 case Stmt::ArraySubscriptExprClass: { 2692 // &X[4] and &4[X] refers to X if X is not a pointer. 2693 2694 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase()); 2695 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D); 2696 if (!VD || VD->getType()->isPointerType()) 2697 return 0; 2698 else 2699 return VD; 2700 } 2701 case Stmt::UnaryOperatorClass: { 2702 UnaryOperator *UO = cast<UnaryOperator>(E); 2703 2704 switch(UO->getOpcode()) { 2705 case UnaryOperator::Deref: { 2706 // *(X + 1) refers to X if X is not a pointer. 2707 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) { 2708 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2709 if (!VD || VD->getType()->isPointerType()) 2710 return 0; 2711 return VD; 2712 } 2713 return 0; 2714 } 2715 case UnaryOperator::Real: 2716 case UnaryOperator::Imag: 2717 case UnaryOperator::Extension: 2718 return getPrimaryDecl(UO->getSubExpr()); 2719 default: 2720 return 0; 2721 } 2722 } 2723 case Stmt::BinaryOperatorClass: { 2724 BinaryOperator *BO = cast<BinaryOperator>(E); 2725 2726 // Handle cases involving pointer arithmetic. The result of an 2727 // Assign or AddAssign is not an lvalue so they can be ignored. 2728 2729 // (x + n) or (n + x) => x 2730 if (BO->getOpcode() == BinaryOperator::Add) { 2731 if (BO->getLHS()->getType()->isPointerType()) { 2732 return getPrimaryDecl(BO->getLHS()); 2733 } else if (BO->getRHS()->getType()->isPointerType()) { 2734 return getPrimaryDecl(BO->getRHS()); 2735 } 2736 } 2737 2738 return 0; 2739 } 2740 case Stmt::ParenExprClass: 2741 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 2742 case Stmt::ImplicitCastExprClass: 2743 // &X[4] when X is an array, has an implicit cast from array to pointer. 2744 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 2745 default: 2746 return 0; 2747 } 2748} 2749 2750/// CheckAddressOfOperand - The operand of & must be either a function 2751/// designator or an lvalue designating an object. If it is an lvalue, the 2752/// object cannot be declared with storage class register or be a bit field. 2753/// Note: The usual conversions are *not* applied to the operand of the & 2754/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 2755/// In C++, the operand might be an overloaded function name, in which case 2756/// we allow the '&' but retain the overloaded-function type. 2757QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) { 2758 if (getLangOptions().C99) { 2759 // Implement C99-only parts of addressof rules. 2760 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 2761 if (uOp->getOpcode() == UnaryOperator::Deref) 2762 // Per C99 6.5.3.2, the address of a deref always returns a valid result 2763 // (assuming the deref expression is valid). 2764 return uOp->getSubExpr()->getType(); 2765 } 2766 // Technically, there should be a check for array subscript 2767 // expressions here, but the result of one is always an lvalue anyway. 2768 } 2769 NamedDecl *dcl = getPrimaryDecl(op); 2770 Expr::isLvalueResult lval = op->isLvalue(Context); 2771 2772 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1 2773 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators 2774 // FIXME: emit more specific diag... 2775 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 2776 << op->getSourceRange(); 2777 return QualType(); 2778 } 2779 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1 2780 if (MemExpr->getMemberDecl()->isBitField()) { 2781 Diag(OpLoc, diag::err_typecheck_address_of) 2782 << "bit-field" << op->getSourceRange(); 2783 return QualType(); 2784 } 2785 // Check for Apple extension for accessing vector components. 2786 } else if (isa<ArraySubscriptExpr>(op) && 2787 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) { 2788 Diag(OpLoc, diag::err_typecheck_address_of) 2789 << "vector" << op->getSourceRange(); 2790 return QualType(); 2791 } else if (dcl) { // C99 6.5.3.2p1 2792 // We have an lvalue with a decl. Make sure the decl is not declared 2793 // with the register storage-class specifier. 2794 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 2795 if (vd->getStorageClass() == VarDecl::Register) { 2796 Diag(OpLoc, diag::err_typecheck_address_of) 2797 << "register variable" << op->getSourceRange(); 2798 return QualType(); 2799 } 2800 } else if (isa<OverloadedFunctionDecl>(dcl)) 2801 return Context.OverloadTy; 2802 else 2803 assert(0 && "Unknown/unexpected decl type"); 2804 } 2805 2806 // If the operand has type "type", the result has type "pointer to type". 2807 return Context.getPointerType(op->getType()); 2808} 2809 2810QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) { 2811 UsualUnaryConversions(op); 2812 QualType qType = op->getType(); 2813 2814 if (const PointerType *PT = qType->getAsPointerType()) { 2815 // Note that per both C89 and C99, this is always legal, even 2816 // if ptype is an incomplete type or void. 2817 // It would be possible to warn about dereferencing a 2818 // void pointer, but it's completely well-defined, 2819 // and such a warning is unlikely to catch any mistakes. 2820 return PT->getPointeeType(); 2821 } 2822 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 2823 << qType.getAsString() << op->getSourceRange(); 2824 return QualType(); 2825} 2826 2827static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode( 2828 tok::TokenKind Kind) { 2829 BinaryOperator::Opcode Opc; 2830 switch (Kind) { 2831 default: assert(0 && "Unknown binop!"); 2832 case tok::star: Opc = BinaryOperator::Mul; break; 2833 case tok::slash: Opc = BinaryOperator::Div; break; 2834 case tok::percent: Opc = BinaryOperator::Rem; break; 2835 case tok::plus: Opc = BinaryOperator::Add; break; 2836 case tok::minus: Opc = BinaryOperator::Sub; break; 2837 case tok::lessless: Opc = BinaryOperator::Shl; break; 2838 case tok::greatergreater: Opc = BinaryOperator::Shr; break; 2839 case tok::lessequal: Opc = BinaryOperator::LE; break; 2840 case tok::less: Opc = BinaryOperator::LT; break; 2841 case tok::greaterequal: Opc = BinaryOperator::GE; break; 2842 case tok::greater: Opc = BinaryOperator::GT; break; 2843 case tok::exclaimequal: Opc = BinaryOperator::NE; break; 2844 case tok::equalequal: Opc = BinaryOperator::EQ; break; 2845 case tok::amp: Opc = BinaryOperator::And; break; 2846 case tok::caret: Opc = BinaryOperator::Xor; break; 2847 case tok::pipe: Opc = BinaryOperator::Or; break; 2848 case tok::ampamp: Opc = BinaryOperator::LAnd; break; 2849 case tok::pipepipe: Opc = BinaryOperator::LOr; break; 2850 case tok::equal: Opc = BinaryOperator::Assign; break; 2851 case tok::starequal: Opc = BinaryOperator::MulAssign; break; 2852 case tok::slashequal: Opc = BinaryOperator::DivAssign; break; 2853 case tok::percentequal: Opc = BinaryOperator::RemAssign; break; 2854 case tok::plusequal: Opc = BinaryOperator::AddAssign; break; 2855 case tok::minusequal: Opc = BinaryOperator::SubAssign; break; 2856 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break; 2857 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break; 2858 case tok::ampequal: Opc = BinaryOperator::AndAssign; break; 2859 case tok::caretequal: Opc = BinaryOperator::XorAssign; break; 2860 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break; 2861 case tok::comma: Opc = BinaryOperator::Comma; break; 2862 } 2863 return Opc; 2864} 2865 2866static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode( 2867 tok::TokenKind Kind) { 2868 UnaryOperator::Opcode Opc; 2869 switch (Kind) { 2870 default: assert(0 && "Unknown unary op!"); 2871 case tok::plusplus: Opc = UnaryOperator::PreInc; break; 2872 case tok::minusminus: Opc = UnaryOperator::PreDec; break; 2873 case tok::amp: Opc = UnaryOperator::AddrOf; break; 2874 case tok::star: Opc = UnaryOperator::Deref; break; 2875 case tok::plus: Opc = UnaryOperator::Plus; break; 2876 case tok::minus: Opc = UnaryOperator::Minus; break; 2877 case tok::tilde: Opc = UnaryOperator::Not; break; 2878 case tok::exclaim: Opc = UnaryOperator::LNot; break; 2879 case tok::kw___real: Opc = UnaryOperator::Real; break; 2880 case tok::kw___imag: Opc = UnaryOperator::Imag; break; 2881 case tok::kw___extension__: Opc = UnaryOperator::Extension; break; 2882 } 2883 return Opc; 2884} 2885 2886/// CreateBuiltinBinOp - Creates a new built-in binary operation with 2887/// operator @p Opc at location @c TokLoc. This routine only supports 2888/// built-in operations; ActOnBinOp handles overloaded operators. 2889Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 2890 unsigned Op, 2891 Expr *lhs, Expr *rhs) { 2892 QualType ResultTy; // Result type of the binary operator. 2893 QualType CompTy; // Computation type for compound assignments (e.g. '+=') 2894 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op; 2895 2896 switch (Opc) { 2897 default: 2898 assert(0 && "Unknown binary expr!"); 2899 case BinaryOperator::Assign: 2900 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType()); 2901 break; 2902 case BinaryOperator::Mul: 2903 case BinaryOperator::Div: 2904 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc); 2905 break; 2906 case BinaryOperator::Rem: 2907 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc); 2908 break; 2909 case BinaryOperator::Add: 2910 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc); 2911 break; 2912 case BinaryOperator::Sub: 2913 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc); 2914 break; 2915 case BinaryOperator::Shl: 2916 case BinaryOperator::Shr: 2917 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc); 2918 break; 2919 case BinaryOperator::LE: 2920 case BinaryOperator::LT: 2921 case BinaryOperator::GE: 2922 case BinaryOperator::GT: 2923 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true); 2924 break; 2925 case BinaryOperator::EQ: 2926 case BinaryOperator::NE: 2927 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false); 2928 break; 2929 case BinaryOperator::And: 2930 case BinaryOperator::Xor: 2931 case BinaryOperator::Or: 2932 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc); 2933 break; 2934 case BinaryOperator::LAnd: 2935 case BinaryOperator::LOr: 2936 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc); 2937 break; 2938 case BinaryOperator::MulAssign: 2939 case BinaryOperator::DivAssign: 2940 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true); 2941 if (!CompTy.isNull()) 2942 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 2943 break; 2944 case BinaryOperator::RemAssign: 2945 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true); 2946 if (!CompTy.isNull()) 2947 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 2948 break; 2949 case BinaryOperator::AddAssign: 2950 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true); 2951 if (!CompTy.isNull()) 2952 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 2953 break; 2954 case BinaryOperator::SubAssign: 2955 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true); 2956 if (!CompTy.isNull()) 2957 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 2958 break; 2959 case BinaryOperator::ShlAssign: 2960 case BinaryOperator::ShrAssign: 2961 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true); 2962 if (!CompTy.isNull()) 2963 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 2964 break; 2965 case BinaryOperator::AndAssign: 2966 case BinaryOperator::XorAssign: 2967 case BinaryOperator::OrAssign: 2968 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true); 2969 if (!CompTy.isNull()) 2970 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy); 2971 break; 2972 case BinaryOperator::Comma: 2973 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc); 2974 break; 2975 } 2976 if (ResultTy.isNull()) 2977 return true; 2978 if (CompTy.isNull()) 2979 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc); 2980 else 2981 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc); 2982} 2983 2984// Binary Operators. 'Tok' is the token for the operator. 2985Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 2986 tok::TokenKind Kind, 2987 ExprTy *LHS, ExprTy *RHS) { 2988 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind); 2989 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS; 2990 2991 assert((lhs != 0) && "ActOnBinOp(): missing left expression"); 2992 assert((rhs != 0) && "ActOnBinOp(): missing right expression"); 2993 2994 if (getLangOptions().CPlusPlus && 2995 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() || 2996 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) { 2997 // If this is one of the assignment operators, we only perform 2998 // overload resolution if the left-hand side is a class or 2999 // enumeration type (C++ [expr.ass]p3). 3000 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign && 3001 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) { 3002 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs); 3003 } 3004 3005 // Determine which overloaded operator we're dealing with. 3006 static const OverloadedOperatorKind OverOps[] = { 3007 OO_Star, OO_Slash, OO_Percent, 3008 OO_Plus, OO_Minus, 3009 OO_LessLess, OO_GreaterGreater, 3010 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual, 3011 OO_EqualEqual, OO_ExclaimEqual, 3012 OO_Amp, 3013 OO_Caret, 3014 OO_Pipe, 3015 OO_AmpAmp, 3016 OO_PipePipe, 3017 OO_Equal, OO_StarEqual, 3018 OO_SlashEqual, OO_PercentEqual, 3019 OO_PlusEqual, OO_MinusEqual, 3020 OO_LessLessEqual, OO_GreaterGreaterEqual, 3021 OO_AmpEqual, OO_CaretEqual, 3022 OO_PipeEqual, 3023 OO_Comma 3024 }; 3025 OverloadedOperatorKind OverOp = OverOps[Opc]; 3026 3027 // Add the appropriate overloaded operators (C++ [over.match.oper]) 3028 // to the candidate set. 3029 OverloadCandidateSet CandidateSet; 3030 Expr *Args[2] = { lhs, rhs }; 3031 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet); 3032 3033 // Perform overload resolution. 3034 OverloadCandidateSet::iterator Best; 3035 switch (BestViableFunction(CandidateSet, Best)) { 3036 case OR_Success: { 3037 // We found a built-in operator or an overloaded operator. 3038 FunctionDecl *FnDecl = Best->Function; 3039 3040 if (FnDecl) { 3041 // We matched an overloaded operator. Build a call to that 3042 // operator. 3043 3044 // Convert the arguments. 3045 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 3046 if (PerformObjectArgumentInitialization(lhs, Method) || 3047 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(), 3048 "passing")) 3049 return true; 3050 } else { 3051 // Convert the arguments. 3052 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(), 3053 "passing") || 3054 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(), 3055 "passing")) 3056 return true; 3057 } 3058 3059 // Determine the result type 3060 QualType ResultTy 3061 = FnDecl->getType()->getAsFunctionType()->getResultType(); 3062 ResultTy = ResultTy.getNonReferenceType(); 3063 3064 // Build the actual expression node. 3065 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(), 3066 SourceLocation()); 3067 UsualUnaryConversions(FnExpr); 3068 3069 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, TokLoc); 3070 } else { 3071 // We matched a built-in operator. Convert the arguments, then 3072 // break out so that we will build the appropriate built-in 3073 // operator node. 3074 if (PerformCopyInitialization(lhs, Best->BuiltinTypes.ParamTypes[0], 3075 "passing") || 3076 PerformCopyInitialization(rhs, Best->BuiltinTypes.ParamTypes[1], 3077 "passing")) 3078 return true; 3079 3080 break; 3081 } 3082 } 3083 3084 case OR_No_Viable_Function: 3085 // No viable function; fall through to handling this as a 3086 // built-in operator, which will produce an error message for us. 3087 break; 3088 3089 case OR_Ambiguous: 3090 Diag(TokLoc, diag::err_ovl_ambiguous_oper) 3091 << BinaryOperator::getOpcodeStr(Opc) 3092 << lhs->getSourceRange() << rhs->getSourceRange(); 3093 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3094 return true; 3095 } 3096 3097 // Either we found no viable overloaded operator or we matched a 3098 // built-in operator. In either case, fall through to trying to 3099 // build a built-in operation. 3100 } 3101 3102 // Build a built-in binary operation. 3103 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs); 3104} 3105 3106// Unary Operators. 'Tok' is the token for the operator. 3107Action::ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 3108 tok::TokenKind Op, ExprTy *input) { 3109 Expr *Input = (Expr*)input; 3110 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op); 3111 3112 if (getLangOptions().CPlusPlus && 3113 (Input->getType()->isRecordType() 3114 || Input->getType()->isEnumeralType())) { 3115 // Determine which overloaded operator we're dealing with. 3116 static const OverloadedOperatorKind OverOps[] = { 3117 OO_None, OO_None, 3118 OO_PlusPlus, OO_MinusMinus, 3119 OO_Amp, OO_Star, 3120 OO_Plus, OO_Minus, 3121 OO_Tilde, OO_Exclaim, 3122 OO_None, OO_None, 3123 OO_None, 3124 OO_None 3125 }; 3126 OverloadedOperatorKind OverOp = OverOps[Opc]; 3127 3128 // Add the appropriate overloaded operators (C++ [over.match.oper]) 3129 // to the candidate set. 3130 OverloadCandidateSet CandidateSet; 3131 if (OverOp != OO_None) 3132 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet); 3133 3134 // Perform overload resolution. 3135 OverloadCandidateSet::iterator Best; 3136 switch (BestViableFunction(CandidateSet, Best)) { 3137 case OR_Success: { 3138 // We found a built-in operator or an overloaded operator. 3139 FunctionDecl *FnDecl = Best->Function; 3140 3141 if (FnDecl) { 3142 // We matched an overloaded operator. Build a call to that 3143 // operator. 3144 3145 // Convert the arguments. 3146 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 3147 if (PerformObjectArgumentInitialization(Input, Method)) 3148 return true; 3149 } else { 3150 // Convert the arguments. 3151 if (PerformCopyInitialization(Input, 3152 FnDecl->getParamDecl(0)->getType(), 3153 "passing")) 3154 return true; 3155 } 3156 3157 // Determine the result type 3158 QualType ResultTy 3159 = FnDecl->getType()->getAsFunctionType()->getResultType(); 3160 ResultTy = ResultTy.getNonReferenceType(); 3161 3162 // Build the actual expression node. 3163 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(), 3164 SourceLocation()); 3165 UsualUnaryConversions(FnExpr); 3166 3167 return new CXXOperatorCallExpr(FnExpr, &Input, 1, ResultTy, OpLoc); 3168 } else { 3169 // We matched a built-in operator. Convert the arguments, then 3170 // break out so that we will build the appropriate built-in 3171 // operator node. 3172 if (PerformCopyInitialization(Input, Best->BuiltinTypes.ParamTypes[0], 3173 "passing")) 3174 return true; 3175 3176 break; 3177 } 3178 } 3179 3180 case OR_No_Viable_Function: 3181 // No viable function; fall through to handling this as a 3182 // built-in operator, which will produce an error message for us. 3183 break; 3184 3185 case OR_Ambiguous: 3186 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 3187 << UnaryOperator::getOpcodeStr(Opc) 3188 << Input->getSourceRange(); 3189 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3190 return true; 3191 } 3192 3193 // Either we found no viable overloaded operator or we matched a 3194 // built-in operator. In either case, fall through to trying to 3195 // build a built-in operation. 3196 } 3197 3198 3199 QualType resultType; 3200 switch (Opc) { 3201 default: 3202 assert(0 && "Unimplemented unary expr!"); 3203 case UnaryOperator::PreInc: 3204 case UnaryOperator::PreDec: 3205 resultType = CheckIncrementDecrementOperand(Input, OpLoc); 3206 break; 3207 case UnaryOperator::AddrOf: 3208 resultType = CheckAddressOfOperand(Input, OpLoc); 3209 break; 3210 case UnaryOperator::Deref: 3211 DefaultFunctionArrayConversion(Input); 3212 resultType = CheckIndirectionOperand(Input, OpLoc); 3213 break; 3214 case UnaryOperator::Plus: 3215 case UnaryOperator::Minus: 3216 UsualUnaryConversions(Input); 3217 resultType = Input->getType(); 3218 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 3219 break; 3220 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7 3221 resultType->isEnumeralType()) 3222 break; 3223 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6 3224 Opc == UnaryOperator::Plus && 3225 resultType->isPointerType()) 3226 break; 3227 3228 return Diag(OpLoc, diag::err_typecheck_unary_expr) 3229 << resultType.getAsString(); 3230 case UnaryOperator::Not: // bitwise complement 3231 UsualUnaryConversions(Input); 3232 resultType = Input->getType(); 3233 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 3234 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 3235 // C99 does not support '~' for complex conjugation. 3236 Diag(OpLoc, diag::ext_integer_complement_complex) 3237 << resultType.getAsString() << Input->getSourceRange(); 3238 else if (!resultType->isIntegerType()) 3239 return Diag(OpLoc, diag::err_typecheck_unary_expr) 3240 << resultType.getAsString() << Input->getSourceRange(); 3241 break; 3242 case UnaryOperator::LNot: // logical negation 3243 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 3244 DefaultFunctionArrayConversion(Input); 3245 resultType = Input->getType(); 3246 if (!resultType->isScalarType()) // C99 6.5.3.3p1 3247 return Diag(OpLoc, diag::err_typecheck_unary_expr) 3248 << resultType.getAsString(); 3249 // LNot always has type int. C99 6.5.3.3p5. 3250 resultType = Context.IntTy; 3251 break; 3252 case UnaryOperator::Real: 3253 case UnaryOperator::Imag: 3254 resultType = CheckRealImagOperand(Input, OpLoc); 3255 break; 3256 case UnaryOperator::Extension: 3257 resultType = Input->getType(); 3258 break; 3259 } 3260 if (resultType.isNull()) 3261 return true; 3262 return new UnaryOperator(Input, Opc, resultType, OpLoc); 3263} 3264 3265/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 3266Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, 3267 SourceLocation LabLoc, 3268 IdentifierInfo *LabelII) { 3269 // Look up the record for this label identifier. 3270 LabelStmt *&LabelDecl = LabelMap[LabelII]; 3271 3272 // If we haven't seen this label yet, create a forward reference. It 3273 // will be validated and/or cleaned up in ActOnFinishFunctionBody. 3274 if (LabelDecl == 0) 3275 LabelDecl = new LabelStmt(LabLoc, LabelII, 0); 3276 3277 // Create the AST node. The address of a label always has type 'void*'. 3278 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl, 3279 Context.getPointerType(Context.VoidTy)); 3280} 3281 3282Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt, 3283 SourceLocation RPLoc) { // "({..})" 3284 Stmt *SubStmt = static_cast<Stmt*>(substmt); 3285 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 3286 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 3287 3288 // FIXME: there are a variety of strange constraints to enforce here, for 3289 // example, it is not possible to goto into a stmt expression apparently. 3290 // More semantic analysis is needed. 3291 3292 // FIXME: the last statement in the compount stmt has its value used. We 3293 // should not warn about it being unused. 3294 3295 // If there are sub stmts in the compound stmt, take the type of the last one 3296 // as the type of the stmtexpr. 3297 QualType Ty = Context.VoidTy; 3298 3299 if (!Compound->body_empty()) { 3300 Stmt *LastStmt = Compound->body_back(); 3301 // If LastStmt is a label, skip down through into the body. 3302 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) 3303 LastStmt = Label->getSubStmt(); 3304 3305 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) 3306 Ty = LastExpr->getType(); 3307 } 3308 3309 return new StmtExpr(Compound, Ty, LPLoc, RPLoc); 3310} 3311 3312Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc, 3313 SourceLocation TypeLoc, 3314 TypeTy *argty, 3315 OffsetOfComponent *CompPtr, 3316 unsigned NumComponents, 3317 SourceLocation RPLoc) { 3318 QualType ArgTy = QualType::getFromOpaquePtr(argty); 3319 assert(!ArgTy.isNull() && "Missing type argument!"); 3320 3321 // We must have at least one component that refers to the type, and the first 3322 // one is known to be a field designator. Verify that the ArgTy represents 3323 // a struct/union/class. 3324 if (!ArgTy->isRecordType()) 3325 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy.getAsString(); 3326 3327 // Otherwise, create a compound literal expression as the base, and 3328 // iteratively process the offsetof designators. 3329 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false); 3330 3331 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 3332 // GCC extension, diagnose them. 3333 if (NumComponents != 1) 3334 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 3335 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 3336 3337 for (unsigned i = 0; i != NumComponents; ++i) { 3338 const OffsetOfComponent &OC = CompPtr[i]; 3339 if (OC.isBrackets) { 3340 // Offset of an array sub-field. TODO: Should we allow vector elements? 3341 const ArrayType *AT = Context.getAsArrayType(Res->getType()); 3342 if (!AT) { 3343 delete Res; 3344 return Diag(OC.LocEnd, diag::err_offsetof_array_type) 3345 << Res->getType().getAsString(); 3346 } 3347 3348 // FIXME: C++: Verify that operator[] isn't overloaded. 3349 3350 // C99 6.5.2.1p1 3351 Expr *Idx = static_cast<Expr*>(OC.U.E); 3352 if (!Idx->getType()->isIntegerType()) 3353 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript) 3354 << Idx->getSourceRange(); 3355 3356 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd); 3357 continue; 3358 } 3359 3360 const RecordType *RC = Res->getType()->getAsRecordType(); 3361 if (!RC) { 3362 delete Res; 3363 return Diag(OC.LocEnd, diag::err_offsetof_record_type) 3364 << Res->getType().getAsString(); 3365 } 3366 3367 // Get the decl corresponding to this. 3368 RecordDecl *RD = RC->getDecl(); 3369 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo); 3370 if (!MemberDecl) 3371 return Diag(BuiltinLoc, diag::err_typecheck_no_member) 3372 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd); 3373 3374 // FIXME: C++: Verify that MemberDecl isn't a static field. 3375 // FIXME: Verify that MemberDecl isn't a bitfield. 3376 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't 3377 // matter here. 3378 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, 3379 MemberDecl->getType().getNonReferenceType()); 3380 } 3381 3382 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(), 3383 BuiltinLoc); 3384} 3385 3386 3387Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc, 3388 TypeTy *arg1, TypeTy *arg2, 3389 SourceLocation RPLoc) { 3390 QualType argT1 = QualType::getFromOpaquePtr(arg1); 3391 QualType argT2 = QualType::getFromOpaquePtr(arg2); 3392 3393 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)"); 3394 3395 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc); 3396} 3397 3398Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond, 3399 ExprTy *expr1, ExprTy *expr2, 3400 SourceLocation RPLoc) { 3401 Expr *CondExpr = static_cast<Expr*>(cond); 3402 Expr *LHSExpr = static_cast<Expr*>(expr1); 3403 Expr *RHSExpr = static_cast<Expr*>(expr2); 3404 3405 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 3406 3407 // The conditional expression is required to be a constant expression. 3408 llvm::APSInt condEval(32); 3409 SourceLocation ExpLoc; 3410 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc)) 3411 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant) 3412 << CondExpr->getSourceRange(); 3413 3414 // If the condition is > zero, then the AST type is the same as the LSHExpr. 3415 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() : 3416 RHSExpr->getType(); 3417 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc); 3418} 3419 3420//===----------------------------------------------------------------------===// 3421// Clang Extensions. 3422//===----------------------------------------------------------------------===// 3423 3424/// ActOnBlockStart - This callback is invoked when a block literal is started. 3425void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) { 3426 // Analyze block parameters. 3427 BlockSemaInfo *BSI = new BlockSemaInfo(); 3428 3429 // Add BSI to CurBlock. 3430 BSI->PrevBlockInfo = CurBlock; 3431 CurBlock = BSI; 3432 3433 BSI->ReturnType = 0; 3434 BSI->TheScope = BlockScope; 3435 3436 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc); 3437 PushDeclContext(BSI->TheDecl); 3438} 3439 3440void Sema::ActOnBlockArguments(Declarator &ParamInfo) { 3441 // Analyze arguments to block. 3442 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function && 3443 "Not a function declarator!"); 3444 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun; 3445 3446 CurBlock->hasPrototype = FTI.hasPrototype; 3447 CurBlock->isVariadic = true; 3448 3449 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes 3450 // no arguments, not a function that takes a single void argument. 3451 if (FTI.hasPrototype && 3452 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 3453 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() && 3454 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) { 3455 // empty arg list, don't push any params. 3456 CurBlock->isVariadic = false; 3457 } else if (FTI.hasPrototype) { 3458 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) 3459 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param); 3460 CurBlock->isVariadic = FTI.isVariadic; 3461 } 3462 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size()); 3463 3464 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 3465 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) 3466 // If this has an identifier, add it to the scope stack. 3467 if ((*AI)->getIdentifier()) 3468 PushOnScopeChains(*AI, CurBlock->TheScope); 3469} 3470 3471/// ActOnBlockError - If there is an error parsing a block, this callback 3472/// is invoked to pop the information about the block from the action impl. 3473void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 3474 // Ensure that CurBlock is deleted. 3475 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock); 3476 3477 // Pop off CurBlock, handle nested blocks. 3478 CurBlock = CurBlock->PrevBlockInfo; 3479 3480 // FIXME: Delete the ParmVarDecl objects as well??? 3481 3482} 3483 3484/// ActOnBlockStmtExpr - This is called when the body of a block statement 3485/// literal was successfully completed. ^(int x){...} 3486Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body, 3487 Scope *CurScope) { 3488 // Ensure that CurBlock is deleted. 3489 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock); 3490 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body)); 3491 3492 PopDeclContext(); 3493 3494 // Pop off CurBlock, handle nested blocks. 3495 CurBlock = CurBlock->PrevBlockInfo; 3496 3497 QualType RetTy = Context.VoidTy; 3498 if (BSI->ReturnType) 3499 RetTy = QualType(BSI->ReturnType, 0); 3500 3501 llvm::SmallVector<QualType, 8> ArgTypes; 3502 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i) 3503 ArgTypes.push_back(BSI->Params[i]->getType()); 3504 3505 QualType BlockTy; 3506 if (!BSI->hasPrototype) 3507 BlockTy = Context.getFunctionTypeNoProto(RetTy); 3508 else 3509 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(), 3510 BSI->isVariadic, 0); 3511 3512 BlockTy = Context.getBlockPointerType(BlockTy); 3513 3514 BSI->TheDecl->setBody(Body.take()); 3515 return new BlockExpr(BSI->TheDecl, BlockTy); 3516} 3517 3518/// ExprsMatchFnType - return true if the Exprs in array Args have 3519/// QualTypes that match the QualTypes of the arguments of the FnType. 3520/// The number of arguments has already been validated to match the number of 3521/// arguments in FnType. 3522static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType, 3523 ASTContext &Context) { 3524 unsigned NumParams = FnType->getNumArgs(); 3525 for (unsigned i = 0; i != NumParams; ++i) { 3526 QualType ExprTy = Context.getCanonicalType(Args[i]->getType()); 3527 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i)); 3528 3529 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType()) 3530 return false; 3531 } 3532 return true; 3533} 3534 3535Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs, 3536 SourceLocation *CommaLocs, 3537 SourceLocation BuiltinLoc, 3538 SourceLocation RParenLoc) { 3539 // __builtin_overload requires at least 2 arguments 3540 if (NumArgs < 2) 3541 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args) 3542 << SourceRange(BuiltinLoc, RParenLoc); 3543 3544 // The first argument is required to be a constant expression. It tells us 3545 // the number of arguments to pass to each of the functions to be overloaded. 3546 Expr **Args = reinterpret_cast<Expr**>(args); 3547 Expr *NParamsExpr = Args[0]; 3548 llvm::APSInt constEval(32); 3549 SourceLocation ExpLoc; 3550 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc)) 3551 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant) 3552 << NParamsExpr->getSourceRange(); 3553 3554 // Verify that the number of parameters is > 0 3555 unsigned NumParams = constEval.getZExtValue(); 3556 if (NumParams == 0) 3557 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant) 3558 << NParamsExpr->getSourceRange(); 3559 // Verify that we have at least 1 + NumParams arguments to the builtin. 3560 if ((NumParams + 1) > NumArgs) 3561 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args) 3562 << SourceRange(BuiltinLoc, RParenLoc); 3563 3564 // Figure out the return type, by matching the args to one of the functions 3565 // listed after the parameters. 3566 OverloadExpr *OE = 0; 3567 for (unsigned i = NumParams + 1; i < NumArgs; ++i) { 3568 // UsualUnaryConversions will convert the function DeclRefExpr into a 3569 // pointer to function. 3570 Expr *Fn = UsualUnaryConversions(Args[i]); 3571 const FunctionTypeProto *FnType = 0; 3572 if (const PointerType *PT = Fn->getType()->getAsPointerType()) 3573 FnType = PT->getPointeeType()->getAsFunctionTypeProto(); 3574 3575 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no 3576 // parameters, and the number of parameters must match the value passed to 3577 // the builtin. 3578 if (!FnType || (FnType->getNumArgs() != NumParams)) 3579 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype) 3580 << Fn->getSourceRange(); 3581 3582 // Scan the parameter list for the FunctionType, checking the QualType of 3583 // each parameter against the QualTypes of the arguments to the builtin. 3584 // If they match, return a new OverloadExpr. 3585 if (ExprsMatchFnType(Args+1, FnType, Context)) { 3586 if (OE) 3587 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match) 3588 << OE->getFn()->getSourceRange(); 3589 // Remember our match, and continue processing the remaining arguments 3590 // to catch any errors. 3591 OE = new OverloadExpr(Args, NumArgs, i, 3592 FnType->getResultType().getNonReferenceType(), 3593 BuiltinLoc, RParenLoc); 3594 } 3595 } 3596 // Return the newly created OverloadExpr node, if we succeded in matching 3597 // exactly one of the candidate functions. 3598 if (OE) 3599 return OE; 3600 3601 // If we didn't find a matching function Expr in the __builtin_overload list 3602 // the return an error. 3603 std::string typeNames; 3604 for (unsigned i = 0; i != NumParams; ++i) { 3605 if (i != 0) typeNames += ", "; 3606 typeNames += Args[i+1]->getType().getAsString(); 3607 } 3608 3609 return Diag(BuiltinLoc, diag::err_overload_no_match) 3610 << typeNames << SourceRange(BuiltinLoc, RParenLoc); 3611} 3612 3613Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 3614 ExprTy *expr, TypeTy *type, 3615 SourceLocation RPLoc) { 3616 Expr *E = static_cast<Expr*>(expr); 3617 QualType T = QualType::getFromOpaquePtr(type); 3618 3619 InitBuiltinVaListType(); 3620 3621 // Get the va_list type 3622 QualType VaListType = Context.getBuiltinVaListType(); 3623 // Deal with implicit array decay; for example, on x86-64, 3624 // va_list is an array, but it's supposed to decay to 3625 // a pointer for va_arg. 3626 if (VaListType->isArrayType()) 3627 VaListType = Context.getArrayDecayedType(VaListType); 3628 // Make sure the input expression also decays appropriately. 3629 UsualUnaryConversions(E); 3630 3631 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible) 3632 return Diag(E->getLocStart(), 3633 diag::err_first_argument_to_va_arg_not_of_type_va_list) 3634 << E->getType().getAsString() << E->getSourceRange(); 3635 3636 // FIXME: Warn if a non-POD type is passed in. 3637 3638 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc); 3639} 3640 3641bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 3642 SourceLocation Loc, 3643 QualType DstType, QualType SrcType, 3644 Expr *SrcExpr, const char *Flavor) { 3645 // Decode the result (notice that AST's are still created for extensions). 3646 bool isInvalid = false; 3647 unsigned DiagKind; 3648 switch (ConvTy) { 3649 default: assert(0 && "Unknown conversion type"); 3650 case Compatible: return false; 3651 case PointerToInt: 3652 DiagKind = diag::ext_typecheck_convert_pointer_int; 3653 break; 3654 case IntToPointer: 3655 DiagKind = diag::ext_typecheck_convert_int_pointer; 3656 break; 3657 case IncompatiblePointer: 3658 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 3659 break; 3660 case FunctionVoidPointer: 3661 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 3662 break; 3663 case CompatiblePointerDiscardsQualifiers: 3664 // If the qualifiers lost were because we were applying the 3665 // (deprecated) C++ conversion from a string literal to a char* 3666 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 3667 // Ideally, this check would be performed in 3668 // CheckPointerTypesForAssignment. However, that would require a 3669 // bit of refactoring (so that the second argument is an 3670 // expression, rather than a type), which should be done as part 3671 // of a larger effort to fix CheckPointerTypesForAssignment for 3672 // C++ semantics. 3673 if (getLangOptions().CPlusPlus && 3674 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 3675 return false; 3676 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 3677 break; 3678 case IntToBlockPointer: 3679 DiagKind = diag::err_int_to_block_pointer; 3680 break; 3681 case IncompatibleBlockPointer: 3682 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer; 3683 break; 3684 case BlockVoidPointer: 3685 DiagKind = diag::ext_typecheck_convert_pointer_void_block; 3686 break; 3687 case IncompatibleObjCQualifiedId: 3688 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 3689 // it can give a more specific diagnostic. 3690 DiagKind = diag::warn_incompatible_qualified_id; 3691 break; 3692 case Incompatible: 3693 DiagKind = diag::err_typecheck_convert_incompatible; 3694 isInvalid = true; 3695 break; 3696 } 3697 3698 Diag(Loc, DiagKind) << DstType.getAsString() << SrcType.getAsString() 3699 << Flavor << SrcExpr->getSourceRange(); 3700 return isInvalid; 3701} 3702