SemaExpr.cpp revision 61000b1f39b1e1742131d8cb90926ec24402a290
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" 24using namespace clang; 25 26//===----------------------------------------------------------------------===// 27// Standard Promotions and Conversions 28//===----------------------------------------------------------------------===// 29 30/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 31void Sema::DefaultFunctionArrayConversion(Expr *&E) { 32 QualType Ty = E->getType(); 33 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 34 35 if (const ReferenceType *ref = Ty->getAsReferenceType()) { 36 ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr] 37 Ty = E->getType(); 38 } 39 if (Ty->isFunctionType()) 40 ImpCastExprToType(E, Context.getPointerType(Ty)); 41 else if (Ty->isArrayType()) { 42 // In C90 mode, arrays only promote to pointers if the array expression is 43 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 44 // type 'array of type' is converted to an expression that has type 'pointer 45 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 46 // that has type 'array of type' ...". The relevant change is "an lvalue" 47 // (C90) to "an expression" (C99). 48 if (getLangOptions().C99 || E->isLvalue(Context) == Expr::LV_Valid) 49 ImpCastExprToType(E, Context.getArrayDecayedType(Ty)); 50 } 51} 52 53/// UsualUnaryConversions - Performs various conversions that are common to most 54/// operators (C99 6.3). The conversions of array and function types are 55/// sometimes surpressed. For example, the array->pointer conversion doesn't 56/// apply if the array is an argument to the sizeof or address (&) operators. 57/// In these instances, this routine should *not* be called. 58Expr *Sema::UsualUnaryConversions(Expr *&Expr) { 59 QualType Ty = Expr->getType(); 60 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 61 62 if (const ReferenceType *Ref = Ty->getAsReferenceType()) { 63 ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr] 64 Ty = Expr->getType(); 65 } 66 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2 67 ImpCastExprToType(Expr, Context.IntTy); 68 else 69 DefaultFunctionArrayConversion(Expr); 70 71 return Expr; 72} 73 74/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 75/// do not have a prototype. Arguments that have type float are promoted to 76/// double. All other argument types are converted by UsualUnaryConversions(). 77void Sema::DefaultArgumentPromotion(Expr *&Expr) { 78 QualType Ty = Expr->getType(); 79 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 80 81 // If this is a 'float' (CVR qualified or typedef) promote to double. 82 if (const BuiltinType *BT = Ty->getAsBuiltinType()) 83 if (BT->getKind() == BuiltinType::Float) 84 return ImpCastExprToType(Expr, Context.DoubleTy); 85 86 UsualUnaryConversions(Expr); 87} 88 89/// UsualArithmeticConversions - Performs various conversions that are common to 90/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 91/// routine returns the first non-arithmetic type found. The client is 92/// responsible for emitting appropriate error diagnostics. 93/// FIXME: verify the conversion rules for "complex int" are consistent with 94/// GCC. 95QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr, 96 bool isCompAssign) { 97 if (!isCompAssign) { 98 UsualUnaryConversions(lhsExpr); 99 UsualUnaryConversions(rhsExpr); 100 } 101 // For conversion purposes, we ignore any qualifiers. 102 // For example, "const float" and "float" are equivalent. 103 QualType lhs = 104 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType(); 105 QualType rhs = 106 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType(); 107 108 // If both types are identical, no conversion is needed. 109 if (lhs == rhs) 110 return lhs; 111 112 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 113 // The caller can deal with this (e.g. pointer + int). 114 if (!lhs->isArithmeticType() || !rhs->isArithmeticType()) 115 return lhs; 116 117 // At this point, we have two different arithmetic types. 118 119 // Handle complex types first (C99 6.3.1.8p1). 120 if (lhs->isComplexType() || rhs->isComplexType()) { 121 // if we have an integer operand, the result is the complex type. 122 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) { 123 // convert the rhs to the lhs complex type. 124 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs); 125 return lhs; 126 } 127 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) { 128 // convert the lhs to the rhs complex type. 129 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); 130 return rhs; 131 } 132 // This handles complex/complex, complex/float, or float/complex. 133 // When both operands are complex, the shorter operand is converted to the 134 // type of the longer, and that is the type of the result. This corresponds 135 // to what is done when combining two real floating-point operands. 136 // The fun begins when size promotion occur across type domains. 137 // From H&S 6.3.4: When one operand is complex and the other is a real 138 // floating-point type, the less precise type is converted, within it's 139 // real or complex domain, to the precision of the other type. For example, 140 // when combining a "long double" with a "double _Complex", the 141 // "double _Complex" is promoted to "long double _Complex". 142 int result = Context.getFloatingTypeOrder(lhs, rhs); 143 144 if (result > 0) { // The left side is bigger, convert rhs. 145 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs); 146 if (!isCompAssign) 147 ImpCastExprToType(rhsExpr, rhs); 148 } else if (result < 0) { // The right side is bigger, convert lhs. 149 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs); 150 if (!isCompAssign) 151 ImpCastExprToType(lhsExpr, lhs); 152 } 153 // At this point, lhs and rhs have the same rank/size. Now, make sure the 154 // domains match. This is a requirement for our implementation, C99 155 // does not require this promotion. 156 if (lhs != rhs) { // Domains don't match, we have complex/float mix. 157 if (lhs->isRealFloatingType()) { // handle "double, _Complex double". 158 if (!isCompAssign) 159 ImpCastExprToType(lhsExpr, rhs); 160 return rhs; 161 } else { // handle "_Complex double, double". 162 if (!isCompAssign) 163 ImpCastExprToType(rhsExpr, lhs); 164 return lhs; 165 } 166 } 167 return lhs; // The domain/size match exactly. 168 } 169 // Now handle "real" floating types (i.e. float, double, long double). 170 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) { 171 // if we have an integer operand, the result is the real floating type. 172 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) { 173 // convert rhs to the lhs floating point type. 174 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs); 175 return lhs; 176 } 177 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) { 178 // convert lhs to the rhs floating point type. 179 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); 180 return rhs; 181 } 182 // We have two real floating types, float/complex combos were handled above. 183 // Convert the smaller operand to the bigger result. 184 int result = Context.getFloatingTypeOrder(lhs, rhs); 185 186 if (result > 0) { // convert the rhs 187 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs); 188 return lhs; 189 } 190 if (result < 0) { // convert the lhs 191 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs 192 return rhs; 193 } 194 assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison"); 195 } 196 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) { 197 // Handle GCC complex int extension. 198 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType(); 199 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType(); 200 201 if (lhsComplexInt && rhsComplexInt) { 202 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(), 203 rhsComplexInt->getElementType()) >= 0) { 204 // convert the rhs 205 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs); 206 return lhs; 207 } 208 if (!isCompAssign) 209 ImpCastExprToType(lhsExpr, rhs); // convert the lhs 210 return rhs; 211 } else if (lhsComplexInt && rhs->isIntegerType()) { 212 // convert the rhs to the lhs complex type. 213 if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs); 214 return lhs; 215 } else if (rhsComplexInt && lhs->isIntegerType()) { 216 // convert the lhs to the rhs complex type. 217 if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); 218 return rhs; 219 } 220 } 221 // Finally, we have two differing integer types. 222 // The rules for this case are in C99 6.3.1.8 223 int compare = Context.getIntegerTypeOrder(lhs, rhs); 224 bool lhsSigned = lhs->isSignedIntegerType(), 225 rhsSigned = rhs->isSignedIntegerType(); 226 QualType destType; 227 if (lhsSigned == rhsSigned) { 228 // Same signedness; use the higher-ranked type 229 destType = compare >= 0 ? lhs : rhs; 230 } else if (compare != (lhsSigned ? 1 : -1)) { 231 // The unsigned type has greater than or equal rank to the 232 // signed type, so use the unsigned type 233 destType = lhsSigned ? rhs : lhs; 234 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) { 235 // The two types are different widths; if we are here, that 236 // means the signed type is larger than the unsigned type, so 237 // use the signed type. 238 destType = lhsSigned ? lhs : rhs; 239 } else { 240 // The signed type is higher-ranked than the unsigned type, 241 // but isn't actually any bigger (like unsigned int and long 242 // on most 32-bit systems). Use the unsigned type corresponding 243 // to the signed type. 244 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs); 245 } 246 if (!isCompAssign) { 247 ImpCastExprToType(lhsExpr, destType); 248 ImpCastExprToType(rhsExpr, destType); 249 } 250 return destType; 251} 252 253//===----------------------------------------------------------------------===// 254// Semantic Analysis for various Expression Types 255//===----------------------------------------------------------------------===// 256 257 258/// ActOnStringLiteral - The specified tokens were lexed as pasted string 259/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 260/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 261/// multiple tokens. However, the common case is that StringToks points to one 262/// string. 263/// 264Action::ExprResult 265Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) { 266 assert(NumStringToks && "Must have at least one string!"); 267 268 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target); 269 if (Literal.hadError) 270 return ExprResult(true); 271 272 llvm::SmallVector<SourceLocation, 4> StringTokLocs; 273 for (unsigned i = 0; i != NumStringToks; ++i) 274 StringTokLocs.push_back(StringToks[i].getLocation()); 275 276 // Verify that pascal strings aren't too large. 277 if (Literal.Pascal && Literal.GetStringLength() > 256) 278 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long, 279 SourceRange(StringToks[0].getLocation(), 280 StringToks[NumStringToks-1].getLocation())); 281 282 QualType StrTy = Context.CharTy; 283 if (Literal.AnyWide) StrTy = Context.getWCharType(); 284 if (Literal.Pascal) StrTy = Context.UnsignedCharTy; 285 286 // Get an array type for the string, according to C99 6.4.5. This includes 287 // the nul terminator character as well as the string length for pascal 288 // strings. 289 StrTy = Context.getConstantArrayType(StrTy, 290 llvm::APInt(32, Literal.GetStringLength()+1), 291 ArrayType::Normal, 0); 292 293 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 294 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(), 295 Literal.AnyWide, StrTy, 296 StringToks[0].getLocation(), 297 StringToks[NumStringToks-1].getLocation()); 298} 299 300 301/// ActOnIdentifierExpr - The parser read an identifier in expression context, 302/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this 303/// identifier is used in a function call context. 304Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc, 305 IdentifierInfo &II, 306 bool HasTrailingLParen) { 307 // Could be enum-constant, value decl, instance variable, etc. 308 Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S); 309 310 // If this reference is in an Objective-C method, then ivar lookup happens as 311 // well. 312 if (getCurMethodDecl()) { 313 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D); 314 // There are two cases to handle here. 1) scoped lookup could have failed, 315 // in which case we should look for an ivar. 2) scoped lookup could have 316 // found a decl, but that decl is outside the current method (i.e. a global 317 // variable). In these two cases, we do a lookup for an ivar with this 318 // name, if the lookup suceeds, we replace it our current decl. 319 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) { 320 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface(); 321 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) { 322 // FIXME: This should use a new expr for a direct reference, don't turn 323 // this into Self->ivar, just return a BareIVarExpr or something. 324 IdentifierInfo &II = Context.Idents.get("self"); 325 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false); 326 return new ObjCIvarRefExpr(IV, IV->getType(), Loc, 327 static_cast<Expr*>(SelfExpr.Val), true, true); 328 } 329 } 330 // Needed to implement property "super.method" notation. 331 if (SD == 0 && !strcmp(II.getName(), "super")) { 332 QualType T = Context.getPointerType(Context.getObjCInterfaceType( 333 getCurMethodDecl()->getClassInterface())); 334 return new PredefinedExpr(Loc, T, PredefinedExpr::ObjCSuper); 335 } 336 } 337 338 if (D == 0) { 339 // Otherwise, this could be an implicitly declared function reference (legal 340 // in C90, extension in C99). 341 if (HasTrailingLParen && 342 !getLangOptions().CPlusPlus) // Not in C++. 343 D = ImplicitlyDefineFunction(Loc, II, S); 344 else { 345 // If this name wasn't predeclared and if this is not a function call, 346 // diagnose the problem. 347 return Diag(Loc, diag::err_undeclared_var_use, II.getName()); 348 } 349 } 350 351 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 352 // check if referencing an identifier with __attribute__((deprecated)). 353 if (VD->getAttr<DeprecatedAttr>()) 354 Diag(Loc, diag::warn_deprecated, VD->getName()); 355 356 // Only create DeclRefExpr's for valid Decl's. 357 if (VD->isInvalidDecl()) 358 return true; 359 return new DeclRefExpr(VD, VD->getType(), Loc); 360 } 361 362 if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) { 363 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) { 364 if (MD->isStatic()) 365 // "invalid use of member 'x' in static member function" 366 return Diag(Loc, diag::err_invalid_member_use_in_static_method, 367 FD->getName()); 368 if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent()) 369 // "invalid use of nonstatic data member 'x'" 370 return Diag(Loc, diag::err_invalid_non_static_member_use, 371 FD->getName()); 372 373 if (FD->isInvalidDecl()) 374 return true; 375 376 // FIXME: Use DeclRefExpr or a new Expr for a direct CXXField reference. 377 ExprResult ThisExpr = ActOnCXXThis(SourceLocation()); 378 return new MemberExpr(static_cast<Expr*>(ThisExpr.Val), 379 true, FD, Loc, FD->getType()); 380 } 381 382 return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName()); 383 } 384 385 if (isa<TypedefDecl>(D)) 386 return Diag(Loc, diag::err_unexpected_typedef, II.getName()); 387 if (isa<ObjCInterfaceDecl>(D)) 388 return Diag(Loc, diag::err_unexpected_interface, II.getName()); 389 if (isa<NamespaceDecl>(D)) 390 return Diag(Loc, diag::err_unexpected_namespace, II.getName()); 391 392 assert(0 && "Invalid decl"); 393 abort(); 394} 395 396Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, 397 tok::TokenKind Kind) { 398 PredefinedExpr::IdentType IT; 399 400 switch (Kind) { 401 default: assert(0 && "Unknown simple primary expr!"); 402 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 403 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 404 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 405 } 406 407 // Verify that this is in a function context. 408 if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0) 409 return Diag(Loc, diag::err_predef_outside_function); 410 411 // Pre-defined identifiers are of type char[x], where x is the length of the 412 // string. 413 unsigned Length; 414 if (getCurFunctionDecl()) 415 Length = getCurFunctionDecl()->getIdentifier()->getLength(); 416 else 417 Length = getCurMethodDecl()->getSynthesizedMethodSize(); 418 419 llvm::APInt LengthI(32, Length + 1); 420 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const); 421 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 422 return new PredefinedExpr(Loc, ResTy, IT); 423} 424 425Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) { 426 llvm::SmallString<16> CharBuffer; 427 CharBuffer.resize(Tok.getLength()); 428 const char *ThisTokBegin = &CharBuffer[0]; 429 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin); 430 431 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 432 Tok.getLocation(), PP); 433 if (Literal.hadError()) 434 return ExprResult(true); 435 436 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy; 437 438 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type, 439 Tok.getLocation()); 440} 441 442Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) { 443 // fast path for a single digit (which is quite common). A single digit 444 // cannot have a trigraph, escaped newline, radix prefix, or type suffix. 445 if (Tok.getLength() == 1) { 446 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation()); 447 448 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy)); 449 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'), 450 Context.IntTy, 451 Tok.getLocation())); 452 } 453 llvm::SmallString<512> IntegerBuffer; 454 IntegerBuffer.resize(Tok.getLength()); 455 const char *ThisTokBegin = &IntegerBuffer[0]; 456 457 // Get the spelling of the token, which eliminates trigraphs, etc. 458 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin); 459 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 460 Tok.getLocation(), PP); 461 if (Literal.hadError) 462 return ExprResult(true); 463 464 Expr *Res; 465 466 if (Literal.isFloatingLiteral()) { 467 QualType Ty; 468 if (Literal.isFloat) 469 Ty = Context.FloatTy; 470 else if (!Literal.isLong) 471 Ty = Context.DoubleTy; 472 else 473 Ty = Context.LongDoubleTy; 474 475 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty); 476 477 // isExact will be set by GetFloatValue(). 478 bool isExact = false; 479 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact, 480 Ty, Tok.getLocation()); 481 482 } else if (!Literal.isIntegerLiteral()) { 483 return ExprResult(true); 484 } else { 485 QualType Ty; 486 487 // long long is a C99 feature. 488 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x && 489 Literal.isLongLong) 490 Diag(Tok.getLocation(), diag::ext_longlong); 491 492 // Get the value in the widest-possible width. 493 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0); 494 495 if (Literal.GetIntegerValue(ResultVal)) { 496 // If this value didn't fit into uintmax_t, warn and force to ull. 497 Diag(Tok.getLocation(), diag::warn_integer_too_large); 498 Ty = Context.UnsignedLongLongTy; 499 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 500 "long long is not intmax_t?"); 501 } else { 502 // If this value fits into a ULL, try to figure out what else it fits into 503 // according to the rules of C99 6.4.4.1p5. 504 505 // Octal, Hexadecimal, and integers with a U suffix are allowed to 506 // be an unsigned int. 507 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 508 509 // Check from smallest to largest, picking the smallest type we can. 510 unsigned Width = 0; 511 if (!Literal.isLong && !Literal.isLongLong) { 512 // Are int/unsigned possibilities? 513 unsigned IntSize = Context.Target.getIntWidth(); 514 515 // Does it fit in a unsigned int? 516 if (ResultVal.isIntN(IntSize)) { 517 // Does it fit in a signed int? 518 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 519 Ty = Context.IntTy; 520 else if (AllowUnsigned) 521 Ty = Context.UnsignedIntTy; 522 Width = IntSize; 523 } 524 } 525 526 // Are long/unsigned long possibilities? 527 if (Ty.isNull() && !Literal.isLongLong) { 528 unsigned LongSize = Context.Target.getLongWidth(); 529 530 // Does it fit in a unsigned long? 531 if (ResultVal.isIntN(LongSize)) { 532 // Does it fit in a signed long? 533 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 534 Ty = Context.LongTy; 535 else if (AllowUnsigned) 536 Ty = Context.UnsignedLongTy; 537 Width = LongSize; 538 } 539 } 540 541 // Finally, check long long if needed. 542 if (Ty.isNull()) { 543 unsigned LongLongSize = Context.Target.getLongLongWidth(); 544 545 // Does it fit in a unsigned long long? 546 if (ResultVal.isIntN(LongLongSize)) { 547 // Does it fit in a signed long long? 548 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0) 549 Ty = Context.LongLongTy; 550 else if (AllowUnsigned) 551 Ty = Context.UnsignedLongLongTy; 552 Width = LongLongSize; 553 } 554 } 555 556 // If we still couldn't decide a type, we probably have something that 557 // does not fit in a signed long long, but has no U suffix. 558 if (Ty.isNull()) { 559 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 560 Ty = Context.UnsignedLongLongTy; 561 Width = Context.Target.getLongLongWidth(); 562 } 563 564 if (ResultVal.getBitWidth() != Width) 565 ResultVal.trunc(Width); 566 } 567 568 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation()); 569 } 570 571 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 572 if (Literal.isImaginary) 573 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType())); 574 575 return Res; 576} 577 578Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, 579 ExprTy *Val) { 580 Expr *E = (Expr *)Val; 581 assert((E != 0) && "ActOnParenExpr() missing expr"); 582 return new ParenExpr(L, R, E); 583} 584 585/// The UsualUnaryConversions() function is *not* called by this routine. 586/// See C99 6.3.2.1p[2-4] for more details. 587QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType, 588 SourceLocation OpLoc, 589 const SourceRange &ExprRange, 590 bool isSizeof) { 591 // C99 6.5.3.4p1: 592 if (isa<FunctionType>(exprType) && isSizeof) 593 // alignof(function) is allowed. 594 Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange); 595 else if (exprType->isVoidType()) 596 Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof", 597 ExprRange); 598 else if (exprType->isIncompleteType()) { 599 Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type : 600 diag::err_alignof_incomplete_type, 601 exprType.getAsString(), ExprRange); 602 return QualType(); // error 603 } 604 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 605 return Context.getSizeType(); 606} 607 608Action::ExprResult Sema:: 609ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof, 610 SourceLocation LPLoc, TypeTy *Ty, 611 SourceLocation RPLoc) { 612 // If error parsing type, ignore. 613 if (Ty == 0) return true; 614 615 // Verify that this is a valid expression. 616 QualType ArgTy = QualType::getFromOpaquePtr(Ty); 617 618 QualType resultType = 619 CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof); 620 621 if (resultType.isNull()) 622 return true; 623 return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc); 624} 625 626QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) { 627 DefaultFunctionArrayConversion(V); 628 629 // These operators return the element type of a complex type. 630 if (const ComplexType *CT = V->getType()->getAsComplexType()) 631 return CT->getElementType(); 632 633 // Otherwise they pass through real integer and floating point types here. 634 if (V->getType()->isArithmeticType()) 635 return V->getType(); 636 637 // Reject anything else. 638 Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString()); 639 return QualType(); 640} 641 642 643 644Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc, 645 tok::TokenKind Kind, 646 ExprTy *Input) { 647 UnaryOperator::Opcode Opc; 648 switch (Kind) { 649 default: assert(0 && "Unknown unary op!"); 650 case tok::plusplus: Opc = UnaryOperator::PostInc; break; 651 case tok::minusminus: Opc = UnaryOperator::PostDec; break; 652 } 653 QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc); 654 if (result.isNull()) 655 return true; 656 return new UnaryOperator((Expr *)Input, Opc, result, OpLoc); 657} 658 659Action::ExprResult Sema:: 660ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc, 661 ExprTy *Idx, SourceLocation RLoc) { 662 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx); 663 664 // Perform default conversions. 665 DefaultFunctionArrayConversion(LHSExp); 666 DefaultFunctionArrayConversion(RHSExp); 667 668 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 669 670 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 671 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 672 // in the subscript position. As a result, we need to derive the array base 673 // and index from the expression types. 674 Expr *BaseExpr, *IndexExpr; 675 QualType ResultType; 676 if (const PointerType *PTy = LHSTy->getAsPointerType()) { 677 BaseExpr = LHSExp; 678 IndexExpr = RHSExp; 679 // FIXME: need to deal with const... 680 ResultType = PTy->getPointeeType(); 681 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) { 682 // Handle the uncommon case of "123[Ptr]". 683 BaseExpr = RHSExp; 684 IndexExpr = LHSExp; 685 // FIXME: need to deal with const... 686 ResultType = PTy->getPointeeType(); 687 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) { 688 BaseExpr = LHSExp; // vectors: V[123] 689 IndexExpr = RHSExp; 690 691 // Component access limited to variables (reject vec4.rg[1]). 692 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) && 693 !isa<ExtVectorElementExpr>(BaseExpr)) 694 return Diag(LLoc, diag::err_ext_vector_component_access, 695 SourceRange(LLoc, RLoc)); 696 // FIXME: need to deal with const... 697 ResultType = VTy->getElementType(); 698 } else { 699 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value, 700 RHSExp->getSourceRange()); 701 } 702 // C99 6.5.2.1p1 703 if (!IndexExpr->getType()->isIntegerType()) 704 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript, 705 IndexExpr->getSourceRange()); 706 707 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice, 708 // the following check catches trying to index a pointer to a function (e.g. 709 // void (*)(int)) and pointers to incomplete types. Functions are not 710 // objects in C99. 711 if (!ResultType->isObjectType()) 712 return Diag(BaseExpr->getLocStart(), 713 diag::err_typecheck_subscript_not_object, 714 BaseExpr->getType().getAsString(), BaseExpr->getSourceRange()); 715 716 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc); 717} 718 719QualType Sema:: 720CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc, 721 IdentifierInfo &CompName, SourceLocation CompLoc) { 722 const ExtVectorType *vecType = baseType->getAsExtVectorType(); 723 724 // This flag determines whether or not the component is to be treated as a 725 // special name, or a regular GLSL-style component access. 726 bool SpecialComponent = false; 727 728 // The vector accessor can't exceed the number of elements. 729 const char *compStr = CompName.getName(); 730 if (strlen(compStr) > vecType->getNumElements()) { 731 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length, 732 baseType.getAsString(), SourceRange(CompLoc)); 733 return QualType(); 734 } 735 736 // Check that we've found one of the special components, or that the component 737 // names must come from the same set. 738 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") || 739 !strcmp(compStr, "e") || !strcmp(compStr, "o")) { 740 SpecialComponent = true; 741 } else if (vecType->getPointAccessorIdx(*compStr) != -1) { 742 do 743 compStr++; 744 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1); 745 } else if (vecType->getColorAccessorIdx(*compStr) != -1) { 746 do 747 compStr++; 748 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1); 749 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) { 750 do 751 compStr++; 752 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1); 753 } 754 755 if (!SpecialComponent && *compStr) { 756 // We didn't get to the end of the string. This means the component names 757 // didn't come from the same set *or* we encountered an illegal name. 758 Diag(OpLoc, diag::err_ext_vector_component_name_illegal, 759 std::string(compStr,compStr+1), SourceRange(CompLoc)); 760 return QualType(); 761 } 762 // Each component accessor can't exceed the vector type. 763 compStr = CompName.getName(); 764 while (*compStr) { 765 if (vecType->isAccessorWithinNumElements(*compStr)) 766 compStr++; 767 else 768 break; 769 } 770 if (!SpecialComponent && *compStr) { 771 // We didn't get to the end of the string. This means a component accessor 772 // exceeds the number of elements in the vector. 773 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length, 774 baseType.getAsString(), SourceRange(CompLoc)); 775 return QualType(); 776 } 777 778 // If we have a special component name, verify that the current vector length 779 // is an even number, since all special component names return exactly half 780 // the elements. 781 if (SpecialComponent && (vecType->getNumElements() & 1U)) { 782 return QualType(); 783 } 784 785 // The component accessor looks fine - now we need to compute the actual type. 786 // The vector type is implied by the component accessor. For example, 787 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc. 788 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2. 789 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2 790 : strlen(CompName.getName()); 791 if (CompSize == 1) 792 return vecType->getElementType(); 793 794 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize); 795 // Now look up the TypeDefDecl from the vector type. Without this, 796 // diagostics look bad. We want extended vector types to appear built-in. 797 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) { 798 if (ExtVectorDecls[i]->getUnderlyingType() == VT) 799 return Context.getTypedefType(ExtVectorDecls[i]); 800 } 801 return VT; // should never get here (a typedef type should always be found). 802} 803 804Action::ExprResult Sema:: 805ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc, 806 tok::TokenKind OpKind, SourceLocation MemberLoc, 807 IdentifierInfo &Member) { 808 Expr *BaseExpr = static_cast<Expr *>(Base); 809 assert(BaseExpr && "no record expression"); 810 811 // Perform default conversions. 812 DefaultFunctionArrayConversion(BaseExpr); 813 814 QualType BaseType = BaseExpr->getType(); 815 assert(!BaseType.isNull() && "no type for member expression"); 816 817 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr 818 // must have pointer type, and the accessed type is the pointee. 819 if (OpKind == tok::arrow) { 820 if (const PointerType *PT = BaseType->getAsPointerType()) 821 BaseType = PT->getPointeeType(); 822 else 823 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow, 824 BaseType.getAsString(), BaseExpr->getSourceRange()); 825 } 826 827 // Handle field access to simple records. This also handles access to fields 828 // of the ObjC 'id' struct. 829 if (const RecordType *RTy = BaseType->getAsRecordType()) { 830 RecordDecl *RDecl = RTy->getDecl(); 831 if (RTy->isIncompleteType()) 832 return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(), 833 BaseExpr->getSourceRange()); 834 // The record definition is complete, now make sure the member is valid. 835 FieldDecl *MemberDecl = RDecl->getMember(&Member); 836 if (!MemberDecl) 837 return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(), 838 BaseExpr->getSourceRange()); 839 840 // Figure out the type of the member; see C99 6.5.2.3p3 841 // FIXME: Handle address space modifiers 842 QualType MemberType = MemberDecl->getType(); 843 unsigned combinedQualifiers = 844 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers(); 845 MemberType = MemberType.getQualifiedType(combinedQualifiers); 846 847 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl, 848 MemberLoc, MemberType); 849 } 850 851 // Handle access to Objective-C instance variables, such as "Obj->ivar" and 852 // (*Obj).ivar. 853 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) { 854 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) 855 return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr, 856 OpKind == tok::arrow); 857 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar, 858 IFTy->getDecl()->getName(), Member.getName(), 859 BaseExpr->getSourceRange()); 860 } 861 862 // Handle Objective-C property access, which is "Obj.property" where Obj is a 863 // pointer to a (potentially qualified) interface type. 864 const PointerType *PTy; 865 const ObjCInterfaceType *IFTy; 866 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) && 867 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) { 868 ObjCInterfaceDecl *IFace = IFTy->getDecl(); 869 870 // FIXME: The logic for looking up nullary and unary selectors should be 871 // shared with the code in ActOnInstanceMessage. 872 873 // Before we look for explicit property declarations, we check for 874 // nullary methods (which allow '.' notation). 875 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member); 876 if (ObjCMethodDecl *MD = IFace->lookupInstanceMethod(Sel)) 877 return new ObjCPropertyRefExpr(MD, MD->getResultType(), 878 MemberLoc, BaseExpr); 879 880 // If this reference is in an @implementation, check for 'private' methods. 881 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) { 882 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) 883 if (ObjCImplementationDecl *ImpDecl = 884 ObjCImplementations[ClassDecl->getIdentifier()]) 885 if (ObjCMethodDecl *MD = ImpDecl->getInstanceMethod(Sel)) 886 return new ObjCPropertyRefExpr(MD, MD->getResultType(), 887 MemberLoc, BaseExpr); 888 } 889 890 // FIXME: Need to deal with setter methods that take 1 argument. E.g.: 891 // @interface NSBundle : NSObject {} 892 // - (NSString *)bundlePath; 893 // - (void)setBundlePath:(NSString *)x; 894 // @end 895 // void someMethod() { frameworkBundle.bundlePath = 0; } 896 // 897 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) 898 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr); 899 900 // Lastly, check protocols on qualified interfaces. 901 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(), 902 E = IFTy->qual_end(); I != E; ++I) 903 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) 904 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr); 905 } 906 907 // Handle 'field access' to vectors, such as 'V.xx'. 908 if (BaseType->isExtVectorType() && OpKind == tok::period) { 909 // Component access limited to variables (reject vec4.rg.g). 910 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) && 911 !isa<ExtVectorElementExpr>(BaseExpr)) 912 return Diag(MemberLoc, diag::err_ext_vector_component_access, 913 BaseExpr->getSourceRange()); 914 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc); 915 if (ret.isNull()) 916 return true; 917 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc); 918 } 919 920 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union, 921 BaseType.getAsString(), BaseExpr->getSourceRange()); 922} 923 924/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 925/// This provides the location of the left/right parens and a list of comma 926/// locations. 927Action::ExprResult Sema:: 928ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc, 929 ExprTy **args, unsigned NumArgs, 930 SourceLocation *CommaLocs, SourceLocation RParenLoc) { 931 Expr *Fn = static_cast<Expr *>(fn); 932 Expr **Args = reinterpret_cast<Expr**>(args); 933 assert(Fn && "no function call expression"); 934 FunctionDecl *FDecl = NULL; 935 936 // Promote the function operand. 937 UsualUnaryConversions(Fn); 938 939 // If we're directly calling a function, get the declaration for 940 // that function. 941 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn)) 942 if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr())) 943 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl()); 944 945 // Make the call expr early, before semantic checks. This guarantees cleanup 946 // of arguments and function on error. 947 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs, 948 Context.BoolTy, RParenLoc)); 949 950 // C99 6.5.2.2p1 - "The expression that denotes the called function shall have 951 // type pointer to function". 952 const PointerType *PT = Fn->getType()->getAsPointerType(); 953 if (PT == 0) 954 return Diag(LParenLoc, diag::err_typecheck_call_not_function, 955 Fn->getSourceRange()); 956 const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType(); 957 if (FuncT == 0) 958 return Diag(LParenLoc, diag::err_typecheck_call_not_function, 959 Fn->getSourceRange()); 960 961 // We know the result type of the call, set it. 962 TheCall->setType(FuncT->getResultType()); 963 964 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) { 965 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 966 // assignment, to the types of the corresponding parameter, ... 967 unsigned NumArgsInProto = Proto->getNumArgs(); 968 unsigned NumArgsToCheck = NumArgs; 969 970 // If too few arguments are available (and we don't have default 971 // arguments for the remaining parameters), don't make the call. 972 if (NumArgs < NumArgsInProto) { 973 if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) { 974 // Use default arguments for missing arguments 975 NumArgsToCheck = NumArgsInProto; 976 TheCall->setNumArgs(NumArgsInProto); 977 } else 978 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args, 979 Fn->getSourceRange()); 980 } 981 982 // If too many are passed and not variadic, error on the extras and drop 983 // them. 984 if (NumArgs > NumArgsInProto) { 985 if (!Proto->isVariadic()) { 986 Diag(Args[NumArgsInProto]->getLocStart(), 987 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(), 988 SourceRange(Args[NumArgsInProto]->getLocStart(), 989 Args[NumArgs-1]->getLocEnd())); 990 // This deletes the extra arguments. 991 TheCall->setNumArgs(NumArgsInProto); 992 } 993 NumArgsToCheck = NumArgsInProto; 994 } 995 996 // Continue to check argument types (even if we have too few/many args). 997 for (unsigned i = 0; i != NumArgsToCheck; i++) { 998 QualType ProtoArgType = Proto->getArgType(i); 999 1000 Expr *Arg; 1001 if (i < NumArgs) 1002 Arg = Args[i]; 1003 else 1004 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i)); 1005 QualType ArgType = Arg->getType(); 1006 1007 // Compute implicit casts from the operand to the formal argument type. 1008 AssignConvertType ConvTy = 1009 CheckSingleAssignmentConstraints(ProtoArgType, Arg); 1010 TheCall->setArg(i, Arg); 1011 1012 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType, 1013 ArgType, Arg, "passing")) 1014 return true; 1015 } 1016 1017 // If this is a variadic call, handle args passed through "...". 1018 if (Proto->isVariadic()) { 1019 // Promote the arguments (C99 6.5.2.2p7). 1020 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 1021 Expr *Arg = Args[i]; 1022 DefaultArgumentPromotion(Arg); 1023 TheCall->setArg(i, Arg); 1024 } 1025 } 1026 } else { 1027 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!"); 1028 1029 // Promote the arguments (C99 6.5.2.2p6). 1030 for (unsigned i = 0; i != NumArgs; i++) { 1031 Expr *Arg = Args[i]; 1032 DefaultArgumentPromotion(Arg); 1033 TheCall->setArg(i, Arg); 1034 } 1035 } 1036 1037 // Do special checking on direct calls to functions. 1038 if (FDecl) 1039 return CheckFunctionCall(FDecl, TheCall.take()); 1040 1041 return TheCall.take(); 1042} 1043 1044Action::ExprResult Sema:: 1045ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty, 1046 SourceLocation RParenLoc, ExprTy *InitExpr) { 1047 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type"); 1048 QualType literalType = QualType::getFromOpaquePtr(Ty); 1049 // FIXME: put back this assert when initializers are worked out. 1050 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 1051 Expr *literalExpr = static_cast<Expr*>(InitExpr); 1052 1053 if (literalType->isArrayType()) { 1054 if (literalType->isVariableArrayType()) 1055 return Diag(LParenLoc, 1056 diag::err_variable_object_no_init, 1057 SourceRange(LParenLoc, 1058 literalExpr->getSourceRange().getEnd())); 1059 } else if (literalType->isIncompleteType()) { 1060 return Diag(LParenLoc, 1061 diag::err_typecheck_decl_incomplete_type, 1062 literalType.getAsString(), 1063 SourceRange(LParenLoc, 1064 literalExpr->getSourceRange().getEnd())); 1065 } 1066 1067 if (CheckInitializerTypes(literalExpr, literalType)) 1068 return true; 1069 1070 bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl(); 1071 if (isFileScope) { // 6.5.2.5p3 1072 if (CheckForConstantInitializer(literalExpr, literalType)) 1073 return true; 1074 } 1075 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope); 1076} 1077 1078Action::ExprResult Sema:: 1079ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit, 1080 SourceLocation RBraceLoc) { 1081 Expr **InitList = reinterpret_cast<Expr**>(initlist); 1082 1083 // Semantic analysis for initializers is done by ActOnDeclarator() and 1084 // CheckInitializer() - it requires knowledge of the object being intialized. 1085 1086 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc); 1087 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 1088 return E; 1089} 1090 1091bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) { 1092 assert(VectorTy->isVectorType() && "Not a vector type!"); 1093 1094 if (Ty->isVectorType() || Ty->isIntegerType()) { 1095 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 1096 return Diag(R.getBegin(), 1097 Ty->isVectorType() ? 1098 diag::err_invalid_conversion_between_vectors : 1099 diag::err_invalid_conversion_between_vector_and_integer, 1100 VectorTy.getAsString().c_str(), 1101 Ty.getAsString().c_str(), R); 1102 } else 1103 return Diag(R.getBegin(), 1104 diag::err_invalid_conversion_between_vector_and_scalar, 1105 VectorTy.getAsString().c_str(), 1106 Ty.getAsString().c_str(), R); 1107 1108 return false; 1109} 1110 1111Action::ExprResult Sema:: 1112ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty, 1113 SourceLocation RParenLoc, ExprTy *Op) { 1114 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr"); 1115 1116 Expr *castExpr = static_cast<Expr*>(Op); 1117 QualType castType = QualType::getFromOpaquePtr(Ty); 1118 1119 UsualUnaryConversions(castExpr); 1120 1121 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression 1122 // type needs to be scalar. 1123 if (castType->isVoidType()) { 1124 // Cast to void allows any expr type. 1125 } else if (!castType->isScalarType() && !castType->isVectorType()) { 1126 // GCC struct/union extension: allow cast to self. 1127 if (Context.getCanonicalType(castType) != 1128 Context.getCanonicalType(castExpr->getType()) || 1129 (!castType->isStructureType() && !castType->isUnionType())) { 1130 // Reject any other conversions to non-scalar types. 1131 return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar, 1132 castType.getAsString(), castExpr->getSourceRange()); 1133 } 1134 1135 // accept this, but emit an ext-warn. 1136 Diag(LParenLoc, diag::ext_typecheck_cast_nonscalar, 1137 castType.getAsString(), castExpr->getSourceRange()); 1138 } else if (!castExpr->getType()->isScalarType() && 1139 !castExpr->getType()->isVectorType()) { 1140 return Diag(castExpr->getLocStart(), 1141 diag::err_typecheck_expect_scalar_operand, 1142 castExpr->getType().getAsString(),castExpr->getSourceRange()); 1143 } else if (castExpr->getType()->isVectorType()) { 1144 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc), 1145 castExpr->getType(), castType)) 1146 return true; 1147 } else if (castType->isVectorType()) { 1148 if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc), 1149 castType, castExpr->getType())) 1150 return true; 1151 } 1152 return new CastExpr(castType, castExpr, LParenLoc); 1153} 1154 1155/// Note that lex is not null here, even if this is the gnu "x ?: y" extension. 1156/// In that case, lex = cond. 1157inline QualType Sema::CheckConditionalOperands( // C99 6.5.15 1158 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) { 1159 UsualUnaryConversions(cond); 1160 UsualUnaryConversions(lex); 1161 UsualUnaryConversions(rex); 1162 QualType condT = cond->getType(); 1163 QualType lexT = lex->getType(); 1164 QualType rexT = rex->getType(); 1165 1166 // first, check the condition. 1167 if (!condT->isScalarType()) { // C99 6.5.15p2 1168 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar, 1169 condT.getAsString()); 1170 return QualType(); 1171 } 1172 1173 // Now check the two expressions. 1174 1175 // If both operands have arithmetic type, do the usual arithmetic conversions 1176 // to find a common type: C99 6.5.15p3,5. 1177 if (lexT->isArithmeticType() && rexT->isArithmeticType()) { 1178 UsualArithmeticConversions(lex, rex); 1179 return lex->getType(); 1180 } 1181 1182 // If both operands are the same structure or union type, the result is that 1183 // type. 1184 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3 1185 if (const RecordType *RHSRT = rexT->getAsRecordType()) 1186 if (LHSRT->getDecl() == RHSRT->getDecl()) 1187 // "If both the operands have structure or union type, the result has 1188 // that type." This implies that CV qualifiers are dropped. 1189 return lexT.getUnqualifiedType(); 1190 } 1191 1192 // C99 6.5.15p5: "If both operands have void type, the result has void type." 1193 // The following || allows only one side to be void (a GCC-ism). 1194 if (lexT->isVoidType() || rexT->isVoidType()) { 1195 if (!lexT->isVoidType()) 1196 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void, 1197 rex->getSourceRange()); 1198 if (!rexT->isVoidType()) 1199 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void, 1200 lex->getSourceRange()); 1201 ImpCastExprToType(lex, Context.VoidTy); 1202 ImpCastExprToType(rex, Context.VoidTy); 1203 return Context.VoidTy; 1204 } 1205 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 1206 // the type of the other operand." 1207 if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) { 1208 ImpCastExprToType(rex, lexT); // promote the null to a pointer. 1209 return lexT; 1210 } 1211 if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) { 1212 ImpCastExprToType(lex, rexT); // promote the null to a pointer. 1213 return rexT; 1214 } 1215 // Handle the case where both operands are pointers before we handle null 1216 // pointer constants in case both operands are null pointer constants. 1217 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6 1218 if (const PointerType *RHSPT = rexT->getAsPointerType()) { 1219 // get the "pointed to" types 1220 QualType lhptee = LHSPT->getPointeeType(); 1221 QualType rhptee = RHSPT->getPointeeType(); 1222 1223 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 1224 if (lhptee->isVoidType() && 1225 rhptee->isIncompleteOrObjectType()) { 1226 // Figure out necessary qualifiers (C99 6.5.15p6) 1227 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers()); 1228 QualType destType = Context.getPointerType(destPointee); 1229 ImpCastExprToType(lex, destType); // add qualifiers if necessary 1230 ImpCastExprToType(rex, destType); // promote to void* 1231 return destType; 1232 } 1233 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 1234 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers()); 1235 QualType destType = Context.getPointerType(destPointee); 1236 ImpCastExprToType(lex, destType); // add qualifiers if necessary 1237 ImpCastExprToType(rex, destType); // promote to void* 1238 return destType; 1239 } 1240 1241 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 1242 rhptee.getUnqualifiedType())) { 1243 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers, 1244 lexT.getAsString(), rexT.getAsString(), 1245 lex->getSourceRange(), rex->getSourceRange()); 1246 // In this situation, we assume void* type. No especially good 1247 // reason, but this is what gcc does, and we do have to pick 1248 // to get a consistent AST. 1249 QualType voidPtrTy = Context.getPointerType(Context.VoidTy); 1250 ImpCastExprToType(lex, voidPtrTy); 1251 ImpCastExprToType(rex, voidPtrTy); 1252 return voidPtrTy; 1253 } 1254 // The pointer types are compatible. 1255 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to 1256 // differently qualified versions of compatible types, the result type is 1257 // a pointer to an appropriately qualified version of the *composite* 1258 // type. 1259 // FIXME: Need to calculate the composite type. 1260 // FIXME: Need to add qualifiers 1261 QualType compositeType = lexT; 1262 ImpCastExprToType(lex, compositeType); 1263 ImpCastExprToType(rex, compositeType); 1264 return compositeType; 1265 } 1266 } 1267 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type 1268 // evaluates to "struct objc_object *" (and is handled above when comparing 1269 // id with statically typed objects). FIXME: Do we need an ImpCastExprToType? 1270 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) { 1271 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true)) 1272 return Context.getObjCIdType(); 1273 } 1274 // Otherwise, the operands are not compatible. 1275 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands, 1276 lexT.getAsString(), rexT.getAsString(), 1277 lex->getSourceRange(), rex->getSourceRange()); 1278 return QualType(); 1279} 1280 1281/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 1282/// in the case of a the GNU conditional expr extension. 1283Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 1284 SourceLocation ColonLoc, 1285 ExprTy *Cond, ExprTy *LHS, 1286 ExprTy *RHS) { 1287 Expr *CondExpr = (Expr *) Cond; 1288 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS; 1289 1290 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 1291 // was the condition. 1292 bool isLHSNull = LHSExpr == 0; 1293 if (isLHSNull) 1294 LHSExpr = CondExpr; 1295 1296 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, 1297 RHSExpr, QuestionLoc); 1298 if (result.isNull()) 1299 return true; 1300 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr, 1301 RHSExpr, result); 1302} 1303 1304 1305// CheckPointerTypesForAssignment - This is a very tricky routine (despite 1306// being closely modeled after the C99 spec:-). The odd characteristic of this 1307// routine is it effectively iqnores the qualifiers on the top level pointee. 1308// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 1309// FIXME: add a couple examples in this comment. 1310Sema::AssignConvertType 1311Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) { 1312 QualType lhptee, rhptee; 1313 1314 // get the "pointed to" type (ignoring qualifiers at the top level) 1315 lhptee = lhsType->getAsPointerType()->getPointeeType(); 1316 rhptee = rhsType->getAsPointerType()->getPointeeType(); 1317 1318 // make sure we operate on the canonical type 1319 lhptee = Context.getCanonicalType(lhptee); 1320 rhptee = Context.getCanonicalType(rhptee); 1321 1322 AssignConvertType ConvTy = Compatible; 1323 1324 // C99 6.5.16.1p1: This following citation is common to constraints 1325 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 1326 // qualifiers of the type *pointed to* by the right; 1327 // FIXME: Handle ASQualType 1328 if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) != 1329 rhptee.getCVRQualifiers()) 1330 ConvTy = CompatiblePointerDiscardsQualifiers; 1331 1332 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 1333 // incomplete type and the other is a pointer to a qualified or unqualified 1334 // version of void... 1335 if (lhptee->isVoidType()) { 1336 if (rhptee->isIncompleteOrObjectType()) 1337 return ConvTy; 1338 1339 // As an extension, we allow cast to/from void* to function pointer. 1340 assert(rhptee->isFunctionType()); 1341 return FunctionVoidPointer; 1342 } 1343 1344 if (rhptee->isVoidType()) { 1345 if (lhptee->isIncompleteOrObjectType()) 1346 return ConvTy; 1347 1348 // As an extension, we allow cast to/from void* to function pointer. 1349 assert(lhptee->isFunctionType()); 1350 return FunctionVoidPointer; 1351 } 1352 1353 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 1354 // unqualified versions of compatible types, ... 1355 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(), 1356 rhptee.getUnqualifiedType())) 1357 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers 1358 return ConvTy; 1359} 1360 1361/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 1362/// has code to accommodate several GCC extensions when type checking 1363/// pointers. Here are some objectionable examples that GCC considers warnings: 1364/// 1365/// int a, *pint; 1366/// short *pshort; 1367/// struct foo *pfoo; 1368/// 1369/// pint = pshort; // warning: assignment from incompatible pointer type 1370/// a = pint; // warning: assignment makes integer from pointer without a cast 1371/// pint = a; // warning: assignment makes pointer from integer without a cast 1372/// pint = pfoo; // warning: assignment from incompatible pointer type 1373/// 1374/// As a result, the code for dealing with pointers is more complex than the 1375/// C99 spec dictates. 1376/// 1377Sema::AssignConvertType 1378Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) { 1379 // Get canonical types. We're not formatting these types, just comparing 1380 // them. 1381 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType(); 1382 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType(); 1383 1384 if (lhsType == rhsType) 1385 return Compatible; // Common case: fast path an exact match. 1386 1387 if (lhsType->isReferenceType() || rhsType->isReferenceType()) { 1388 if (Context.typesAreCompatible(lhsType, rhsType)) 1389 return Compatible; 1390 return Incompatible; 1391 } 1392 1393 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) { 1394 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false)) 1395 return Compatible; 1396 // Relax integer conversions like we do for pointers below. 1397 if (rhsType->isIntegerType()) 1398 return IntToPointer; 1399 if (lhsType->isIntegerType()) 1400 return PointerToInt; 1401 return Incompatible; 1402 } 1403 1404 if (lhsType->isVectorType() || rhsType->isVectorType()) { 1405 // For ExtVector, allow vector splats; float -> <n x float> 1406 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) 1407 if (LV->getElementType() == rhsType) 1408 return Compatible; 1409 1410 // If we are allowing lax vector conversions, and LHS and RHS are both 1411 // vectors, the total size only needs to be the same. This is a bitcast; 1412 // no bits are changed but the result type is different. 1413 if (getLangOptions().LaxVectorConversions && 1414 lhsType->isVectorType() && rhsType->isVectorType()) { 1415 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType)) 1416 return Compatible; 1417 } 1418 return Incompatible; 1419 } 1420 1421 if (lhsType->isArithmeticType() && rhsType->isArithmeticType()) 1422 return Compatible; 1423 1424 if (isa<PointerType>(lhsType)) { 1425 if (rhsType->isIntegerType()) 1426 return IntToPointer; 1427 1428 if (isa<PointerType>(rhsType)) 1429 return CheckPointerTypesForAssignment(lhsType, rhsType); 1430 return Incompatible; 1431 } 1432 1433 if (isa<PointerType>(rhsType)) { 1434 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer. 1435 if (lhsType == Context.BoolTy) 1436 return Compatible; 1437 1438 if (lhsType->isIntegerType()) 1439 return PointerToInt; 1440 1441 if (isa<PointerType>(lhsType)) 1442 return CheckPointerTypesForAssignment(lhsType, rhsType); 1443 return Incompatible; 1444 } 1445 1446 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) { 1447 if (Context.typesAreCompatible(lhsType, rhsType)) 1448 return Compatible; 1449 } 1450 return Incompatible; 1451} 1452 1453Sema::AssignConvertType 1454Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) { 1455 // C99 6.5.16.1p1: the left operand is a pointer and the right is 1456 // a null pointer constant. 1457 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType()) 1458 && rExpr->isNullPointerConstant(Context)) { 1459 ImpCastExprToType(rExpr, lhsType); 1460 return Compatible; 1461 } 1462 // This check seems unnatural, however it is necessary to ensure the proper 1463 // conversion of functions/arrays. If the conversion were done for all 1464 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary 1465 // expressions that surpress this implicit conversion (&, sizeof). 1466 // 1467 // Suppress this for references: C99 8.5.3p5. FIXME: revisit when references 1468 // are better understood. 1469 if (!lhsType->isReferenceType()) 1470 DefaultFunctionArrayConversion(rExpr); 1471 1472 Sema::AssignConvertType result = 1473 CheckAssignmentConstraints(lhsType, rExpr->getType()); 1474 1475 // C99 6.5.16.1p2: The value of the right operand is converted to the 1476 // type of the assignment expression. 1477 if (rExpr->getType() != lhsType) 1478 ImpCastExprToType(rExpr, lhsType); 1479 return result; 1480} 1481 1482Sema::AssignConvertType 1483Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) { 1484 return CheckAssignmentConstraints(lhsType, rhsType); 1485} 1486 1487QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) { 1488 Diag(loc, diag::err_typecheck_invalid_operands, 1489 lex->getType().getAsString(), rex->getType().getAsString(), 1490 lex->getSourceRange(), rex->getSourceRange()); 1491 return QualType(); 1492} 1493 1494inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex, 1495 Expr *&rex) { 1496 // For conversion purposes, we ignore any qualifiers. 1497 // For example, "const float" and "float" are equivalent. 1498 QualType lhsType = 1499 Context.getCanonicalType(lex->getType()).getUnqualifiedType(); 1500 QualType rhsType = 1501 Context.getCanonicalType(rex->getType()).getUnqualifiedType(); 1502 1503 // If the vector types are identical, return. 1504 if (lhsType == rhsType) 1505 return lhsType; 1506 1507 // Handle the case of a vector & extvector type of the same size and element 1508 // type. It would be nice if we only had one vector type someday. 1509 if (getLangOptions().LaxVectorConversions) 1510 if (const VectorType *LV = lhsType->getAsVectorType()) 1511 if (const VectorType *RV = rhsType->getAsVectorType()) 1512 if (LV->getElementType() == RV->getElementType() && 1513 LV->getNumElements() == RV->getNumElements()) 1514 return lhsType->isExtVectorType() ? lhsType : rhsType; 1515 1516 // If the lhs is an extended vector and the rhs is a scalar of the same type 1517 // or a literal, promote the rhs to the vector type. 1518 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) { 1519 QualType eltType = V->getElementType(); 1520 1521 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) || 1522 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) || 1523 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) { 1524 ImpCastExprToType(rex, lhsType); 1525 return lhsType; 1526 } 1527 } 1528 1529 // If the rhs is an extended vector and the lhs is a scalar of the same type, 1530 // promote the lhs to the vector type. 1531 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) { 1532 QualType eltType = V->getElementType(); 1533 1534 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) || 1535 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) || 1536 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) { 1537 ImpCastExprToType(lex, rhsType); 1538 return rhsType; 1539 } 1540 } 1541 1542 // You cannot convert between vector values of different size. 1543 Diag(loc, diag::err_typecheck_vector_not_convertable, 1544 lex->getType().getAsString(), rex->getType().getAsString(), 1545 lex->getSourceRange(), rex->getSourceRange()); 1546 return QualType(); 1547} 1548 1549inline QualType Sema::CheckMultiplyDivideOperands( 1550 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) 1551{ 1552 QualType lhsType = lex->getType(), rhsType = rex->getType(); 1553 1554 if (lhsType->isVectorType() || rhsType->isVectorType()) 1555 return CheckVectorOperands(loc, lex, rex); 1556 1557 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 1558 1559 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 1560 return compType; 1561 return InvalidOperands(loc, lex, rex); 1562} 1563 1564inline QualType Sema::CheckRemainderOperands( 1565 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) 1566{ 1567 QualType lhsType = lex->getType(), rhsType = rex->getType(); 1568 1569 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 1570 1571 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 1572 return compType; 1573 return InvalidOperands(loc, lex, rex); 1574} 1575 1576inline QualType Sema::CheckAdditionOperands( // C99 6.5.6 1577 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) 1578{ 1579 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 1580 return CheckVectorOperands(loc, lex, rex); 1581 1582 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 1583 1584 // handle the common case first (both operands are arithmetic). 1585 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 1586 return compType; 1587 1588 // Put any potential pointer into PExp 1589 Expr* PExp = lex, *IExp = rex; 1590 if (IExp->getType()->isPointerType()) 1591 std::swap(PExp, IExp); 1592 1593 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) { 1594 if (IExp->getType()->isIntegerType()) { 1595 // Check for arithmetic on pointers to incomplete types 1596 if (!PTy->getPointeeType()->isObjectType()) { 1597 if (PTy->getPointeeType()->isVoidType()) { 1598 Diag(loc, diag::ext_gnu_void_ptr, 1599 lex->getSourceRange(), rex->getSourceRange()); 1600 } else { 1601 Diag(loc, diag::err_typecheck_arithmetic_incomplete_type, 1602 lex->getType().getAsString(), lex->getSourceRange()); 1603 return QualType(); 1604 } 1605 } 1606 return PExp->getType(); 1607 } 1608 } 1609 1610 return InvalidOperands(loc, lex, rex); 1611} 1612 1613// C99 6.5.6 1614QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex, 1615 SourceLocation loc, bool isCompAssign) { 1616 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 1617 return CheckVectorOperands(loc, lex, rex); 1618 1619 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 1620 1621 // Enforce type constraints: C99 6.5.6p3. 1622 1623 // Handle the common case first (both operands are arithmetic). 1624 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 1625 return compType; 1626 1627 // Either ptr - int or ptr - ptr. 1628 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) { 1629 QualType lpointee = LHSPTy->getPointeeType(); 1630 1631 // The LHS must be an object type, not incomplete, function, etc. 1632 if (!lpointee->isObjectType()) { 1633 // Handle the GNU void* extension. 1634 if (lpointee->isVoidType()) { 1635 Diag(loc, diag::ext_gnu_void_ptr, 1636 lex->getSourceRange(), rex->getSourceRange()); 1637 } else { 1638 Diag(loc, diag::err_typecheck_sub_ptr_object, 1639 lex->getType().getAsString(), lex->getSourceRange()); 1640 return QualType(); 1641 } 1642 } 1643 1644 // The result type of a pointer-int computation is the pointer type. 1645 if (rex->getType()->isIntegerType()) 1646 return lex->getType(); 1647 1648 // Handle pointer-pointer subtractions. 1649 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) { 1650 QualType rpointee = RHSPTy->getPointeeType(); 1651 1652 // RHS must be an object type, unless void (GNU). 1653 if (!rpointee->isObjectType()) { 1654 // Handle the GNU void* extension. 1655 if (rpointee->isVoidType()) { 1656 if (!lpointee->isVoidType()) 1657 Diag(loc, diag::ext_gnu_void_ptr, 1658 lex->getSourceRange(), rex->getSourceRange()); 1659 } else { 1660 Diag(loc, diag::err_typecheck_sub_ptr_object, 1661 rex->getType().getAsString(), rex->getSourceRange()); 1662 return QualType(); 1663 } 1664 } 1665 1666 // Pointee types must be compatible. 1667 if (!Context.typesAreCompatible(lpointee.getUnqualifiedType(), 1668 rpointee.getUnqualifiedType())) { 1669 Diag(loc, diag::err_typecheck_sub_ptr_compatible, 1670 lex->getType().getAsString(), rex->getType().getAsString(), 1671 lex->getSourceRange(), rex->getSourceRange()); 1672 return QualType(); 1673 } 1674 1675 return Context.getPointerDiffType(); 1676 } 1677 } 1678 1679 return InvalidOperands(loc, lex, rex); 1680} 1681 1682// C99 6.5.7 1683QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc, 1684 bool isCompAssign) { 1685 // C99 6.5.7p2: Each of the operands shall have integer type. 1686 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType()) 1687 return InvalidOperands(loc, lex, rex); 1688 1689 // Shifts don't perform usual arithmetic conversions, they just do integer 1690 // promotions on each operand. C99 6.5.7p3 1691 if (!isCompAssign) 1692 UsualUnaryConversions(lex); 1693 UsualUnaryConversions(rex); 1694 1695 // "The type of the result is that of the promoted left operand." 1696 return lex->getType(); 1697} 1698 1699// C99 6.5.8 1700QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc, 1701 bool isRelational) { 1702 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 1703 return CheckVectorCompareOperands(lex, rex, loc, isRelational); 1704 1705 // C99 6.5.8p3 / C99 6.5.9p4 1706 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType()) 1707 UsualArithmeticConversions(lex, rex); 1708 else { 1709 UsualUnaryConversions(lex); 1710 UsualUnaryConversions(rex); 1711 } 1712 QualType lType = lex->getType(); 1713 QualType rType = rex->getType(); 1714 1715 // For non-floating point types, check for self-comparisons of the form 1716 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 1717 // often indicate logic errors in the program. 1718 if (!lType->isFloatingType()) { 1719 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens())) 1720 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens())) 1721 if (DRL->getDecl() == DRR->getDecl()) 1722 Diag(loc, diag::warn_selfcomparison); 1723 } 1724 1725 if (isRelational) { 1726 if (lType->isRealType() && rType->isRealType()) 1727 return Context.IntTy; 1728 } else { 1729 // Check for comparisons of floating point operands using != and ==. 1730 if (lType->isFloatingType()) { 1731 assert (rType->isFloatingType()); 1732 CheckFloatComparison(loc,lex,rex); 1733 } 1734 1735 if (lType->isArithmeticType() && rType->isArithmeticType()) 1736 return Context.IntTy; 1737 } 1738 1739 bool LHSIsNull = lex->isNullPointerConstant(Context); 1740 bool RHSIsNull = rex->isNullPointerConstant(Context); 1741 1742 // All of the following pointer related warnings are GCC extensions, except 1743 // when handling null pointer constants. One day, we can consider making them 1744 // errors (when -pedantic-errors is enabled). 1745 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2 1746 QualType LCanPointeeTy = 1747 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType()); 1748 QualType RCanPointeeTy = 1749 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType()); 1750 1751 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2 1752 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() && 1753 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 1754 RCanPointeeTy.getUnqualifiedType())) { 1755 Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers, 1756 lType.getAsString(), rType.getAsString(), 1757 lex->getSourceRange(), rex->getSourceRange()); 1758 } 1759 ImpCastExprToType(rex, lType); // promote the pointer to pointer 1760 return Context.IntTy; 1761 } 1762 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) { 1763 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) { 1764 ImpCastExprToType(rex, lType); 1765 return Context.IntTy; 1766 } 1767 } 1768 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) && 1769 rType->isIntegerType()) { 1770 if (!RHSIsNull) 1771 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer, 1772 lType.getAsString(), rType.getAsString(), 1773 lex->getSourceRange(), rex->getSourceRange()); 1774 ImpCastExprToType(rex, lType); // promote the integer to pointer 1775 return Context.IntTy; 1776 } 1777 if (lType->isIntegerType() && 1778 (rType->isPointerType() || rType->isObjCQualifiedIdType())) { 1779 if (!LHSIsNull) 1780 Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer, 1781 lType.getAsString(), rType.getAsString(), 1782 lex->getSourceRange(), rex->getSourceRange()); 1783 ImpCastExprToType(lex, rType); // promote the integer to pointer 1784 return Context.IntTy; 1785 } 1786 return InvalidOperands(loc, lex, rex); 1787} 1788 1789/// CheckVectorCompareOperands - vector comparisons are a clang extension that 1790/// operates on extended vector types. Instead of producing an IntTy result, 1791/// like a scalar comparison, a vector comparison produces a vector of integer 1792/// types. 1793QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex, 1794 SourceLocation loc, 1795 bool isRelational) { 1796 // Check to make sure we're operating on vectors of the same type and width, 1797 // Allowing one side to be a scalar of element type. 1798 QualType vType = CheckVectorOperands(loc, lex, rex); 1799 if (vType.isNull()) 1800 return vType; 1801 1802 QualType lType = lex->getType(); 1803 QualType rType = rex->getType(); 1804 1805 // For non-floating point types, check for self-comparisons of the form 1806 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 1807 // often indicate logic errors in the program. 1808 if (!lType->isFloatingType()) { 1809 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens())) 1810 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens())) 1811 if (DRL->getDecl() == DRR->getDecl()) 1812 Diag(loc, diag::warn_selfcomparison); 1813 } 1814 1815 // Check for comparisons of floating point operands using != and ==. 1816 if (!isRelational && lType->isFloatingType()) { 1817 assert (rType->isFloatingType()); 1818 CheckFloatComparison(loc,lex,rex); 1819 } 1820 1821 // Return the type for the comparison, which is the same as vector type for 1822 // integer vectors, or an integer type of identical size and number of 1823 // elements for floating point vectors. 1824 if (lType->isIntegerType()) 1825 return lType; 1826 1827 const VectorType *VTy = lType->getAsVectorType(); 1828 1829 // FIXME: need to deal with non-32b int / non-64b long long 1830 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 1831 if (TypeSize == 32) { 1832 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 1833 } 1834 assert(TypeSize == 64 && "Unhandled vector element size in vector compare"); 1835 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 1836} 1837 1838inline QualType Sema::CheckBitwiseOperands( 1839 Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign) 1840{ 1841 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) 1842 return CheckVectorOperands(loc, lex, rex); 1843 1844 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign); 1845 1846 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType()) 1847 return compType; 1848 return InvalidOperands(loc, lex, rex); 1849} 1850 1851inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 1852 Expr *&lex, Expr *&rex, SourceLocation loc) 1853{ 1854 UsualUnaryConversions(lex); 1855 UsualUnaryConversions(rex); 1856 1857 if (lex->getType()->isScalarType() && rex->getType()->isScalarType()) 1858 return Context.IntTy; 1859 return InvalidOperands(loc, lex, rex); 1860} 1861 1862inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1 1863 Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType) 1864{ 1865 QualType lhsType = lex->getType(); 1866 QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType; 1867 Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context); 1868 1869 switch (mlval) { // C99 6.5.16p2 1870 case Expr::MLV_Valid: 1871 break; 1872 case Expr::MLV_ConstQualified: 1873 Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange()); 1874 return QualType(); 1875 case Expr::MLV_ArrayType: 1876 Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue, 1877 lhsType.getAsString(), lex->getSourceRange()); 1878 return QualType(); 1879 case Expr::MLV_NotObjectType: 1880 Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue, 1881 lhsType.getAsString(), lex->getSourceRange()); 1882 return QualType(); 1883 case Expr::MLV_InvalidExpression: 1884 Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue, 1885 lex->getSourceRange()); 1886 return QualType(); 1887 case Expr::MLV_IncompleteType: 1888 case Expr::MLV_IncompleteVoidType: 1889 Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue, 1890 lhsType.getAsString(), lex->getSourceRange()); 1891 return QualType(); 1892 case Expr::MLV_DuplicateVectorComponents: 1893 Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue, 1894 lex->getSourceRange()); 1895 return QualType(); 1896 } 1897 1898 AssignConvertType ConvTy; 1899 if (compoundType.isNull()) 1900 ConvTy = CheckSingleAssignmentConstraints(lhsType, rex); 1901 else 1902 ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType); 1903 1904 if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType, 1905 rex, "assigning")) 1906 return QualType(); 1907 1908 // C99 6.5.16p3: The type of an assignment expression is the type of the 1909 // left operand unless the left operand has qualified type, in which case 1910 // it is the unqualified version of the type of the left operand. 1911 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 1912 // is converted to the type of the assignment expression (above). 1913 // C++ 5.17p1: the type of the assignment expression is that of its left 1914 // oprdu. 1915 return lhsType.getUnqualifiedType(); 1916} 1917 1918inline QualType Sema::CheckCommaOperands( // C99 6.5.17 1919 Expr *&lex, Expr *&rex, SourceLocation loc) { 1920 1921 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions. 1922 DefaultFunctionArrayConversion(rex); 1923 return rex->getType(); 1924} 1925 1926/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 1927/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 1928QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) { 1929 QualType resType = op->getType(); 1930 assert(!resType.isNull() && "no type for increment/decrement expression"); 1931 1932 // C99 6.5.2.4p1: We allow complex as a GCC extension. 1933 if (const PointerType *pt = resType->getAsPointerType()) { 1934 if (pt->getPointeeType()->isVoidType()) { 1935 Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange()); 1936 } else if (!pt->getPointeeType()->isObjectType()) { 1937 // C99 6.5.2.4p2, 6.5.6p2 1938 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type, 1939 resType.getAsString(), op->getSourceRange()); 1940 return QualType(); 1941 } 1942 } else if (!resType->isRealType()) { 1943 if (resType->isComplexType()) 1944 // C99 does not support ++/-- on complex types. 1945 Diag(OpLoc, diag::ext_integer_increment_complex, 1946 resType.getAsString(), op->getSourceRange()); 1947 else { 1948 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement, 1949 resType.getAsString(), op->getSourceRange()); 1950 return QualType(); 1951 } 1952 } 1953 // At this point, we know we have a real, complex or pointer type. 1954 // Now make sure the operand is a modifiable lvalue. 1955 Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context); 1956 if (mlval != Expr::MLV_Valid) { 1957 // FIXME: emit a more precise diagnostic... 1958 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr, 1959 op->getSourceRange()); 1960 return QualType(); 1961 } 1962 return resType; 1963} 1964 1965/// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 1966/// This routine allows us to typecheck complex/recursive expressions 1967/// where the declaration is needed for type checking. We only need to 1968/// handle cases when the expression references a function designator 1969/// or is an lvalue. Here are some examples: 1970/// - &(x) => x 1971/// - &*****f => f for f a function designator. 1972/// - &s.xx => s 1973/// - &s.zz[1].yy -> s, if zz is an array 1974/// - *(x + 1) -> x, if x is an array 1975/// - &"123"[2] -> 0 1976/// - & __real__ x -> x 1977static ValueDecl *getPrimaryDecl(Expr *E) { 1978 switch (E->getStmtClass()) { 1979 case Stmt::DeclRefExprClass: 1980 return cast<DeclRefExpr>(E)->getDecl(); 1981 case Stmt::MemberExprClass: 1982 // Fields cannot be declared with a 'register' storage class. 1983 // &X->f is always ok, even if X is declared register. 1984 if (cast<MemberExpr>(E)->isArrow()) 1985 return 0; 1986 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 1987 case Stmt::ArraySubscriptExprClass: { 1988 // &X[4] and &4[X] refers to X if X is not a pointer. 1989 1990 ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase()); 1991 if (!VD || VD->getType()->isPointerType()) 1992 return 0; 1993 else 1994 return VD; 1995 } 1996 case Stmt::UnaryOperatorClass: { 1997 UnaryOperator *UO = cast<UnaryOperator>(E); 1998 1999 switch(UO->getOpcode()) { 2000 case UnaryOperator::Deref: { 2001 // *(X + 1) refers to X if X is not a pointer. 2002 ValueDecl *VD = getPrimaryDecl(UO->getSubExpr()); 2003 if (!VD || VD->getType()->isPointerType()) 2004 return 0; 2005 return VD; 2006 } 2007 case UnaryOperator::Real: 2008 case UnaryOperator::Imag: 2009 case UnaryOperator::Extension: 2010 return getPrimaryDecl(UO->getSubExpr()); 2011 default: 2012 return 0; 2013 } 2014 } 2015 case Stmt::BinaryOperatorClass: { 2016 BinaryOperator *BO = cast<BinaryOperator>(E); 2017 2018 // Handle cases involving pointer arithmetic. The result of an 2019 // Assign or AddAssign is not an lvalue so they can be ignored. 2020 2021 // (x + n) or (n + x) => x 2022 if (BO->getOpcode() == BinaryOperator::Add) { 2023 if (BO->getLHS()->getType()->isPointerType()) { 2024 return getPrimaryDecl(BO->getLHS()); 2025 } else if (BO->getRHS()->getType()->isPointerType()) { 2026 return getPrimaryDecl(BO->getRHS()); 2027 } 2028 } 2029 2030 return 0; 2031 } 2032 case Stmt::ParenExprClass: 2033 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 2034 case Stmt::ImplicitCastExprClass: 2035 // &X[4] when X is an array, has an implicit cast from array to pointer. 2036 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 2037 default: 2038 return 0; 2039 } 2040} 2041 2042/// CheckAddressOfOperand - The operand of & must be either a function 2043/// designator or an lvalue designating an object. If it is an lvalue, the 2044/// object cannot be declared with storage class register or be a bit field. 2045/// Note: The usual conversions are *not* applied to the operand of the & 2046/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 2047QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) { 2048 if (getLangOptions().C99) { 2049 // Implement C99-only parts of addressof rules. 2050 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 2051 if (uOp->getOpcode() == UnaryOperator::Deref) 2052 // Per C99 6.5.3.2, the address of a deref always returns a valid result 2053 // (assuming the deref expression is valid). 2054 return uOp->getSubExpr()->getType(); 2055 } 2056 // Technically, there should be a check for array subscript 2057 // expressions here, but the result of one is always an lvalue anyway. 2058 } 2059 ValueDecl *dcl = getPrimaryDecl(op); 2060 Expr::isLvalueResult lval = op->isLvalue(Context); 2061 2062 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1 2063 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators 2064 // FIXME: emit more specific diag... 2065 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof, 2066 op->getSourceRange()); 2067 return QualType(); 2068 } 2069 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1 2070 if (MemExpr->getMemberDecl()->isBitField()) { 2071 Diag(OpLoc, diag::err_typecheck_address_of, 2072 std::string("bit-field"), op->getSourceRange()); 2073 return QualType(); 2074 } 2075 // Check for Apple extension for accessing vector components. 2076 } else if (isa<ArraySubscriptExpr>(op) && 2077 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) { 2078 Diag(OpLoc, diag::err_typecheck_address_of, 2079 std::string("vector"), op->getSourceRange()); 2080 return QualType(); 2081 } else if (dcl) { // C99 6.5.3.2p1 2082 // We have an lvalue with a decl. Make sure the decl is not declared 2083 // with the register storage-class specifier. 2084 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 2085 if (vd->getStorageClass() == VarDecl::Register) { 2086 Diag(OpLoc, diag::err_typecheck_address_of, 2087 std::string("register variable"), op->getSourceRange()); 2088 return QualType(); 2089 } 2090 } else 2091 assert(0 && "Unknown/unexpected decl type"); 2092 } 2093 2094 // If the operand has type "type", the result has type "pointer to type". 2095 return Context.getPointerType(op->getType()); 2096} 2097 2098QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) { 2099 UsualUnaryConversions(op); 2100 QualType qType = op->getType(); 2101 2102 if (const PointerType *PT = qType->getAsPointerType()) { 2103 // Note that per both C89 and C99, this is always legal, even 2104 // if ptype is an incomplete type or void. 2105 // It would be possible to warn about dereferencing a 2106 // void pointer, but it's completely well-defined, 2107 // and such a warning is unlikely to catch any mistakes. 2108 return PT->getPointeeType(); 2109 } 2110 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer, 2111 qType.getAsString(), op->getSourceRange()); 2112 return QualType(); 2113} 2114 2115static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode( 2116 tok::TokenKind Kind) { 2117 BinaryOperator::Opcode Opc; 2118 switch (Kind) { 2119 default: assert(0 && "Unknown binop!"); 2120 case tok::star: Opc = BinaryOperator::Mul; break; 2121 case tok::slash: Opc = BinaryOperator::Div; break; 2122 case tok::percent: Opc = BinaryOperator::Rem; break; 2123 case tok::plus: Opc = BinaryOperator::Add; break; 2124 case tok::minus: Opc = BinaryOperator::Sub; break; 2125 case tok::lessless: Opc = BinaryOperator::Shl; break; 2126 case tok::greatergreater: Opc = BinaryOperator::Shr; break; 2127 case tok::lessequal: Opc = BinaryOperator::LE; break; 2128 case tok::less: Opc = BinaryOperator::LT; break; 2129 case tok::greaterequal: Opc = BinaryOperator::GE; break; 2130 case tok::greater: Opc = BinaryOperator::GT; break; 2131 case tok::exclaimequal: Opc = BinaryOperator::NE; break; 2132 case tok::equalequal: Opc = BinaryOperator::EQ; break; 2133 case tok::amp: Opc = BinaryOperator::And; break; 2134 case tok::caret: Opc = BinaryOperator::Xor; break; 2135 case tok::pipe: Opc = BinaryOperator::Or; break; 2136 case tok::ampamp: Opc = BinaryOperator::LAnd; break; 2137 case tok::pipepipe: Opc = BinaryOperator::LOr; break; 2138 case tok::equal: Opc = BinaryOperator::Assign; break; 2139 case tok::starequal: Opc = BinaryOperator::MulAssign; break; 2140 case tok::slashequal: Opc = BinaryOperator::DivAssign; break; 2141 case tok::percentequal: Opc = BinaryOperator::RemAssign; break; 2142 case tok::plusequal: Opc = BinaryOperator::AddAssign; break; 2143 case tok::minusequal: Opc = BinaryOperator::SubAssign; break; 2144 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break; 2145 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break; 2146 case tok::ampequal: Opc = BinaryOperator::AndAssign; break; 2147 case tok::caretequal: Opc = BinaryOperator::XorAssign; break; 2148 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break; 2149 case tok::comma: Opc = BinaryOperator::Comma; break; 2150 } 2151 return Opc; 2152} 2153 2154static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode( 2155 tok::TokenKind Kind) { 2156 UnaryOperator::Opcode Opc; 2157 switch (Kind) { 2158 default: assert(0 && "Unknown unary op!"); 2159 case tok::plusplus: Opc = UnaryOperator::PreInc; break; 2160 case tok::minusminus: Opc = UnaryOperator::PreDec; break; 2161 case tok::amp: Opc = UnaryOperator::AddrOf; break; 2162 case tok::star: Opc = UnaryOperator::Deref; break; 2163 case tok::plus: Opc = UnaryOperator::Plus; break; 2164 case tok::minus: Opc = UnaryOperator::Minus; break; 2165 case tok::tilde: Opc = UnaryOperator::Not; break; 2166 case tok::exclaim: Opc = UnaryOperator::LNot; break; 2167 case tok::kw_sizeof: Opc = UnaryOperator::SizeOf; break; 2168 case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break; 2169 case tok::kw___real: Opc = UnaryOperator::Real; break; 2170 case tok::kw___imag: Opc = UnaryOperator::Imag; break; 2171 case tok::kw___extension__: Opc = UnaryOperator::Extension; break; 2172 } 2173 return Opc; 2174} 2175 2176// Binary Operators. 'Tok' is the token for the operator. 2177Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind, 2178 ExprTy *LHS, ExprTy *RHS) { 2179 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind); 2180 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS; 2181 2182 assert((lhs != 0) && "ActOnBinOp(): missing left expression"); 2183 assert((rhs != 0) && "ActOnBinOp(): missing right expression"); 2184 2185 QualType ResultTy; // Result type of the binary operator. 2186 QualType CompTy; // Computation type for compound assignments (e.g. '+=') 2187 2188 switch (Opc) { 2189 default: 2190 assert(0 && "Unknown binary expr!"); 2191 case BinaryOperator::Assign: 2192 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType()); 2193 break; 2194 case BinaryOperator::Mul: 2195 case BinaryOperator::Div: 2196 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc); 2197 break; 2198 case BinaryOperator::Rem: 2199 ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc); 2200 break; 2201 case BinaryOperator::Add: 2202 ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc); 2203 break; 2204 case BinaryOperator::Sub: 2205 ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc); 2206 break; 2207 case BinaryOperator::Shl: 2208 case BinaryOperator::Shr: 2209 ResultTy = CheckShiftOperands(lhs, rhs, TokLoc); 2210 break; 2211 case BinaryOperator::LE: 2212 case BinaryOperator::LT: 2213 case BinaryOperator::GE: 2214 case BinaryOperator::GT: 2215 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true); 2216 break; 2217 case BinaryOperator::EQ: 2218 case BinaryOperator::NE: 2219 ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false); 2220 break; 2221 case BinaryOperator::And: 2222 case BinaryOperator::Xor: 2223 case BinaryOperator::Or: 2224 ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc); 2225 break; 2226 case BinaryOperator::LAnd: 2227 case BinaryOperator::LOr: 2228 ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc); 2229 break; 2230 case BinaryOperator::MulAssign: 2231 case BinaryOperator::DivAssign: 2232 CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true); 2233 if (!CompTy.isNull()) 2234 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy); 2235 break; 2236 case BinaryOperator::RemAssign: 2237 CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true); 2238 if (!CompTy.isNull()) 2239 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy); 2240 break; 2241 case BinaryOperator::AddAssign: 2242 CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true); 2243 if (!CompTy.isNull()) 2244 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy); 2245 break; 2246 case BinaryOperator::SubAssign: 2247 CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true); 2248 if (!CompTy.isNull()) 2249 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy); 2250 break; 2251 case BinaryOperator::ShlAssign: 2252 case BinaryOperator::ShrAssign: 2253 CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true); 2254 if (!CompTy.isNull()) 2255 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy); 2256 break; 2257 case BinaryOperator::AndAssign: 2258 case BinaryOperator::XorAssign: 2259 case BinaryOperator::OrAssign: 2260 CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true); 2261 if (!CompTy.isNull()) 2262 ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy); 2263 break; 2264 case BinaryOperator::Comma: 2265 ResultTy = CheckCommaOperands(lhs, rhs, TokLoc); 2266 break; 2267 } 2268 if (ResultTy.isNull()) 2269 return true; 2270 if (CompTy.isNull()) 2271 return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc); 2272 else 2273 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc); 2274} 2275 2276// Unary Operators. 'Tok' is the token for the operator. 2277Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op, 2278 ExprTy *input) { 2279 Expr *Input = (Expr*)input; 2280 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op); 2281 QualType resultType; 2282 switch (Opc) { 2283 default: 2284 assert(0 && "Unimplemented unary expr!"); 2285 case UnaryOperator::PreInc: 2286 case UnaryOperator::PreDec: 2287 resultType = CheckIncrementDecrementOperand(Input, OpLoc); 2288 break; 2289 case UnaryOperator::AddrOf: 2290 resultType = CheckAddressOfOperand(Input, OpLoc); 2291 break; 2292 case UnaryOperator::Deref: 2293 DefaultFunctionArrayConversion(Input); 2294 resultType = CheckIndirectionOperand(Input, OpLoc); 2295 break; 2296 case UnaryOperator::Plus: 2297 case UnaryOperator::Minus: 2298 UsualUnaryConversions(Input); 2299 resultType = Input->getType(); 2300 if (!resultType->isArithmeticType()) // C99 6.5.3.3p1 2301 return Diag(OpLoc, diag::err_typecheck_unary_expr, 2302 resultType.getAsString()); 2303 break; 2304 case UnaryOperator::Not: // bitwise complement 2305 UsualUnaryConversions(Input); 2306 resultType = Input->getType(); 2307 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 2308 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 2309 // C99 does not support '~' for complex conjugation. 2310 Diag(OpLoc, diag::ext_integer_complement_complex, 2311 resultType.getAsString(), Input->getSourceRange()); 2312 else if (!resultType->isIntegerType()) 2313 return Diag(OpLoc, diag::err_typecheck_unary_expr, 2314 resultType.getAsString(), Input->getSourceRange()); 2315 break; 2316 case UnaryOperator::LNot: // logical negation 2317 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 2318 DefaultFunctionArrayConversion(Input); 2319 resultType = Input->getType(); 2320 if (!resultType->isScalarType()) // C99 6.5.3.3p1 2321 return Diag(OpLoc, diag::err_typecheck_unary_expr, 2322 resultType.getAsString()); 2323 // LNot always has type int. C99 6.5.3.3p5. 2324 resultType = Context.IntTy; 2325 break; 2326 case UnaryOperator::SizeOf: 2327 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, 2328 Input->getSourceRange(), true); 2329 break; 2330 case UnaryOperator::AlignOf: 2331 resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, 2332 Input->getSourceRange(), false); 2333 break; 2334 case UnaryOperator::Real: 2335 case UnaryOperator::Imag: 2336 resultType = CheckRealImagOperand(Input, OpLoc); 2337 break; 2338 case UnaryOperator::Extension: 2339 resultType = Input->getType(); 2340 break; 2341 } 2342 if (resultType.isNull()) 2343 return true; 2344 return new UnaryOperator(Input, Opc, resultType, OpLoc); 2345} 2346 2347/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 2348Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, 2349 SourceLocation LabLoc, 2350 IdentifierInfo *LabelII) { 2351 // Look up the record for this label identifier. 2352 LabelStmt *&LabelDecl = LabelMap[LabelII]; 2353 2354 // If we haven't seen this label yet, create a forward reference. It 2355 // will be validated and/or cleaned up in ActOnFinishFunctionBody. 2356 if (LabelDecl == 0) 2357 LabelDecl = new LabelStmt(LabLoc, LabelII, 0); 2358 2359 // Create the AST node. The address of a label always has type 'void*'. 2360 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl, 2361 Context.getPointerType(Context.VoidTy)); 2362} 2363 2364Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt, 2365 SourceLocation RPLoc) { // "({..})" 2366 Stmt *SubStmt = static_cast<Stmt*>(substmt); 2367 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 2368 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 2369 2370 // FIXME: there are a variety of strange constraints to enforce here, for 2371 // example, it is not possible to goto into a stmt expression apparently. 2372 // More semantic analysis is needed. 2373 2374 // FIXME: the last statement in the compount stmt has its value used. We 2375 // should not warn about it being unused. 2376 2377 // If there are sub stmts in the compound stmt, take the type of the last one 2378 // as the type of the stmtexpr. 2379 QualType Ty = Context.VoidTy; 2380 2381 if (!Compound->body_empty()) { 2382 Stmt *LastStmt = Compound->body_back(); 2383 // If LastStmt is a label, skip down through into the body. 2384 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) 2385 LastStmt = Label->getSubStmt(); 2386 2387 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) 2388 Ty = LastExpr->getType(); 2389 } 2390 2391 return new StmtExpr(Compound, Ty, LPLoc, RPLoc); 2392} 2393 2394Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc, 2395 SourceLocation TypeLoc, 2396 TypeTy *argty, 2397 OffsetOfComponent *CompPtr, 2398 unsigned NumComponents, 2399 SourceLocation RPLoc) { 2400 QualType ArgTy = QualType::getFromOpaquePtr(argty); 2401 assert(!ArgTy.isNull() && "Missing type argument!"); 2402 2403 // We must have at least one component that refers to the type, and the first 2404 // one is known to be a field designator. Verify that the ArgTy represents 2405 // a struct/union/class. 2406 if (!ArgTy->isRecordType()) 2407 return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString()); 2408 2409 // Otherwise, create a compound literal expression as the base, and 2410 // iteratively process the offsetof designators. 2411 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false); 2412 2413 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 2414 // GCC extension, diagnose them. 2415 if (NumComponents != 1) 2416 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator, 2417 SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd)); 2418 2419 for (unsigned i = 0; i != NumComponents; ++i) { 2420 const OffsetOfComponent &OC = CompPtr[i]; 2421 if (OC.isBrackets) { 2422 // Offset of an array sub-field. TODO: Should we allow vector elements? 2423 const ArrayType *AT = Context.getAsArrayType(Res->getType()); 2424 if (!AT) { 2425 delete Res; 2426 return Diag(OC.LocEnd, diag::err_offsetof_array_type, 2427 Res->getType().getAsString()); 2428 } 2429 2430 // FIXME: C++: Verify that operator[] isn't overloaded. 2431 2432 // C99 6.5.2.1p1 2433 Expr *Idx = static_cast<Expr*>(OC.U.E); 2434 if (!Idx->getType()->isIntegerType()) 2435 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript, 2436 Idx->getSourceRange()); 2437 2438 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd); 2439 continue; 2440 } 2441 2442 const RecordType *RC = Res->getType()->getAsRecordType(); 2443 if (!RC) { 2444 delete Res; 2445 return Diag(OC.LocEnd, diag::err_offsetof_record_type, 2446 Res->getType().getAsString()); 2447 } 2448 2449 // Get the decl corresponding to this. 2450 RecordDecl *RD = RC->getDecl(); 2451 FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo); 2452 if (!MemberDecl) 2453 return Diag(BuiltinLoc, diag::err_typecheck_no_member, 2454 OC.U.IdentInfo->getName(), 2455 SourceRange(OC.LocStart, OC.LocEnd)); 2456 2457 // FIXME: C++: Verify that MemberDecl isn't a static field. 2458 // FIXME: Verify that MemberDecl isn't a bitfield. 2459 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't 2460 // matter here. 2461 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType()); 2462 } 2463 2464 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(), 2465 BuiltinLoc); 2466} 2467 2468 2469Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc, 2470 TypeTy *arg1, TypeTy *arg2, 2471 SourceLocation RPLoc) { 2472 QualType argT1 = QualType::getFromOpaquePtr(arg1); 2473 QualType argT2 = QualType::getFromOpaquePtr(arg2); 2474 2475 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)"); 2476 2477 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc); 2478} 2479 2480Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond, 2481 ExprTy *expr1, ExprTy *expr2, 2482 SourceLocation RPLoc) { 2483 Expr *CondExpr = static_cast<Expr*>(cond); 2484 Expr *LHSExpr = static_cast<Expr*>(expr1); 2485 Expr *RHSExpr = static_cast<Expr*>(expr2); 2486 2487 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 2488 2489 // The conditional expression is required to be a constant expression. 2490 llvm::APSInt condEval(32); 2491 SourceLocation ExpLoc; 2492 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc)) 2493 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant, 2494 CondExpr->getSourceRange()); 2495 2496 // If the condition is > zero, then the AST type is the same as the LSHExpr. 2497 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() : 2498 RHSExpr->getType(); 2499 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc); 2500} 2501 2502/// ExprsMatchFnType - return true if the Exprs in array Args have 2503/// QualTypes that match the QualTypes of the arguments of the FnType. 2504/// The number of arguments has already been validated to match the number of 2505/// arguments in FnType. 2506static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType, 2507 ASTContext &Context) { 2508 unsigned NumParams = FnType->getNumArgs(); 2509 for (unsigned i = 0; i != NumParams; ++i) { 2510 QualType ExprTy = Context.getCanonicalType(Args[i]->getType()); 2511 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i)); 2512 2513 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType()) 2514 return false; 2515 } 2516 return true; 2517} 2518 2519Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs, 2520 SourceLocation *CommaLocs, 2521 SourceLocation BuiltinLoc, 2522 SourceLocation RParenLoc) { 2523 // __builtin_overload requires at least 2 arguments 2524 if (NumArgs < 2) 2525 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args, 2526 SourceRange(BuiltinLoc, RParenLoc)); 2527 2528 // The first argument is required to be a constant expression. It tells us 2529 // the number of arguments to pass to each of the functions to be overloaded. 2530 Expr **Args = reinterpret_cast<Expr**>(args); 2531 Expr *NParamsExpr = Args[0]; 2532 llvm::APSInt constEval(32); 2533 SourceLocation ExpLoc; 2534 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc)) 2535 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant, 2536 NParamsExpr->getSourceRange()); 2537 2538 // Verify that the number of parameters is > 0 2539 unsigned NumParams = constEval.getZExtValue(); 2540 if (NumParams == 0) 2541 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant, 2542 NParamsExpr->getSourceRange()); 2543 // Verify that we have at least 1 + NumParams arguments to the builtin. 2544 if ((NumParams + 1) > NumArgs) 2545 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args, 2546 SourceRange(BuiltinLoc, RParenLoc)); 2547 2548 // Figure out the return type, by matching the args to one of the functions 2549 // listed after the parameters. 2550 OverloadExpr *OE = 0; 2551 for (unsigned i = NumParams + 1; i < NumArgs; ++i) { 2552 // UsualUnaryConversions will convert the function DeclRefExpr into a 2553 // pointer to function. 2554 Expr *Fn = UsualUnaryConversions(Args[i]); 2555 const FunctionTypeProto *FnType = 0; 2556 if (const PointerType *PT = Fn->getType()->getAsPointerType()) 2557 FnType = PT->getPointeeType()->getAsFunctionTypeProto(); 2558 2559 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no 2560 // parameters, and the number of parameters must match the value passed to 2561 // the builtin. 2562 if (!FnType || (FnType->getNumArgs() != NumParams)) 2563 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype, 2564 Fn->getSourceRange()); 2565 2566 // Scan the parameter list for the FunctionType, checking the QualType of 2567 // each parameter against the QualTypes of the arguments to the builtin. 2568 // If they match, return a new OverloadExpr. 2569 if (ExprsMatchFnType(Args+1, FnType, Context)) { 2570 if (OE) 2571 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match, 2572 OE->getFn()->getSourceRange()); 2573 // Remember our match, and continue processing the remaining arguments 2574 // to catch any errors. 2575 OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(), 2576 BuiltinLoc, RParenLoc); 2577 } 2578 } 2579 // Return the newly created OverloadExpr node, if we succeded in matching 2580 // exactly one of the candidate functions. 2581 if (OE) 2582 return OE; 2583 2584 // If we didn't find a matching function Expr in the __builtin_overload list 2585 // the return an error. 2586 std::string typeNames; 2587 for (unsigned i = 0; i != NumParams; ++i) { 2588 if (i != 0) typeNames += ", "; 2589 typeNames += Args[i+1]->getType().getAsString(); 2590 } 2591 2592 return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames, 2593 SourceRange(BuiltinLoc, RParenLoc)); 2594} 2595 2596Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 2597 ExprTy *expr, TypeTy *type, 2598 SourceLocation RPLoc) { 2599 Expr *E = static_cast<Expr*>(expr); 2600 QualType T = QualType::getFromOpaquePtr(type); 2601 2602 InitBuiltinVaListType(); 2603 2604 // Get the va_list type 2605 QualType VaListType = Context.getBuiltinVaListType(); 2606 // Deal with implicit array decay; for example, on x86-64, 2607 // va_list is an array, but it's supposed to decay to 2608 // a pointer for va_arg. 2609 if (VaListType->isArrayType()) 2610 VaListType = Context.getArrayDecayedType(VaListType); 2611 2612 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible) 2613 return Diag(E->getLocStart(), 2614 diag::err_first_argument_to_va_arg_not_of_type_va_list, 2615 E->getType().getAsString(), 2616 E->getSourceRange()); 2617 2618 // FIXME: Warn if a non-POD type is passed in. 2619 2620 return new VAArgExpr(BuiltinLoc, E, T, RPLoc); 2621} 2622 2623bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 2624 SourceLocation Loc, 2625 QualType DstType, QualType SrcType, 2626 Expr *SrcExpr, const char *Flavor) { 2627 // Decode the result (notice that AST's are still created for extensions). 2628 bool isInvalid = false; 2629 unsigned DiagKind; 2630 switch (ConvTy) { 2631 default: assert(0 && "Unknown conversion type"); 2632 case Compatible: return false; 2633 case PointerToInt: 2634 DiagKind = diag::ext_typecheck_convert_pointer_int; 2635 break; 2636 case IntToPointer: 2637 DiagKind = diag::ext_typecheck_convert_int_pointer; 2638 break; 2639 case IncompatiblePointer: 2640 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 2641 break; 2642 case FunctionVoidPointer: 2643 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 2644 break; 2645 case CompatiblePointerDiscardsQualifiers: 2646 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 2647 break; 2648 case Incompatible: 2649 DiagKind = diag::err_typecheck_convert_incompatible; 2650 isInvalid = true; 2651 break; 2652 } 2653 2654 Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor, 2655 SrcExpr->getSourceRange()); 2656 return isInvalid; 2657} 2658