SemaExpr.cpp revision f1775fb1081db58015e6d9e4a2fd83bed440a296
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 "clang/Sema/SemaInternal.h" 15#include "clang/Sema/Initialization.h" 16#include "clang/Sema/Lookup.h" 17#include "clang/Sema/AnalysisBasedWarnings.h" 18#include "clang/AST/ASTContext.h" 19#include "clang/AST/ASTMutationListener.h" 20#include "clang/AST/CXXInheritance.h" 21#include "clang/AST/DeclObjC.h" 22#include "clang/AST/DeclTemplate.h" 23#include "clang/AST/EvaluatedExprVisitor.h" 24#include "clang/AST/Expr.h" 25#include "clang/AST/ExprCXX.h" 26#include "clang/AST/ExprObjC.h" 27#include "clang/AST/RecursiveASTVisitor.h" 28#include "clang/AST/TypeLoc.h" 29#include "clang/Basic/PartialDiagnostic.h" 30#include "clang/Basic/SourceManager.h" 31#include "clang/Basic/TargetInfo.h" 32#include "clang/Lex/LiteralSupport.h" 33#include "clang/Lex/Preprocessor.h" 34#include "clang/Sema/DeclSpec.h" 35#include "clang/Sema/Designator.h" 36#include "clang/Sema/Scope.h" 37#include "clang/Sema/ScopeInfo.h" 38#include "clang/Sema/ParsedTemplate.h" 39#include "clang/Sema/SemaFixItUtils.h" 40#include "clang/Sema/Template.h" 41using namespace clang; 42using namespace sema; 43 44 45/// \brief Determine whether the use of this declaration is valid, and 46/// emit any corresponding diagnostics. 47/// 48/// This routine diagnoses various problems with referencing 49/// declarations that can occur when using a declaration. For example, 50/// it might warn if a deprecated or unavailable declaration is being 51/// used, or produce an error (and return true) if a C++0x deleted 52/// function is being used. 53/// 54/// If IgnoreDeprecated is set to true, this should not warn about deprecated 55/// decls. 56/// 57/// \returns true if there was an error (this declaration cannot be 58/// referenced), false otherwise. 59/// 60bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 61 const ObjCInterfaceDecl *UnknownObjCClass) { 62 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) { 63 // If there were any diagnostics suppressed by template argument deduction, 64 // emit them now. 65 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator 66 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 67 if (Pos != SuppressedDiagnostics.end()) { 68 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second; 69 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I) 70 Diag(Suppressed[I].first, Suppressed[I].second); 71 72 // Clear out the list of suppressed diagnostics, so that we don't emit 73 // them again for this specialization. However, we don't obsolete this 74 // entry from the table, because we want to avoid ever emitting these 75 // diagnostics again. 76 Suppressed.clear(); 77 } 78 } 79 80 // See if this is an auto-typed variable whose initializer we are parsing. 81 if (ParsingInitForAutoVars.count(D)) { 82 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 83 << D->getDeclName(); 84 return true; 85 } 86 87 // See if this is a deleted function. 88 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 89 if (FD->isDeleted()) { 90 Diag(Loc, diag::err_deleted_function_use); 91 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true; 92 return true; 93 } 94 } 95 96 // See if this declaration is unavailable or deprecated. 97 std::string Message; 98 switch (D->getAvailability(&Message)) { 99 case AR_Available: 100 case AR_NotYetIntroduced: 101 break; 102 103 case AR_Deprecated: 104 EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass); 105 break; 106 107 case AR_Unavailable: 108 if (cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) { 109 if (Message.empty()) { 110 if (!UnknownObjCClass) 111 Diag(Loc, diag::err_unavailable) << D->getDeclName(); 112 else 113 Diag(Loc, diag::warn_unavailable_fwdclass_message) 114 << D->getDeclName(); 115 } 116 else 117 Diag(Loc, diag::err_unavailable_message) 118 << D->getDeclName() << Message; 119 Diag(D->getLocation(), diag::note_unavailable_here) 120 << isa<FunctionDecl>(D) << false; 121 } 122 break; 123 } 124 125 // Warn if this is used but marked unused. 126 if (D->hasAttr<UnusedAttr>()) 127 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 128 129 return false; 130} 131 132/// \brief Retrieve the message suffix that should be added to a 133/// diagnostic complaining about the given function being deleted or 134/// unavailable. 135std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 136 // FIXME: C++0x implicitly-deleted special member functions could be 137 // detected here so that we could improve diagnostics to say, e.g., 138 // "base class 'A' had a deleted copy constructor". 139 if (FD->isDeleted()) 140 return std::string(); 141 142 std::string Message; 143 if (FD->getAvailability(&Message)) 144 return ": " + Message; 145 146 return std::string(); 147} 148 149/// DiagnoseSentinelCalls - This routine checks on method dispatch calls 150/// (and other functions in future), which have been declared with sentinel 151/// attribute. It warns if call does not have the sentinel argument. 152/// 153void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 154 Expr **Args, unsigned NumArgs) { 155 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 156 if (!attr) 157 return; 158 159 int sentinelPos = attr->getSentinel(); 160 int nullPos = attr->getNullPos(); 161 162 unsigned int i = 0; 163 bool warnNotEnoughArgs = false; 164 int isMethod = 0; 165 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 166 // skip over named parameters. 167 ObjCMethodDecl::param_iterator P, E = MD->param_end(); 168 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) { 169 if (nullPos) 170 --nullPos; 171 else 172 ++i; 173 } 174 warnNotEnoughArgs = (P != E || i >= NumArgs); 175 isMethod = 1; 176 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 177 // skip over named parameters. 178 ObjCMethodDecl::param_iterator P, E = FD->param_end(); 179 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) { 180 if (nullPos) 181 --nullPos; 182 else 183 ++i; 184 } 185 warnNotEnoughArgs = (P != E || i >= NumArgs); 186 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) { 187 // block or function pointer call. 188 QualType Ty = V->getType(); 189 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) { 190 const FunctionType *FT = Ty->isFunctionPointerType() 191 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>() 192 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>(); 193 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) { 194 unsigned NumArgsInProto = Proto->getNumArgs(); 195 unsigned k; 196 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) { 197 if (nullPos) 198 --nullPos; 199 else 200 ++i; 201 } 202 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs); 203 } 204 if (Ty->isBlockPointerType()) 205 isMethod = 2; 206 } else 207 return; 208 } else 209 return; 210 211 if (warnNotEnoughArgs) { 212 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 213 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod; 214 return; 215 } 216 int sentinel = i; 217 while (sentinelPos > 0 && i < NumArgs-1) { 218 --sentinelPos; 219 ++i; 220 } 221 if (sentinelPos > 0) { 222 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 223 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod; 224 return; 225 } 226 while (i < NumArgs-1) { 227 ++i; 228 ++sentinel; 229 } 230 Expr *sentinelExpr = Args[sentinel]; 231 if (!sentinelExpr) return; 232 if (sentinelExpr->isTypeDependent()) return; 233 if (sentinelExpr->isValueDependent()) return; 234 235 // nullptr_t is always treated as null. 236 if (sentinelExpr->getType()->isNullPtrType()) return; 237 238 if (sentinelExpr->getType()->isAnyPointerType() && 239 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context, 240 Expr::NPC_ValueDependentIsNull)) 241 return; 242 243 // Unfortunately, __null has type 'int'. 244 if (isa<GNUNullExpr>(sentinelExpr)) return; 245 246 SourceLocation MissingNilLoc 247 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd()); 248 std::string NullValue; 249 if (isMethod && PP.getIdentifierInfo("nil")->hasMacroDefinition()) 250 NullValue = "nil"; 251 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition()) 252 NullValue = "NULL"; 253 else if (Context.getTypeSize(Context.IntTy) 254 == Context.getTypeSize(Context.getSizeType())) 255 NullValue = "0"; 256 else 257 NullValue = "0L"; 258 259 Diag(MissingNilLoc, diag::warn_missing_sentinel) 260 << isMethod 261 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 262 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod; 263} 264 265SourceRange Sema::getExprRange(ExprTy *E) const { 266 Expr *Ex = (Expr *)E; 267 return Ex? Ex->getSourceRange() : SourceRange(); 268} 269 270//===----------------------------------------------------------------------===// 271// Standard Promotions and Conversions 272//===----------------------------------------------------------------------===// 273 274/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 275ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) { 276 QualType Ty = E->getType(); 277 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 278 279 if (Ty->isFunctionType()) 280 E = ImpCastExprToType(E, Context.getPointerType(Ty), 281 CK_FunctionToPointerDecay).take(); 282 else if (Ty->isArrayType()) { 283 // In C90 mode, arrays only promote to pointers if the array expression is 284 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 285 // type 'array of type' is converted to an expression that has type 'pointer 286 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 287 // that has type 'array of type' ...". The relevant change is "an lvalue" 288 // (C90) to "an expression" (C99). 289 // 290 // C++ 4.2p1: 291 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 292 // T" can be converted to an rvalue of type "pointer to T". 293 // 294 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue()) 295 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 296 CK_ArrayToPointerDecay).take(); 297 } 298 return Owned(E); 299} 300 301static void CheckForNullPointerDereference(Sema &S, Expr *E) { 302 // Check to see if we are dereferencing a null pointer. If so, 303 // and if not volatile-qualified, this is undefined behavior that the 304 // optimizer will delete, so warn about it. People sometimes try to use this 305 // to get a deterministic trap and are surprised by clang's behavior. This 306 // only handles the pattern "*null", which is a very syntactic check. 307 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 308 if (UO->getOpcode() == UO_Deref && 309 UO->getSubExpr()->IgnoreParenCasts()-> 310 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 311 !UO->getType().isVolatileQualified()) { 312 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 313 S.PDiag(diag::warn_indirection_through_null) 314 << UO->getSubExpr()->getSourceRange()); 315 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 316 S.PDiag(diag::note_indirection_through_null)); 317 } 318} 319 320ExprResult Sema::DefaultLvalueConversion(Expr *E) { 321 // C++ [conv.lval]p1: 322 // A glvalue of a non-function, non-array type T can be 323 // converted to a prvalue. 324 if (!E->isGLValue()) return Owned(E); 325 326 QualType T = E->getType(); 327 assert(!T.isNull() && "r-value conversion on typeless expression?"); 328 329 // Create a load out of an ObjCProperty l-value, if necessary. 330 if (E->getObjectKind() == OK_ObjCProperty) { 331 ExprResult Res = ConvertPropertyForRValue(E); 332 if (Res.isInvalid()) 333 return Owned(E); 334 E = Res.take(); 335 if (!E->isGLValue()) 336 return Owned(E); 337 } 338 339 // We don't want to throw lvalue-to-rvalue casts on top of 340 // expressions of certain types in C++. 341 if (getLangOptions().CPlusPlus && 342 (E->getType() == Context.OverloadTy || 343 T->isDependentType() || 344 T->isRecordType())) 345 return Owned(E); 346 347 // The C standard is actually really unclear on this point, and 348 // DR106 tells us what the result should be but not why. It's 349 // generally best to say that void types just doesn't undergo 350 // lvalue-to-rvalue at all. Note that expressions of unqualified 351 // 'void' type are never l-values, but qualified void can be. 352 if (T->isVoidType()) 353 return Owned(E); 354 355 CheckForNullPointerDereference(*this, E); 356 357 // C++ [conv.lval]p1: 358 // [...] If T is a non-class type, the type of the prvalue is the 359 // cv-unqualified version of T. Otherwise, the type of the 360 // rvalue is T. 361 // 362 // C99 6.3.2.1p2: 363 // If the lvalue has qualified type, the value has the unqualified 364 // version of the type of the lvalue; otherwise, the value has the 365 // type of the lvalue. 366 if (T.hasQualifiers()) 367 T = T.getUnqualifiedType(); 368 369 return Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, 370 E, 0, VK_RValue)); 371} 372 373ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 374 ExprResult Res = DefaultFunctionArrayConversion(E); 375 if (Res.isInvalid()) 376 return ExprError(); 377 Res = DefaultLvalueConversion(Res.take()); 378 if (Res.isInvalid()) 379 return ExprError(); 380 return move(Res); 381} 382 383 384/// UsualUnaryConversions - Performs various conversions that are common to most 385/// operators (C99 6.3). The conversions of array and function types are 386/// sometimes suppressed. For example, the array->pointer conversion doesn't 387/// apply if the array is an argument to the sizeof or address (&) operators. 388/// In these instances, this routine should *not* be called. 389ExprResult Sema::UsualUnaryConversions(Expr *E) { 390 // First, convert to an r-value. 391 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 392 if (Res.isInvalid()) 393 return Owned(E); 394 E = Res.take(); 395 396 QualType Ty = E->getType(); 397 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 398 399 // Try to perform integral promotions if the object has a theoretically 400 // promotable type. 401 if (Ty->isIntegralOrUnscopedEnumerationType()) { 402 // C99 6.3.1.1p2: 403 // 404 // The following may be used in an expression wherever an int or 405 // unsigned int may be used: 406 // - an object or expression with an integer type whose integer 407 // conversion rank is less than or equal to the rank of int 408 // and unsigned int. 409 // - A bit-field of type _Bool, int, signed int, or unsigned int. 410 // 411 // If an int can represent all values of the original type, the 412 // value is converted to an int; otherwise, it is converted to an 413 // unsigned int. These are called the integer promotions. All 414 // other types are unchanged by the integer promotions. 415 416 QualType PTy = Context.isPromotableBitField(E); 417 if (!PTy.isNull()) { 418 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take(); 419 return Owned(E); 420 } 421 if (Ty->isPromotableIntegerType()) { 422 QualType PT = Context.getPromotedIntegerType(Ty); 423 E = ImpCastExprToType(E, PT, CK_IntegralCast).take(); 424 return Owned(E); 425 } 426 } 427 return Owned(E); 428} 429 430/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 431/// do not have a prototype. Arguments that have type float are promoted to 432/// double. All other argument types are converted by UsualUnaryConversions(). 433ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 434 QualType Ty = E->getType(); 435 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 436 437 ExprResult Res = UsualUnaryConversions(E); 438 if (Res.isInvalid()) 439 return Owned(E); 440 E = Res.take(); 441 442 // If this is a 'float' (CVR qualified or typedef) promote to double. 443 if (Ty->isSpecificBuiltinType(BuiltinType::Float)) 444 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take(); 445 446 // C++ performs lvalue-to-rvalue conversion as a default argument 447 // promotion, even on class types, but note: 448 // C++11 [conv.lval]p2: 449 // When an lvalue-to-rvalue conversion occurs in an unevaluated 450 // operand or a subexpression thereof the value contained in the 451 // referenced object is not accessed. Otherwise, if the glvalue 452 // has a class type, the conversion copy-initializes a temporary 453 // of type T from the glvalue and the result of the conversion 454 // is a prvalue for the temporary. 455 // FIXME: add some way to gate this entire thing for correctness in 456 // potentially potentially evaluated contexts. 457 if (getLangOptions().CPlusPlus && E->isGLValue() && 458 ExprEvalContexts.back().Context != Unevaluated) { 459 ExprResult Temp = PerformCopyInitialization( 460 InitializedEntity::InitializeTemporary(E->getType()), 461 E->getExprLoc(), 462 Owned(E)); 463 if (Temp.isInvalid()) 464 return ExprError(); 465 E = Temp.get(); 466 } 467 468 return Owned(E); 469} 470 471/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 472/// will warn if the resulting type is not a POD type, and rejects ObjC 473/// interfaces passed by value. 474ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 475 FunctionDecl *FDecl) { 476 ExprResult ExprRes = CheckPlaceholderExpr(E); 477 if (ExprRes.isInvalid()) 478 return ExprError(); 479 480 ExprRes = DefaultArgumentPromotion(E); 481 if (ExprRes.isInvalid()) 482 return ExprError(); 483 E = ExprRes.take(); 484 485 // Don't allow one to pass an Objective-C interface to a vararg. 486 if (E->getType()->isObjCObjectType() && 487 DiagRuntimeBehavior(E->getLocStart(), 0, 488 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 489 << E->getType() << CT)) 490 return ExprError(); 491 492 if (!E->getType().isPODType(Context)) { 493 // C++0x [expr.call]p7: 494 // Passing a potentially-evaluated argument of class type (Clause 9) 495 // having a non-trivial copy constructor, a non-trivial move constructor, 496 // or a non-trivial destructor, with no corresponding parameter, 497 // is conditionally-supported with implementation-defined semantics. 498 bool TrivialEnough = false; 499 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) { 500 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) { 501 if (Record->hasTrivialCopyConstructor() && 502 Record->hasTrivialMoveConstructor() && 503 Record->hasTrivialDestructor()) 504 TrivialEnough = true; 505 } 506 } 507 508 if (!TrivialEnough && 509 getLangOptions().ObjCAutoRefCount && 510 E->getType()->isObjCLifetimeType()) 511 TrivialEnough = true; 512 513 if (TrivialEnough) { 514 // Nothing to diagnose. This is okay. 515 } else if (DiagRuntimeBehavior(E->getLocStart(), 0, 516 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 517 << getLangOptions().CPlusPlus0x << E->getType() 518 << CT)) { 519 // Turn this into a trap. 520 CXXScopeSpec SS; 521 UnqualifiedId Name; 522 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 523 E->getLocStart()); 524 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false); 525 if (TrapFn.isInvalid()) 526 return ExprError(); 527 528 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(), 529 MultiExprArg(), E->getLocEnd()); 530 if (Call.isInvalid()) 531 return ExprError(); 532 533 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 534 Call.get(), E); 535 if (Comma.isInvalid()) 536 return ExprError(); 537 E = Comma.get(); 538 } 539 } 540 541 return Owned(E); 542} 543 544/// \brief Converts an integer to complex float type. Helper function of 545/// UsualArithmeticConversions() 546/// 547/// \return false if the integer expression is an integer type and is 548/// successfully converted to the complex type. 549static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &intExpr, 550 ExprResult &complexExpr, 551 QualType intTy, 552 QualType complexTy, 553 bool skipCast) { 554 if (intTy->isComplexType() || intTy->isRealFloatingType()) return true; 555 if (skipCast) return false; 556 if (intTy->isIntegerType()) { 557 QualType fpTy = cast<ComplexType>(complexTy)->getElementType(); 558 intExpr = S.ImpCastExprToType(intExpr.take(), fpTy, CK_IntegralToFloating); 559 intExpr = S.ImpCastExprToType(intExpr.take(), complexTy, 560 CK_FloatingRealToComplex); 561 } else { 562 assert(intTy->isComplexIntegerType()); 563 intExpr = S.ImpCastExprToType(intExpr.take(), complexTy, 564 CK_IntegralComplexToFloatingComplex); 565 } 566 return false; 567} 568 569/// \brief Takes two complex float types and converts them to the same type. 570/// Helper function of UsualArithmeticConversions() 571static QualType 572handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS, 573 ExprResult &RHS, QualType LHSType, 574 QualType RHSType, 575 bool isCompAssign) { 576 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 577 578 if (order < 0) { 579 // _Complex float -> _Complex double 580 if (!isCompAssign) 581 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast); 582 return RHSType; 583 } 584 if (order > 0) 585 // _Complex float -> _Complex double 586 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast); 587 return LHSType; 588} 589 590/// \brief Converts otherExpr to complex float and promotes complexExpr if 591/// necessary. Helper function of UsualArithmeticConversions() 592static QualType handleOtherComplexFloatConversion(Sema &S, 593 ExprResult &complexExpr, 594 ExprResult &otherExpr, 595 QualType complexTy, 596 QualType otherTy, 597 bool convertComplexExpr, 598 bool convertOtherExpr) { 599 int order = S.Context.getFloatingTypeOrder(complexTy, otherTy); 600 601 // If just the complexExpr is complex, the otherExpr needs to be converted, 602 // and the complexExpr might need to be promoted. 603 if (order > 0) { // complexExpr is wider 604 // float -> _Complex double 605 if (convertOtherExpr) { 606 QualType fp = cast<ComplexType>(complexTy)->getElementType(); 607 otherExpr = S.ImpCastExprToType(otherExpr.take(), fp, CK_FloatingCast); 608 otherExpr = S.ImpCastExprToType(otherExpr.take(), complexTy, 609 CK_FloatingRealToComplex); 610 } 611 return complexTy; 612 } 613 614 // otherTy is at least as wide. Find its corresponding complex type. 615 QualType result = (order == 0 ? complexTy : 616 S.Context.getComplexType(otherTy)); 617 618 // double -> _Complex double 619 if (convertOtherExpr) 620 otherExpr = S.ImpCastExprToType(otherExpr.take(), result, 621 CK_FloatingRealToComplex); 622 623 // _Complex float -> _Complex double 624 if (convertComplexExpr && order < 0) 625 complexExpr = S.ImpCastExprToType(complexExpr.take(), result, 626 CK_FloatingComplexCast); 627 628 return result; 629} 630 631/// \brief Handle arithmetic conversion with complex types. Helper function of 632/// UsualArithmeticConversions() 633static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 634 ExprResult &RHS, QualType LHSType, 635 QualType RHSType, 636 bool isCompAssign) { 637 // if we have an integer operand, the result is the complex type. 638 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 639 /*skipCast*/false)) 640 return LHSType; 641 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 642 /*skipCast*/isCompAssign)) 643 return RHSType; 644 645 // This handles complex/complex, complex/float, or float/complex. 646 // When both operands are complex, the shorter operand is converted to the 647 // type of the longer, and that is the type of the result. This corresponds 648 // to what is done when combining two real floating-point operands. 649 // The fun begins when size promotion occur across type domains. 650 // From H&S 6.3.4: When one operand is complex and the other is a real 651 // floating-point type, the less precise type is converted, within it's 652 // real or complex domain, to the precision of the other type. For example, 653 // when combining a "long double" with a "double _Complex", the 654 // "double _Complex" is promoted to "long double _Complex". 655 656 bool LHSComplexFloat = LHSType->isComplexType(); 657 bool RHSComplexFloat = RHSType->isComplexType(); 658 659 // If both are complex, just cast to the more precise type. 660 if (LHSComplexFloat && RHSComplexFloat) 661 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS, 662 LHSType, RHSType, 663 isCompAssign); 664 665 // If only one operand is complex, promote it if necessary and convert the 666 // other operand to complex. 667 if (LHSComplexFloat) 668 return handleOtherComplexFloatConversion( 669 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!isCompAssign, 670 /*convertOtherExpr*/ true); 671 672 assert(RHSComplexFloat); 673 return handleOtherComplexFloatConversion( 674 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true, 675 /*convertOtherExpr*/ !isCompAssign); 676} 677 678/// \brief Hande arithmetic conversion from integer to float. Helper function 679/// of UsualArithmeticConversions() 680static QualType handleIntToFloatConversion(Sema &S, ExprResult &floatExpr, 681 ExprResult &intExpr, 682 QualType floatTy, QualType intTy, 683 bool convertFloat, bool convertInt) { 684 if (intTy->isIntegerType()) { 685 if (convertInt) 686 // Convert intExpr to the lhs floating point type. 687 intExpr = S.ImpCastExprToType(intExpr.take(), floatTy, 688 CK_IntegralToFloating); 689 return floatTy; 690 } 691 692 // Convert both sides to the appropriate complex float. 693 assert(intTy->isComplexIntegerType()); 694 QualType result = S.Context.getComplexType(floatTy); 695 696 // _Complex int -> _Complex float 697 if (convertInt) 698 intExpr = S.ImpCastExprToType(intExpr.take(), result, 699 CK_IntegralComplexToFloatingComplex); 700 701 // float -> _Complex float 702 if (convertFloat) 703 floatExpr = S.ImpCastExprToType(floatExpr.take(), result, 704 CK_FloatingRealToComplex); 705 706 return result; 707} 708 709/// \brief Handle arithmethic conversion with floating point types. Helper 710/// function of UsualArithmeticConversions() 711static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 712 ExprResult &RHS, QualType LHSType, 713 QualType RHSType, bool isCompAssign) { 714 bool LHSFloat = LHSType->isRealFloatingType(); 715 bool RHSFloat = RHSType->isRealFloatingType(); 716 717 // If we have two real floating types, convert the smaller operand 718 // to the bigger result. 719 if (LHSFloat && RHSFloat) { 720 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 721 if (order > 0) { 722 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast); 723 return LHSType; 724 } 725 726 assert(order < 0 && "illegal float comparison"); 727 if (!isCompAssign) 728 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast); 729 return RHSType; 730 } 731 732 if (LHSFloat) 733 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 734 /*convertFloat=*/!isCompAssign, 735 /*convertInt=*/ true); 736 assert(RHSFloat); 737 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 738 /*convertInt=*/ true, 739 /*convertFloat=*/!isCompAssign); 740} 741 742/// \brief Handle conversions with GCC complex int extension. Helper function 743/// of UsualArithmeticConversions() 744// FIXME: if the operands are (int, _Complex long), we currently 745// don't promote the complex. Also, signedness? 746static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 747 ExprResult &RHS, QualType LHSType, 748 QualType RHSType, 749 bool isCompAssign) { 750 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 751 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 752 753 if (LHSComplexInt && RHSComplexInt) { 754 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(), 755 RHSComplexInt->getElementType()); 756 assert(order && "inequal types with equal element ordering"); 757 if (order > 0) { 758 // _Complex int -> _Complex long 759 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast); 760 return LHSType; 761 } 762 763 if (!isCompAssign) 764 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast); 765 return RHSType; 766 } 767 768 if (LHSComplexInt) { 769 // int -> _Complex int 770 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex); 771 return LHSType; 772 } 773 774 assert(RHSComplexInt); 775 // int -> _Complex int 776 if (!isCompAssign) 777 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex); 778 return RHSType; 779} 780 781/// \brief Handle integer arithmetic conversions. Helper function of 782/// UsualArithmeticConversions() 783static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 784 ExprResult &RHS, QualType LHSType, 785 QualType RHSType, bool isCompAssign) { 786 // The rules for this case are in C99 6.3.1.8 787 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 788 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 789 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 790 if (LHSSigned == RHSSigned) { 791 // Same signedness; use the higher-ranked type 792 if (order >= 0) { 793 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast); 794 return LHSType; 795 } else if (!isCompAssign) 796 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast); 797 return RHSType; 798 } else if (order != (LHSSigned ? 1 : -1)) { 799 // The unsigned type has greater than or equal rank to the 800 // signed type, so use the unsigned type 801 if (RHSSigned) { 802 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast); 803 return LHSType; 804 } else if (!isCompAssign) 805 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast); 806 return RHSType; 807 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 808 // The two types are different widths; if we are here, that 809 // means the signed type is larger than the unsigned type, so 810 // use the signed type. 811 if (LHSSigned) { 812 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast); 813 return LHSType; 814 } else if (!isCompAssign) 815 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast); 816 return RHSType; 817 } else { 818 // The signed type is higher-ranked than the unsigned type, 819 // but isn't actually any bigger (like unsigned int and long 820 // on most 32-bit systems). Use the unsigned type corresponding 821 // to the signed type. 822 QualType result = 823 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 824 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast); 825 if (!isCompAssign) 826 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast); 827 return result; 828 } 829} 830 831/// UsualArithmeticConversions - Performs various conversions that are common to 832/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 833/// routine returns the first non-arithmetic type found. The client is 834/// responsible for emitting appropriate error diagnostics. 835/// FIXME: verify the conversion rules for "complex int" are consistent with 836/// GCC. 837QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 838 bool isCompAssign) { 839 if (!isCompAssign) { 840 LHS = UsualUnaryConversions(LHS.take()); 841 if (LHS.isInvalid()) 842 return QualType(); 843 } 844 845 RHS = UsualUnaryConversions(RHS.take()); 846 if (RHS.isInvalid()) 847 return QualType(); 848 849 // For conversion purposes, we ignore any qualifiers. 850 // For example, "const float" and "float" are equivalent. 851 QualType LHSType = 852 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 853 QualType RHSType = 854 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 855 856 // If both types are identical, no conversion is needed. 857 if (LHSType == RHSType) 858 return LHSType; 859 860 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 861 // The caller can deal with this (e.g. pointer + int). 862 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 863 return LHSType; 864 865 // Apply unary and bitfield promotions to the LHS's type. 866 QualType LHSUnpromotedType = LHSType; 867 if (LHSType->isPromotableIntegerType()) 868 LHSType = Context.getPromotedIntegerType(LHSType); 869 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 870 if (!LHSBitfieldPromoteTy.isNull()) 871 LHSType = LHSBitfieldPromoteTy; 872 if (LHSType != LHSUnpromotedType && !isCompAssign) 873 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast); 874 875 // If both types are identical, no conversion is needed. 876 if (LHSType == RHSType) 877 return LHSType; 878 879 // At this point, we have two different arithmetic types. 880 881 // Handle complex types first (C99 6.3.1.8p1). 882 if (LHSType->isComplexType() || RHSType->isComplexType()) 883 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 884 isCompAssign); 885 886 // Now handle "real" floating types (i.e. float, double, long double). 887 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 888 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 889 isCompAssign); 890 891 // Handle GCC complex int extension. 892 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 893 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 894 isCompAssign); 895 896 // Finally, we have two differing integer types. 897 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType, 898 isCompAssign); 899} 900 901//===----------------------------------------------------------------------===// 902// Semantic Analysis for various Expression Types 903//===----------------------------------------------------------------------===// 904 905 906ExprResult 907Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 908 SourceLocation DefaultLoc, 909 SourceLocation RParenLoc, 910 Expr *ControllingExpr, 911 MultiTypeArg types, 912 MultiExprArg exprs) { 913 unsigned NumAssocs = types.size(); 914 assert(NumAssocs == exprs.size()); 915 916 ParsedType *ParsedTypes = types.release(); 917 Expr **Exprs = exprs.release(); 918 919 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 920 for (unsigned i = 0; i < NumAssocs; ++i) { 921 if (ParsedTypes[i]) 922 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]); 923 else 924 Types[i] = 0; 925 } 926 927 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 928 ControllingExpr, Types, Exprs, 929 NumAssocs); 930 delete [] Types; 931 return ER; 932} 933 934ExprResult 935Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 936 SourceLocation DefaultLoc, 937 SourceLocation RParenLoc, 938 Expr *ControllingExpr, 939 TypeSourceInfo **Types, 940 Expr **Exprs, 941 unsigned NumAssocs) { 942 bool TypeErrorFound = false, 943 IsResultDependent = ControllingExpr->isTypeDependent(), 944 ContainsUnexpandedParameterPack 945 = ControllingExpr->containsUnexpandedParameterPack(); 946 947 for (unsigned i = 0; i < NumAssocs; ++i) { 948 if (Exprs[i]->containsUnexpandedParameterPack()) 949 ContainsUnexpandedParameterPack = true; 950 951 if (Types[i]) { 952 if (Types[i]->getType()->containsUnexpandedParameterPack()) 953 ContainsUnexpandedParameterPack = true; 954 955 if (Types[i]->getType()->isDependentType()) { 956 IsResultDependent = true; 957 } else { 958 // C1X 6.5.1.1p2 "The type name in a generic association shall specify a 959 // complete object type other than a variably modified type." 960 unsigned D = 0; 961 if (Types[i]->getType()->isIncompleteType()) 962 D = diag::err_assoc_type_incomplete; 963 else if (!Types[i]->getType()->isObjectType()) 964 D = diag::err_assoc_type_nonobject; 965 else if (Types[i]->getType()->isVariablyModifiedType()) 966 D = diag::err_assoc_type_variably_modified; 967 968 if (D != 0) { 969 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 970 << Types[i]->getTypeLoc().getSourceRange() 971 << Types[i]->getType(); 972 TypeErrorFound = true; 973 } 974 975 // C1X 6.5.1.1p2 "No two generic associations in the same generic 976 // selection shall specify compatible types." 977 for (unsigned j = i+1; j < NumAssocs; ++j) 978 if (Types[j] && !Types[j]->getType()->isDependentType() && 979 Context.typesAreCompatible(Types[i]->getType(), 980 Types[j]->getType())) { 981 Diag(Types[j]->getTypeLoc().getBeginLoc(), 982 diag::err_assoc_compatible_types) 983 << Types[j]->getTypeLoc().getSourceRange() 984 << Types[j]->getType() 985 << Types[i]->getType(); 986 Diag(Types[i]->getTypeLoc().getBeginLoc(), 987 diag::note_compat_assoc) 988 << Types[i]->getTypeLoc().getSourceRange() 989 << Types[i]->getType(); 990 TypeErrorFound = true; 991 } 992 } 993 } 994 } 995 if (TypeErrorFound) 996 return ExprError(); 997 998 // If we determined that the generic selection is result-dependent, don't 999 // try to compute the result expression. 1000 if (IsResultDependent) 1001 return Owned(new (Context) GenericSelectionExpr( 1002 Context, KeyLoc, ControllingExpr, 1003 Types, Exprs, NumAssocs, DefaultLoc, 1004 RParenLoc, ContainsUnexpandedParameterPack)); 1005 1006 SmallVector<unsigned, 1> CompatIndices; 1007 unsigned DefaultIndex = -1U; 1008 for (unsigned i = 0; i < NumAssocs; ++i) { 1009 if (!Types[i]) 1010 DefaultIndex = i; 1011 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1012 Types[i]->getType())) 1013 CompatIndices.push_back(i); 1014 } 1015 1016 // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have 1017 // type compatible with at most one of the types named in its generic 1018 // association list." 1019 if (CompatIndices.size() > 1) { 1020 // We strip parens here because the controlling expression is typically 1021 // parenthesized in macro definitions. 1022 ControllingExpr = ControllingExpr->IgnoreParens(); 1023 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1024 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1025 << (unsigned) CompatIndices.size(); 1026 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(), 1027 E = CompatIndices.end(); I != E; ++I) { 1028 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1029 diag::note_compat_assoc) 1030 << Types[*I]->getTypeLoc().getSourceRange() 1031 << Types[*I]->getType(); 1032 } 1033 return ExprError(); 1034 } 1035 1036 // C1X 6.5.1.1p2 "If a generic selection has no default generic association, 1037 // its controlling expression shall have type compatible with exactly one of 1038 // the types named in its generic association list." 1039 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1040 // We strip parens here because the controlling expression is typically 1041 // parenthesized in macro definitions. 1042 ControllingExpr = ControllingExpr->IgnoreParens(); 1043 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1044 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1045 return ExprError(); 1046 } 1047 1048 // C1X 6.5.1.1p3 "If a generic selection has a generic association with a 1049 // type name that is compatible with the type of the controlling expression, 1050 // then the result expression of the generic selection is the expression 1051 // in that generic association. Otherwise, the result expression of the 1052 // generic selection is the expression in the default generic association." 1053 unsigned ResultIndex = 1054 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1055 1056 return Owned(new (Context) GenericSelectionExpr( 1057 Context, KeyLoc, ControllingExpr, 1058 Types, Exprs, NumAssocs, DefaultLoc, 1059 RParenLoc, ContainsUnexpandedParameterPack, 1060 ResultIndex)); 1061} 1062 1063/// ActOnStringLiteral - The specified tokens were lexed as pasted string 1064/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1065/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1066/// multiple tokens. However, the common case is that StringToks points to one 1067/// string. 1068/// 1069ExprResult 1070Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) { 1071 assert(NumStringToks && "Must have at least one string!"); 1072 1073 StringLiteralParser Literal(StringToks, NumStringToks, PP); 1074 if (Literal.hadError) 1075 return ExprError(); 1076 1077 SmallVector<SourceLocation, 4> StringTokLocs; 1078 for (unsigned i = 0; i != NumStringToks; ++i) 1079 StringTokLocs.push_back(StringToks[i].getLocation()); 1080 1081 QualType StrTy = Context.CharTy; 1082 if (Literal.isWide()) 1083 StrTy = Context.getWCharType(); 1084 else if (Literal.isUTF16()) 1085 StrTy = Context.Char16Ty; 1086 else if (Literal.isUTF32()) 1087 StrTy = Context.Char32Ty; 1088 else if (Literal.Pascal) 1089 StrTy = Context.UnsignedCharTy; 1090 1091 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1092 if (Literal.isWide()) 1093 Kind = StringLiteral::Wide; 1094 else if (Literal.isUTF8()) 1095 Kind = StringLiteral::UTF8; 1096 else if (Literal.isUTF16()) 1097 Kind = StringLiteral::UTF16; 1098 else if (Literal.isUTF32()) 1099 Kind = StringLiteral::UTF32; 1100 1101 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1102 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings) 1103 StrTy.addConst(); 1104 1105 // Get an array type for the string, according to C99 6.4.5. This includes 1106 // the nul terminator character as well as the string length for pascal 1107 // strings. 1108 StrTy = Context.getConstantArrayType(StrTy, 1109 llvm::APInt(32, Literal.GetNumStringChars()+1), 1110 ArrayType::Normal, 0); 1111 1112 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1113 return Owned(StringLiteral::Create(Context, Literal.GetString(), 1114 Kind, Literal.Pascal, StrTy, 1115 &StringTokLocs[0], 1116 StringTokLocs.size())); 1117} 1118 1119enum CaptureResult { 1120 /// No capture is required. 1121 CR_NoCapture, 1122 1123 /// A capture is required. 1124 CR_Capture, 1125 1126 /// A by-ref capture is required. 1127 CR_CaptureByRef, 1128 1129 /// An error occurred when trying to capture the given variable. 1130 CR_Error 1131}; 1132 1133/// Diagnose an uncapturable value reference. 1134/// 1135/// \param var - the variable referenced 1136/// \param DC - the context which we couldn't capture through 1137static CaptureResult 1138diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 1139 VarDecl *var, DeclContext *DC) { 1140 switch (S.ExprEvalContexts.back().Context) { 1141 case Sema::Unevaluated: 1142 // The argument will never be evaluated, so don't complain. 1143 return CR_NoCapture; 1144 1145 case Sema::PotentiallyEvaluated: 1146 case Sema::PotentiallyEvaluatedIfUsed: 1147 break; 1148 1149 case Sema::PotentiallyPotentiallyEvaluated: 1150 // FIXME: delay these! 1151 break; 1152 } 1153 1154 // Don't diagnose about capture if we're not actually in code right 1155 // now; in general, there are more appropriate places that will 1156 // diagnose this. 1157 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture; 1158 1159 // Certain madnesses can happen with parameter declarations, which 1160 // we want to ignore. 1161 if (isa<ParmVarDecl>(var)) { 1162 // - If the parameter still belongs to the translation unit, then 1163 // we're actually just using one parameter in the declaration of 1164 // the next. This is useful in e.g. VLAs. 1165 if (isa<TranslationUnitDecl>(var->getDeclContext())) 1166 return CR_NoCapture; 1167 1168 // - This particular madness can happen in ill-formed default 1169 // arguments; claim it's okay and let downstream code handle it. 1170 if (S.CurContext == var->getDeclContext()->getParent()) 1171 return CR_NoCapture; 1172 } 1173 1174 DeclarationName functionName; 1175 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext())) 1176 functionName = fn->getDeclName(); 1177 // FIXME: variable from enclosing block that we couldn't capture from! 1178 1179 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 1180 << var->getIdentifier() << functionName; 1181 S.Diag(var->getLocation(), diag::note_local_variable_declared_here) 1182 << var->getIdentifier(); 1183 1184 return CR_Error; 1185} 1186 1187/// There is a well-formed capture at a particular scope level; 1188/// propagate it through all the nested blocks. 1189static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex, 1190 const BlockDecl::Capture &capture) { 1191 VarDecl *var = capture.getVariable(); 1192 1193 // Update all the inner blocks with the capture information. 1194 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size(); 1195 i != e; ++i) { 1196 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]); 1197 innerBlock->Captures.push_back( 1198 BlockDecl::Capture(capture.getVariable(), capture.isByRef(), 1199 /*nested*/ true, capture.getCopyExpr())); 1200 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1 1201 } 1202 1203 return capture.isByRef() ? CR_CaptureByRef : CR_Capture; 1204} 1205 1206/// shouldCaptureValueReference - Determine if a reference to the 1207/// given value in the current context requires a variable capture. 1208/// 1209/// This also keeps the captures set in the BlockScopeInfo records 1210/// up-to-date. 1211static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc, 1212 ValueDecl *value) { 1213 // Only variables ever require capture. 1214 VarDecl *var = dyn_cast<VarDecl>(value); 1215 if (!var) return CR_NoCapture; 1216 1217 // Fast path: variables from the current context never require capture. 1218 DeclContext *DC = S.CurContext; 1219 if (var->getDeclContext() == DC) return CR_NoCapture; 1220 1221 // Only variables with local storage require capture. 1222 // FIXME: What about 'const' variables in C++? 1223 if (!var->hasLocalStorage()) return CR_NoCapture; 1224 1225 // Otherwise, we need to capture. 1226 1227 unsigned functionScopesIndex = S.FunctionScopes.size() - 1; 1228 do { 1229 // Only blocks (and eventually C++0x closures) can capture; other 1230 // scopes don't work. 1231 if (!isa<BlockDecl>(DC)) 1232 return diagnoseUncapturableValueReference(S, loc, var, DC); 1233 1234 BlockScopeInfo *blockScope = 1235 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]); 1236 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC)); 1237 1238 // Check whether we've already captured it in this block. If so, 1239 // we're done. 1240 if (unsigned indexPlus1 = blockScope->CaptureMap[var]) 1241 return propagateCapture(S, functionScopesIndex, 1242 blockScope->Captures[indexPlus1 - 1]); 1243 1244 functionScopesIndex--; 1245 DC = cast<BlockDecl>(DC)->getDeclContext(); 1246 } while (var->getDeclContext() != DC); 1247 1248 // Okay, we descended all the way to the block that defines the variable. 1249 // Actually try to capture it. 1250 QualType type = var->getType(); 1251 1252 // Prohibit variably-modified types. 1253 if (type->isVariablyModifiedType()) { 1254 S.Diag(loc, diag::err_ref_vm_type); 1255 S.Diag(var->getLocation(), diag::note_declared_at); 1256 return CR_Error; 1257 } 1258 1259 // Prohibit arrays, even in __block variables, but not references to 1260 // them. 1261 if (type->isArrayType()) { 1262 S.Diag(loc, diag::err_ref_array_type); 1263 S.Diag(var->getLocation(), diag::note_declared_at); 1264 return CR_Error; 1265 } 1266 1267 S.MarkDeclarationReferenced(loc, var); 1268 1269 // The BlocksAttr indicates the variable is bound by-reference. 1270 bool byRef = var->hasAttr<BlocksAttr>(); 1271 1272 // Build a copy expression. 1273 Expr *copyExpr = 0; 1274 const RecordType *rtype; 1275 if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() && 1276 (rtype = type->getAs<RecordType>())) { 1277 1278 // The capture logic needs the destructor, so make sure we mark it. 1279 // Usually this is unnecessary because most local variables have 1280 // their destructors marked at declaration time, but parameters are 1281 // an exception because it's technically only the call site that 1282 // actually requires the destructor. 1283 if (isa<ParmVarDecl>(var)) 1284 S.FinalizeVarWithDestructor(var, rtype); 1285 1286 // According to the blocks spec, the capture of a variable from 1287 // the stack requires a const copy constructor. This is not true 1288 // of the copy/move done to move a __block variable to the heap. 1289 type.addConst(); 1290 1291 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc); 1292 ExprResult result = 1293 S.PerformCopyInitialization( 1294 InitializedEntity::InitializeBlock(var->getLocation(), 1295 type, false), 1296 loc, S.Owned(declRef)); 1297 1298 // Build a full-expression copy expression if initialization 1299 // succeeded and used a non-trivial constructor. Recover from 1300 // errors by pretending that the copy isn't necessary. 1301 if (!result.isInvalid() && 1302 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) { 1303 result = S.MaybeCreateExprWithCleanups(result); 1304 copyExpr = result.take(); 1305 } 1306 } 1307 1308 // We're currently at the declarer; go back to the closure. 1309 functionScopesIndex++; 1310 BlockScopeInfo *blockScope = 1311 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]); 1312 1313 // Build a valid capture in this scope. 1314 blockScope->Captures.push_back( 1315 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr)); 1316 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1 1317 1318 // Propagate that to inner captures if necessary. 1319 return propagateCapture(S, functionScopesIndex, 1320 blockScope->Captures.back()); 1321} 1322 1323static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd, 1324 const DeclarationNameInfo &NameInfo, 1325 bool byRef) { 1326 assert(isa<VarDecl>(vd) && "capturing non-variable"); 1327 1328 VarDecl *var = cast<VarDecl>(vd); 1329 assert(var->hasLocalStorage() && "capturing non-local"); 1330 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong"); 1331 1332 QualType exprType = var->getType().getNonReferenceType(); 1333 1334 BlockDeclRefExpr *BDRE; 1335 if (!byRef) { 1336 // The variable will be bound by copy; make it const within the 1337 // closure, but record that this was done in the expression. 1338 bool constAdded = !exprType.isConstQualified(); 1339 exprType.addConst(); 1340 1341 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue, 1342 NameInfo.getLoc(), false, 1343 constAdded); 1344 } else { 1345 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue, 1346 NameInfo.getLoc(), true); 1347 } 1348 1349 return S.Owned(BDRE); 1350} 1351 1352ExprResult 1353Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1354 SourceLocation Loc, 1355 const CXXScopeSpec *SS) { 1356 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1357 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1358} 1359 1360/// BuildDeclRefExpr - Build an expression that references a 1361/// declaration that does not require a closure capture. 1362ExprResult 1363Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1364 const DeclarationNameInfo &NameInfo, 1365 const CXXScopeSpec *SS) { 1366 MarkDeclarationReferenced(NameInfo.getLoc(), D); 1367 1368 Expr *E = DeclRefExpr::Create(Context, 1369 SS? SS->getWithLocInContext(Context) 1370 : NestedNameSpecifierLoc(), 1371 D, NameInfo, Ty, VK); 1372 1373 // Just in case we're building an illegal pointer-to-member. 1374 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth()) 1375 E->setObjectKind(OK_BitField); 1376 1377 return Owned(E); 1378} 1379 1380/// Decomposes the given name into a DeclarationNameInfo, its location, and 1381/// possibly a list of template arguments. 1382/// 1383/// If this produces template arguments, it is permitted to call 1384/// DecomposeTemplateName. 1385/// 1386/// This actually loses a lot of source location information for 1387/// non-standard name kinds; we should consider preserving that in 1388/// some way. 1389void 1390Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1391 TemplateArgumentListInfo &Buffer, 1392 DeclarationNameInfo &NameInfo, 1393 const TemplateArgumentListInfo *&TemplateArgs) { 1394 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1395 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1396 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1397 1398 ASTTemplateArgsPtr TemplateArgsPtr(*this, 1399 Id.TemplateId->getTemplateArgs(), 1400 Id.TemplateId->NumArgs); 1401 translateTemplateArguments(TemplateArgsPtr, Buffer); 1402 TemplateArgsPtr.release(); 1403 1404 TemplateName TName = Id.TemplateId->Template.get(); 1405 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1406 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1407 TemplateArgs = &Buffer; 1408 } else { 1409 NameInfo = GetNameFromUnqualifiedId(Id); 1410 TemplateArgs = 0; 1411 } 1412} 1413 1414/// Diagnose an empty lookup. 1415/// 1416/// \return false if new lookup candidates were found 1417bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1418 CorrectTypoContext CTC, 1419 TemplateArgumentListInfo *ExplicitTemplateArgs, 1420 Expr **Args, unsigned NumArgs) { 1421 DeclarationName Name = R.getLookupName(); 1422 1423 unsigned diagnostic = diag::err_undeclared_var_use; 1424 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1425 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1426 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1427 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1428 diagnostic = diag::err_undeclared_use; 1429 diagnostic_suggest = diag::err_undeclared_use_suggest; 1430 } 1431 1432 // If the original lookup was an unqualified lookup, fake an 1433 // unqualified lookup. This is useful when (for example) the 1434 // original lookup would not have found something because it was a 1435 // dependent name. 1436 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0; 1437 DC; DC = DC->getParent()) { 1438 if (isa<CXXRecordDecl>(DC)) { 1439 LookupQualifiedName(R, DC); 1440 1441 if (!R.empty()) { 1442 // Don't give errors about ambiguities in this lookup. 1443 R.suppressDiagnostics(); 1444 1445 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1446 bool isInstance = CurMethod && 1447 CurMethod->isInstance() && 1448 DC == CurMethod->getParent(); 1449 1450 // Give a code modification hint to insert 'this->'. 1451 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1452 // Actually quite difficult! 1453 if (isInstance) { 1454 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 1455 CallsUndergoingInstantiation.back()->getCallee()); 1456 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>( 1457 CurMethod->getInstantiatedFromMemberFunction()); 1458 if (DepMethod) { 1459 Diag(R.getNameLoc(), diagnostic) << Name 1460 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1461 QualType DepThisType = DepMethod->getThisType(Context); 1462 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 1463 R.getNameLoc(), DepThisType, false); 1464 TemplateArgumentListInfo TList; 1465 if (ULE->hasExplicitTemplateArgs()) 1466 ULE->copyTemplateArgumentsInto(TList); 1467 1468 CXXScopeSpec SS; 1469 SS.Adopt(ULE->getQualifierLoc()); 1470 CXXDependentScopeMemberExpr *DepExpr = 1471 CXXDependentScopeMemberExpr::Create( 1472 Context, DepThis, DepThisType, true, SourceLocation(), 1473 SS.getWithLocInContext(Context), NULL, 1474 R.getLookupNameInfo(), 1475 ULE->hasExplicitTemplateArgs() ? &TList : 0); 1476 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 1477 } else { 1478 // FIXME: we should be able to handle this case too. It is correct 1479 // to add this-> here. This is a workaround for PR7947. 1480 Diag(R.getNameLoc(), diagnostic) << Name; 1481 } 1482 } else { 1483 Diag(R.getNameLoc(), diagnostic) << Name; 1484 } 1485 1486 // Do we really want to note all of these? 1487 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1488 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1489 1490 // Tell the callee to try to recover. 1491 return false; 1492 } 1493 1494 R.clear(); 1495 } 1496 } 1497 1498 // We didn't find anything, so try to correct for a typo. 1499 TypoCorrection Corrected; 1500 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 1501 S, &SS, NULL, false, CTC))) { 1502 std::string CorrectedStr(Corrected.getAsString(getLangOptions())); 1503 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions())); 1504 R.setLookupName(Corrected.getCorrection()); 1505 1506 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 1507 if (Corrected.isOverloaded()) { 1508 OverloadCandidateSet OCS(R.getNameLoc()); 1509 OverloadCandidateSet::iterator Best; 1510 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1511 CDEnd = Corrected.end(); 1512 CD != CDEnd; ++CD) { 1513 if (FunctionTemplateDecl *FTD = 1514 dyn_cast<FunctionTemplateDecl>(*CD)) 1515 AddTemplateOverloadCandidate( 1516 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1517 Args, NumArgs, OCS); 1518 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1519 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1520 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1521 Args, NumArgs, OCS); 1522 } 1523 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1524 case OR_Success: 1525 ND = Best->Function; 1526 break; 1527 default: 1528 break; 1529 } 1530 } 1531 R.addDecl(ND); 1532 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 1533 if (SS.isEmpty()) 1534 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr 1535 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1536 else 1537 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1538 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1539 << SS.getRange() 1540 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1541 if (ND) 1542 Diag(ND->getLocation(), diag::note_previous_decl) 1543 << CorrectedQuotedStr; 1544 1545 // Tell the callee to try to recover. 1546 return false; 1547 } 1548 1549 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) { 1550 // FIXME: If we ended up with a typo for a type name or 1551 // Objective-C class name, we're in trouble because the parser 1552 // is in the wrong place to recover. Suggest the typo 1553 // correction, but don't make it a fix-it since we're not going 1554 // to recover well anyway. 1555 if (SS.isEmpty()) 1556 Diag(R.getNameLoc(), diagnostic_suggest) 1557 << Name << CorrectedQuotedStr; 1558 else 1559 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1560 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1561 << SS.getRange(); 1562 1563 // Don't try to recover; it won't work. 1564 return true; 1565 } 1566 } else { 1567 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1568 // because we aren't able to recover. 1569 if (SS.isEmpty()) 1570 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr; 1571 else 1572 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1573 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1574 << SS.getRange(); 1575 return true; 1576 } 1577 } 1578 R.clear(); 1579 1580 // Emit a special diagnostic for failed member lookups. 1581 // FIXME: computing the declaration context might fail here (?) 1582 if (!SS.isEmpty()) { 1583 Diag(R.getNameLoc(), diag::err_no_member) 1584 << Name << computeDeclContext(SS, false) 1585 << SS.getRange(); 1586 return true; 1587 } 1588 1589 // Give up, we can't recover. 1590 Diag(R.getNameLoc(), diagnostic) << Name; 1591 return true; 1592} 1593 1594ExprResult Sema::ActOnIdExpression(Scope *S, 1595 CXXScopeSpec &SS, 1596 UnqualifiedId &Id, 1597 bool HasTrailingLParen, 1598 bool isAddressOfOperand) { 1599 assert(!(isAddressOfOperand && HasTrailingLParen) && 1600 "cannot be direct & operand and have a trailing lparen"); 1601 1602 if (SS.isInvalid()) 1603 return ExprError(); 1604 1605 TemplateArgumentListInfo TemplateArgsBuffer; 1606 1607 // Decompose the UnqualifiedId into the following data. 1608 DeclarationNameInfo NameInfo; 1609 const TemplateArgumentListInfo *TemplateArgs; 1610 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 1611 1612 DeclarationName Name = NameInfo.getName(); 1613 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1614 SourceLocation NameLoc = NameInfo.getLoc(); 1615 1616 // C++ [temp.dep.expr]p3: 1617 // An id-expression is type-dependent if it contains: 1618 // -- an identifier that was declared with a dependent type, 1619 // (note: handled after lookup) 1620 // -- a template-id that is dependent, 1621 // (note: handled in BuildTemplateIdExpr) 1622 // -- a conversion-function-id that specifies a dependent type, 1623 // -- a nested-name-specifier that contains a class-name that 1624 // names a dependent type. 1625 // Determine whether this is a member of an unknown specialization; 1626 // we need to handle these differently. 1627 bool DependentID = false; 1628 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 1629 Name.getCXXNameType()->isDependentType()) { 1630 DependentID = true; 1631 } else if (SS.isSet()) { 1632 if (DeclContext *DC = computeDeclContext(SS, false)) { 1633 if (RequireCompleteDeclContext(SS, DC)) 1634 return ExprError(); 1635 } else { 1636 DependentID = true; 1637 } 1638 } 1639 1640 if (DependentID) 1641 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand, 1642 TemplateArgs); 1643 1644 bool IvarLookupFollowUp = false; 1645 // Perform the required lookup. 1646 LookupResult R(*this, NameInfo, 1647 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 1648 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 1649 if (TemplateArgs) { 1650 // Lookup the template name again to correctly establish the context in 1651 // which it was found. This is really unfortunate as we already did the 1652 // lookup to determine that it was a template name in the first place. If 1653 // this becomes a performance hit, we can work harder to preserve those 1654 // results until we get here but it's likely not worth it. 1655 bool MemberOfUnknownSpecialization; 1656 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 1657 MemberOfUnknownSpecialization); 1658 1659 if (MemberOfUnknownSpecialization || 1660 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 1661 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand, 1662 TemplateArgs); 1663 } else { 1664 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl()); 1665 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 1666 1667 // If the result might be in a dependent base class, this is a dependent 1668 // id-expression. 1669 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 1670 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand, 1671 TemplateArgs); 1672 1673 // If this reference is in an Objective-C method, then we need to do 1674 // some special Objective-C lookup, too. 1675 if (IvarLookupFollowUp) { 1676 ExprResult E(LookupInObjCMethod(R, S, II, true)); 1677 if (E.isInvalid()) 1678 return ExprError(); 1679 1680 if (Expr *Ex = E.takeAs<Expr>()) 1681 return Owned(Ex); 1682 1683 // for further use, this must be set to false if in class method. 1684 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod(); 1685 } 1686 } 1687 1688 if (R.isAmbiguous()) 1689 return ExprError(); 1690 1691 // Determine whether this name might be a candidate for 1692 // argument-dependent lookup. 1693 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 1694 1695 if (R.empty() && !ADL) { 1696 // Otherwise, this could be an implicitly declared function reference (legal 1697 // in C90, extension in C99, forbidden in C++). 1698 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) { 1699 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 1700 if (D) R.addDecl(D); 1701 } 1702 1703 // If this name wasn't predeclared and if this is not a function 1704 // call, diagnose the problem. 1705 if (R.empty()) { 1706 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown)) 1707 return ExprError(); 1708 1709 assert(!R.empty() && 1710 "DiagnoseEmptyLookup returned false but added no results"); 1711 1712 // If we found an Objective-C instance variable, let 1713 // LookupInObjCMethod build the appropriate expression to 1714 // reference the ivar. 1715 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 1716 R.clear(); 1717 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 1718 assert(E.isInvalid() || E.get()); 1719 return move(E); 1720 } 1721 } 1722 } 1723 1724 // This is guaranteed from this point on. 1725 assert(!R.empty() || ADL); 1726 1727 // Check whether this might be a C++ implicit instance member access. 1728 // C++ [class.mfct.non-static]p3: 1729 // When an id-expression that is not part of a class member access 1730 // syntax and not used to form a pointer to member is used in the 1731 // body of a non-static member function of class X, if name lookup 1732 // resolves the name in the id-expression to a non-static non-type 1733 // member of some class C, the id-expression is transformed into a 1734 // class member access expression using (*this) as the 1735 // postfix-expression to the left of the . operator. 1736 // 1737 // But we don't actually need to do this for '&' operands if R 1738 // resolved to a function or overloaded function set, because the 1739 // expression is ill-formed if it actually works out to be a 1740 // non-static member function: 1741 // 1742 // C++ [expr.ref]p4: 1743 // Otherwise, if E1.E2 refers to a non-static member function. . . 1744 // [t]he expression can be used only as the left-hand operand of a 1745 // member function call. 1746 // 1747 // There are other safeguards against such uses, but it's important 1748 // to get this right here so that we don't end up making a 1749 // spuriously dependent expression if we're inside a dependent 1750 // instance method. 1751 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 1752 bool MightBeImplicitMember; 1753 if (!isAddressOfOperand) 1754 MightBeImplicitMember = true; 1755 else if (!SS.isEmpty()) 1756 MightBeImplicitMember = false; 1757 else if (R.isOverloadedResult()) 1758 MightBeImplicitMember = false; 1759 else if (R.isUnresolvableResult()) 1760 MightBeImplicitMember = true; 1761 else 1762 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 1763 isa<IndirectFieldDecl>(R.getFoundDecl()); 1764 1765 if (MightBeImplicitMember) 1766 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs); 1767 } 1768 1769 if (TemplateArgs) 1770 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs); 1771 1772 return BuildDeclarationNameExpr(SS, R, ADL); 1773} 1774 1775/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 1776/// declaration name, generally during template instantiation. 1777/// There's a large number of things which don't need to be done along 1778/// this path. 1779ExprResult 1780Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 1781 const DeclarationNameInfo &NameInfo) { 1782 DeclContext *DC; 1783 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext()) 1784 return BuildDependentDeclRefExpr(SS, NameInfo, 0); 1785 1786 if (RequireCompleteDeclContext(SS, DC)) 1787 return ExprError(); 1788 1789 LookupResult R(*this, NameInfo, LookupOrdinaryName); 1790 LookupQualifiedName(R, DC); 1791 1792 if (R.isAmbiguous()) 1793 return ExprError(); 1794 1795 if (R.empty()) { 1796 Diag(NameInfo.getLoc(), diag::err_no_member) 1797 << NameInfo.getName() << DC << SS.getRange(); 1798 return ExprError(); 1799 } 1800 1801 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false); 1802} 1803 1804/// LookupInObjCMethod - The parser has read a name in, and Sema has 1805/// detected that we're currently inside an ObjC method. Perform some 1806/// additional lookup. 1807/// 1808/// Ideally, most of this would be done by lookup, but there's 1809/// actually quite a lot of extra work involved. 1810/// 1811/// Returns a null sentinel to indicate trivial success. 1812ExprResult 1813Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 1814 IdentifierInfo *II, bool AllowBuiltinCreation) { 1815 SourceLocation Loc = Lookup.getNameLoc(); 1816 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 1817 1818 // There are two cases to handle here. 1) scoped lookup could have failed, 1819 // in which case we should look for an ivar. 2) scoped lookup could have 1820 // found a decl, but that decl is outside the current instance method (i.e. 1821 // a global variable). In these two cases, we do a lookup for an ivar with 1822 // this name, if the lookup sucedes, we replace it our current decl. 1823 1824 // If we're in a class method, we don't normally want to look for 1825 // ivars. But if we don't find anything else, and there's an 1826 // ivar, that's an error. 1827 bool IsClassMethod = CurMethod->isClassMethod(); 1828 1829 bool LookForIvars; 1830 if (Lookup.empty()) 1831 LookForIvars = true; 1832 else if (IsClassMethod) 1833 LookForIvars = false; 1834 else 1835 LookForIvars = (Lookup.isSingleResult() && 1836 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 1837 ObjCInterfaceDecl *IFace = 0; 1838 if (LookForIvars) { 1839 IFace = CurMethod->getClassInterface(); 1840 ObjCInterfaceDecl *ClassDeclared; 1841 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 1842 // Diagnose using an ivar in a class method. 1843 if (IsClassMethod) 1844 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 1845 << IV->getDeclName()); 1846 1847 // If we're referencing an invalid decl, just return this as a silent 1848 // error node. The error diagnostic was already emitted on the decl. 1849 if (IV->isInvalidDecl()) 1850 return ExprError(); 1851 1852 // Check if referencing a field with __attribute__((deprecated)). 1853 if (DiagnoseUseOfDecl(IV, Loc)) 1854 return ExprError(); 1855 1856 // Diagnose the use of an ivar outside of the declaring class. 1857 if (IV->getAccessControl() == ObjCIvarDecl::Private && 1858 ClassDeclared != IFace) 1859 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 1860 1861 // FIXME: This should use a new expr for a direct reference, don't 1862 // turn this into Self->ivar, just return a BareIVarExpr or something. 1863 IdentifierInfo &II = Context.Idents.get("self"); 1864 UnqualifiedId SelfName; 1865 SelfName.setIdentifier(&II, SourceLocation()); 1866 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 1867 CXXScopeSpec SelfScopeSpec; 1868 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, 1869 SelfName, false, false); 1870 if (SelfExpr.isInvalid()) 1871 return ExprError(); 1872 1873 SelfExpr = DefaultLvalueConversion(SelfExpr.take()); 1874 if (SelfExpr.isInvalid()) 1875 return ExprError(); 1876 1877 MarkDeclarationReferenced(Loc, IV); 1878 return Owned(new (Context) 1879 ObjCIvarRefExpr(IV, IV->getType(), Loc, 1880 SelfExpr.take(), true, true)); 1881 } 1882 } else if (CurMethod->isInstanceMethod()) { 1883 // We should warn if a local variable hides an ivar. 1884 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 1885 ObjCInterfaceDecl *ClassDeclared; 1886 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 1887 if (IV->getAccessControl() != ObjCIvarDecl::Private || 1888 IFace == ClassDeclared) 1889 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 1890 } 1891 } 1892 1893 if (Lookup.empty() && II && AllowBuiltinCreation) { 1894 // FIXME. Consolidate this with similar code in LookupName. 1895 if (unsigned BuiltinID = II->getBuiltinID()) { 1896 if (!(getLangOptions().CPlusPlus && 1897 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 1898 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 1899 S, Lookup.isForRedeclaration(), 1900 Lookup.getNameLoc()); 1901 if (D) Lookup.addDecl(D); 1902 } 1903 } 1904 } 1905 // Sentinel value saying that we didn't do anything special. 1906 return Owned((Expr*) 0); 1907} 1908 1909/// \brief Cast a base object to a member's actual type. 1910/// 1911/// Logically this happens in three phases: 1912/// 1913/// * First we cast from the base type to the naming class. 1914/// The naming class is the class into which we were looking 1915/// when we found the member; it's the qualifier type if a 1916/// qualifier was provided, and otherwise it's the base type. 1917/// 1918/// * Next we cast from the naming class to the declaring class. 1919/// If the member we found was brought into a class's scope by 1920/// a using declaration, this is that class; otherwise it's 1921/// the class declaring the member. 1922/// 1923/// * Finally we cast from the declaring class to the "true" 1924/// declaring class of the member. This conversion does not 1925/// obey access control. 1926ExprResult 1927Sema::PerformObjectMemberConversion(Expr *From, 1928 NestedNameSpecifier *Qualifier, 1929 NamedDecl *FoundDecl, 1930 NamedDecl *Member) { 1931 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 1932 if (!RD) 1933 return Owned(From); 1934 1935 QualType DestRecordType; 1936 QualType DestType; 1937 QualType FromRecordType; 1938 QualType FromType = From->getType(); 1939 bool PointerConversions = false; 1940 if (isa<FieldDecl>(Member)) { 1941 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 1942 1943 if (FromType->getAs<PointerType>()) { 1944 DestType = Context.getPointerType(DestRecordType); 1945 FromRecordType = FromType->getPointeeType(); 1946 PointerConversions = true; 1947 } else { 1948 DestType = DestRecordType; 1949 FromRecordType = FromType; 1950 } 1951 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 1952 if (Method->isStatic()) 1953 return Owned(From); 1954 1955 DestType = Method->getThisType(Context); 1956 DestRecordType = DestType->getPointeeType(); 1957 1958 if (FromType->getAs<PointerType>()) { 1959 FromRecordType = FromType->getPointeeType(); 1960 PointerConversions = true; 1961 } else { 1962 FromRecordType = FromType; 1963 DestType = DestRecordType; 1964 } 1965 } else { 1966 // No conversion necessary. 1967 return Owned(From); 1968 } 1969 1970 if (DestType->isDependentType() || FromType->isDependentType()) 1971 return Owned(From); 1972 1973 // If the unqualified types are the same, no conversion is necessary. 1974 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 1975 return Owned(From); 1976 1977 SourceRange FromRange = From->getSourceRange(); 1978 SourceLocation FromLoc = FromRange.getBegin(); 1979 1980 ExprValueKind VK = CastCategory(From); 1981 1982 // C++ [class.member.lookup]p8: 1983 // [...] Ambiguities can often be resolved by qualifying a name with its 1984 // class name. 1985 // 1986 // If the member was a qualified name and the qualified referred to a 1987 // specific base subobject type, we'll cast to that intermediate type 1988 // first and then to the object in which the member is declared. That allows 1989 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 1990 // 1991 // class Base { public: int x; }; 1992 // class Derived1 : public Base { }; 1993 // class Derived2 : public Base { }; 1994 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 1995 // 1996 // void VeryDerived::f() { 1997 // x = 17; // error: ambiguous base subobjects 1998 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 1999 // } 2000 if (Qualifier) { 2001 QualType QType = QualType(Qualifier->getAsType(), 0); 2002 assert(!QType.isNull() && "lookup done with dependent qualifier?"); 2003 assert(QType->isRecordType() && "lookup done with non-record type"); 2004 2005 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2006 2007 // In C++98, the qualifier type doesn't actually have to be a base 2008 // type of the object type, in which case we just ignore it. 2009 // Otherwise build the appropriate casts. 2010 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2011 CXXCastPath BasePath; 2012 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2013 FromLoc, FromRange, &BasePath)) 2014 return ExprError(); 2015 2016 if (PointerConversions) 2017 QType = Context.getPointerType(QType); 2018 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2019 VK, &BasePath).take(); 2020 2021 FromType = QType; 2022 FromRecordType = QRecordType; 2023 2024 // If the qualifier type was the same as the destination type, 2025 // we're done. 2026 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2027 return Owned(From); 2028 } 2029 } 2030 2031 bool IgnoreAccess = false; 2032 2033 // If we actually found the member through a using declaration, cast 2034 // down to the using declaration's type. 2035 // 2036 // Pointer equality is fine here because only one declaration of a 2037 // class ever has member declarations. 2038 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2039 assert(isa<UsingShadowDecl>(FoundDecl)); 2040 QualType URecordType = Context.getTypeDeclType( 2041 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2042 2043 // We only need to do this if the naming-class to declaring-class 2044 // conversion is non-trivial. 2045 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2046 assert(IsDerivedFrom(FromRecordType, URecordType)); 2047 CXXCastPath BasePath; 2048 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2049 FromLoc, FromRange, &BasePath)) 2050 return ExprError(); 2051 2052 QualType UType = URecordType; 2053 if (PointerConversions) 2054 UType = Context.getPointerType(UType); 2055 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2056 VK, &BasePath).take(); 2057 FromType = UType; 2058 FromRecordType = URecordType; 2059 } 2060 2061 // We don't do access control for the conversion from the 2062 // declaring class to the true declaring class. 2063 IgnoreAccess = true; 2064 } 2065 2066 CXXCastPath BasePath; 2067 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2068 FromLoc, FromRange, &BasePath, 2069 IgnoreAccess)) 2070 return ExprError(); 2071 2072 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2073 VK, &BasePath); 2074} 2075 2076bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2077 const LookupResult &R, 2078 bool HasTrailingLParen) { 2079 // Only when used directly as the postfix-expression of a call. 2080 if (!HasTrailingLParen) 2081 return false; 2082 2083 // Never if a scope specifier was provided. 2084 if (SS.isSet()) 2085 return false; 2086 2087 // Only in C++ or ObjC++. 2088 if (!getLangOptions().CPlusPlus) 2089 return false; 2090 2091 // Turn off ADL when we find certain kinds of declarations during 2092 // normal lookup: 2093 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2094 NamedDecl *D = *I; 2095 2096 // C++0x [basic.lookup.argdep]p3: 2097 // -- a declaration of a class member 2098 // Since using decls preserve this property, we check this on the 2099 // original decl. 2100 if (D->isCXXClassMember()) 2101 return false; 2102 2103 // C++0x [basic.lookup.argdep]p3: 2104 // -- a block-scope function declaration that is not a 2105 // using-declaration 2106 // NOTE: we also trigger this for function templates (in fact, we 2107 // don't check the decl type at all, since all other decl types 2108 // turn off ADL anyway). 2109 if (isa<UsingShadowDecl>(D)) 2110 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2111 else if (D->getDeclContext()->isFunctionOrMethod()) 2112 return false; 2113 2114 // C++0x [basic.lookup.argdep]p3: 2115 // -- a declaration that is neither a function or a function 2116 // template 2117 // And also for builtin functions. 2118 if (isa<FunctionDecl>(D)) { 2119 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2120 2121 // But also builtin functions. 2122 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2123 return false; 2124 } else if (!isa<FunctionTemplateDecl>(D)) 2125 return false; 2126 } 2127 2128 return true; 2129} 2130 2131 2132/// Diagnoses obvious problems with the use of the given declaration 2133/// as an expression. This is only actually called for lookups that 2134/// were not overloaded, and it doesn't promise that the declaration 2135/// will in fact be used. 2136static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2137 if (isa<TypedefNameDecl>(D)) { 2138 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2139 return true; 2140 } 2141 2142 if (isa<ObjCInterfaceDecl>(D)) { 2143 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2144 return true; 2145 } 2146 2147 if (isa<NamespaceDecl>(D)) { 2148 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2149 return true; 2150 } 2151 2152 return false; 2153} 2154 2155ExprResult 2156Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2157 LookupResult &R, 2158 bool NeedsADL) { 2159 // If this is a single, fully-resolved result and we don't need ADL, 2160 // just build an ordinary singleton decl ref. 2161 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2162 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), 2163 R.getFoundDecl()); 2164 2165 // We only need to check the declaration if there's exactly one 2166 // result, because in the overloaded case the results can only be 2167 // functions and function templates. 2168 if (R.isSingleResult() && 2169 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2170 return ExprError(); 2171 2172 // Otherwise, just build an unresolved lookup expression. Suppress 2173 // any lookup-related diagnostics; we'll hash these out later, when 2174 // we've picked a target. 2175 R.suppressDiagnostics(); 2176 2177 UnresolvedLookupExpr *ULE 2178 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2179 SS.getWithLocInContext(Context), 2180 R.getLookupNameInfo(), 2181 NeedsADL, R.isOverloadedResult(), 2182 R.begin(), R.end()); 2183 2184 return Owned(ULE); 2185} 2186 2187/// \brief Complete semantic analysis for a reference to the given declaration. 2188ExprResult 2189Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2190 const DeclarationNameInfo &NameInfo, 2191 NamedDecl *D) { 2192 assert(D && "Cannot refer to a NULL declaration"); 2193 assert(!isa<FunctionTemplateDecl>(D) && 2194 "Cannot refer unambiguously to a function template"); 2195 2196 SourceLocation Loc = NameInfo.getLoc(); 2197 if (CheckDeclInExpr(*this, Loc, D)) 2198 return ExprError(); 2199 2200 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2201 // Specifically diagnose references to class templates that are missing 2202 // a template argument list. 2203 Diag(Loc, diag::err_template_decl_ref) 2204 << Template << SS.getRange(); 2205 Diag(Template->getLocation(), diag::note_template_decl_here); 2206 return ExprError(); 2207 } 2208 2209 // Make sure that we're referring to a value. 2210 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2211 if (!VD) { 2212 Diag(Loc, diag::err_ref_non_value) 2213 << D << SS.getRange(); 2214 Diag(D->getLocation(), diag::note_declared_at); 2215 return ExprError(); 2216 } 2217 2218 // Check whether this declaration can be used. Note that we suppress 2219 // this check when we're going to perform argument-dependent lookup 2220 // on this function name, because this might not be the function 2221 // that overload resolution actually selects. 2222 if (DiagnoseUseOfDecl(VD, Loc)) 2223 return ExprError(); 2224 2225 // Only create DeclRefExpr's for valid Decl's. 2226 if (VD->isInvalidDecl()) 2227 return ExprError(); 2228 2229 // Handle members of anonymous structs and unions. If we got here, 2230 // and the reference is to a class member indirect field, then this 2231 // must be the subject of a pointer-to-member expression. 2232 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2233 if (!indirectField->isCXXClassMember()) 2234 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2235 indirectField); 2236 2237 // If the identifier reference is inside a block, and it refers to a value 2238 // that is outside the block, create a BlockDeclRefExpr instead of a 2239 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when 2240 // the block is formed. 2241 // 2242 // We do not do this for things like enum constants, global variables, etc, 2243 // as they do not get snapshotted. 2244 // 2245 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) { 2246 case CR_Error: 2247 return ExprError(); 2248 2249 case CR_Capture: 2250 assert(!SS.isSet() && "referenced local variable with scope specifier?"); 2251 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false); 2252 2253 case CR_CaptureByRef: 2254 assert(!SS.isSet() && "referenced local variable with scope specifier?"); 2255 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true); 2256 2257 case CR_NoCapture: { 2258 // If this reference is not in a block or if the referenced 2259 // variable is within the block, create a normal DeclRefExpr. 2260 2261 QualType type = VD->getType(); 2262 ExprValueKind valueKind = VK_RValue; 2263 2264 switch (D->getKind()) { 2265 // Ignore all the non-ValueDecl kinds. 2266#define ABSTRACT_DECL(kind) 2267#define VALUE(type, base) 2268#define DECL(type, base) \ 2269 case Decl::type: 2270#include "clang/AST/DeclNodes.inc" 2271 llvm_unreachable("invalid value decl kind"); 2272 return ExprError(); 2273 2274 // These shouldn't make it here. 2275 case Decl::ObjCAtDefsField: 2276 case Decl::ObjCIvar: 2277 llvm_unreachable("forming non-member reference to ivar?"); 2278 return ExprError(); 2279 2280 // Enum constants are always r-values and never references. 2281 // Unresolved using declarations are dependent. 2282 case Decl::EnumConstant: 2283 case Decl::UnresolvedUsingValue: 2284 valueKind = VK_RValue; 2285 break; 2286 2287 // Fields and indirect fields that got here must be for 2288 // pointer-to-member expressions; we just call them l-values for 2289 // internal consistency, because this subexpression doesn't really 2290 // exist in the high-level semantics. 2291 case Decl::Field: 2292 case Decl::IndirectField: 2293 assert(getLangOptions().CPlusPlus && 2294 "building reference to field in C?"); 2295 2296 // These can't have reference type in well-formed programs, but 2297 // for internal consistency we do this anyway. 2298 type = type.getNonReferenceType(); 2299 valueKind = VK_LValue; 2300 break; 2301 2302 // Non-type template parameters are either l-values or r-values 2303 // depending on the type. 2304 case Decl::NonTypeTemplateParm: { 2305 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2306 type = reftype->getPointeeType(); 2307 valueKind = VK_LValue; // even if the parameter is an r-value reference 2308 break; 2309 } 2310 2311 // For non-references, we need to strip qualifiers just in case 2312 // the template parameter was declared as 'const int' or whatever. 2313 valueKind = VK_RValue; 2314 type = type.getUnqualifiedType(); 2315 break; 2316 } 2317 2318 case Decl::Var: 2319 // In C, "extern void blah;" is valid and is an r-value. 2320 if (!getLangOptions().CPlusPlus && 2321 !type.hasQualifiers() && 2322 type->isVoidType()) { 2323 valueKind = VK_RValue; 2324 break; 2325 } 2326 // fallthrough 2327 2328 case Decl::ImplicitParam: 2329 case Decl::ParmVar: 2330 // These are always l-values. 2331 valueKind = VK_LValue; 2332 type = type.getNonReferenceType(); 2333 break; 2334 2335 case Decl::Function: { 2336 const FunctionType *fty = type->castAs<FunctionType>(); 2337 2338 // If we're referring to a function with an __unknown_anytype 2339 // result type, make the entire expression __unknown_anytype. 2340 if (fty->getResultType() == Context.UnknownAnyTy) { 2341 type = Context.UnknownAnyTy; 2342 valueKind = VK_RValue; 2343 break; 2344 } 2345 2346 // Functions are l-values in C++. 2347 if (getLangOptions().CPlusPlus) { 2348 valueKind = VK_LValue; 2349 break; 2350 } 2351 2352 // C99 DR 316 says that, if a function type comes from a 2353 // function definition (without a prototype), that type is only 2354 // used for checking compatibility. Therefore, when referencing 2355 // the function, we pretend that we don't have the full function 2356 // type. 2357 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2358 isa<FunctionProtoType>(fty)) 2359 type = Context.getFunctionNoProtoType(fty->getResultType(), 2360 fty->getExtInfo()); 2361 2362 // Functions are r-values in C. 2363 valueKind = VK_RValue; 2364 break; 2365 } 2366 2367 case Decl::CXXMethod: 2368 // If we're referring to a method with an __unknown_anytype 2369 // result type, make the entire expression __unknown_anytype. 2370 // This should only be possible with a type written directly. 2371 if (const FunctionProtoType *proto 2372 = dyn_cast<FunctionProtoType>(VD->getType())) 2373 if (proto->getResultType() == Context.UnknownAnyTy) { 2374 type = Context.UnknownAnyTy; 2375 valueKind = VK_RValue; 2376 break; 2377 } 2378 2379 // C++ methods are l-values if static, r-values if non-static. 2380 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2381 valueKind = VK_LValue; 2382 break; 2383 } 2384 // fallthrough 2385 2386 case Decl::CXXConversion: 2387 case Decl::CXXDestructor: 2388 case Decl::CXXConstructor: 2389 valueKind = VK_RValue; 2390 break; 2391 } 2392 2393 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS); 2394 } 2395 2396 } 2397 2398 llvm_unreachable("unknown capture result"); 2399 return ExprError(); 2400} 2401 2402ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 2403 PredefinedExpr::IdentType IT; 2404 2405 switch (Kind) { 2406 default: assert(0 && "Unknown simple primary expr!"); 2407 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 2408 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 2409 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 2410 } 2411 2412 // Pre-defined identifiers are of type char[x], where x is the length of the 2413 // string. 2414 2415 Decl *currentDecl = getCurFunctionOrMethodDecl(); 2416 if (!currentDecl && getCurBlock()) 2417 currentDecl = getCurBlock()->TheDecl; 2418 if (!currentDecl) { 2419 Diag(Loc, diag::ext_predef_outside_function); 2420 currentDecl = Context.getTranslationUnitDecl(); 2421 } 2422 2423 QualType ResTy; 2424 if (cast<DeclContext>(currentDecl)->isDependentContext()) { 2425 ResTy = Context.DependentTy; 2426 } else { 2427 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 2428 2429 llvm::APInt LengthI(32, Length + 1); 2430 ResTy = Context.CharTy.withConst(); 2431 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 2432 } 2433 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 2434} 2435 2436ExprResult Sema::ActOnCharacterConstant(const Token &Tok) { 2437 llvm::SmallString<16> CharBuffer; 2438 bool Invalid = false; 2439 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 2440 if (Invalid) 2441 return ExprError(); 2442 2443 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 2444 PP, Tok.getKind()); 2445 if (Literal.hadError()) 2446 return ExprError(); 2447 2448 QualType Ty; 2449 if (!getLangOptions().CPlusPlus) 2450 Ty = Context.IntTy; // 'x' and L'x' -> int in C. 2451 else if (Literal.isWide()) 2452 Ty = Context.WCharTy; // L'x' -> wchar_t in C++. 2453 else if (Literal.isUTF16()) 2454 Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x. 2455 else if (Literal.isUTF32()) 2456 Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x. 2457 else if (Literal.isMultiChar()) 2458 Ty = Context.IntTy; // 'wxyz' -> int in C++. 2459 else 2460 Ty = Context.CharTy; // 'x' -> char in C++ 2461 2462 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 2463 if (Literal.isWide()) 2464 Kind = CharacterLiteral::Wide; 2465 else if (Literal.isUTF16()) 2466 Kind = CharacterLiteral::UTF16; 2467 else if (Literal.isUTF32()) 2468 Kind = CharacterLiteral::UTF32; 2469 2470 return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 2471 Tok.getLocation())); 2472} 2473 2474ExprResult Sema::ActOnNumericConstant(const Token &Tok) { 2475 // Fast path for a single digit (which is quite common). A single digit 2476 // cannot have a trigraph, escaped newline, radix prefix, or type suffix. 2477 if (Tok.getLength() == 1) { 2478 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 2479 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2480 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'), 2481 Context.IntTy, Tok.getLocation())); 2482 } 2483 2484 llvm::SmallString<512> IntegerBuffer; 2485 // Add padding so that NumericLiteralParser can overread by one character. 2486 IntegerBuffer.resize(Tok.getLength()+1); 2487 const char *ThisTokBegin = &IntegerBuffer[0]; 2488 2489 // Get the spelling of the token, which eliminates trigraphs, etc. 2490 bool Invalid = false; 2491 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid); 2492 if (Invalid) 2493 return ExprError(); 2494 2495 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength, 2496 Tok.getLocation(), PP); 2497 if (Literal.hadError) 2498 return ExprError(); 2499 2500 Expr *Res; 2501 2502 if (Literal.isFloatingLiteral()) { 2503 QualType Ty; 2504 if (Literal.isFloat) 2505 Ty = Context.FloatTy; 2506 else if (!Literal.isLong) 2507 Ty = Context.DoubleTy; 2508 else 2509 Ty = Context.LongDoubleTy; 2510 2511 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty); 2512 2513 using llvm::APFloat; 2514 APFloat Val(Format); 2515 2516 APFloat::opStatus result = Literal.GetFloatValue(Val); 2517 2518 // Overflow is always an error, but underflow is only an error if 2519 // we underflowed to zero (APFloat reports denormals as underflow). 2520 if ((result & APFloat::opOverflow) || 2521 ((result & APFloat::opUnderflow) && Val.isZero())) { 2522 unsigned diagnostic; 2523 llvm::SmallString<20> buffer; 2524 if (result & APFloat::opOverflow) { 2525 diagnostic = diag::warn_float_overflow; 2526 APFloat::getLargest(Format).toString(buffer); 2527 } else { 2528 diagnostic = diag::warn_float_underflow; 2529 APFloat::getSmallest(Format).toString(buffer); 2530 } 2531 2532 Diag(Tok.getLocation(), diagnostic) 2533 << Ty 2534 << StringRef(buffer.data(), buffer.size()); 2535 } 2536 2537 bool isExact = (result == APFloat::opOK); 2538 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation()); 2539 2540 if (Ty == Context.DoubleTy) { 2541 if (getLangOptions().SinglePrecisionConstants) { 2542 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 2543 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) { 2544 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 2545 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 2546 } 2547 } 2548 } else if (!Literal.isIntegerLiteral()) { 2549 return ExprError(); 2550 } else { 2551 QualType Ty; 2552 2553 // long long is a C99 feature. 2554 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x && 2555 Literal.isLongLong) 2556 Diag(Tok.getLocation(), diag::ext_longlong); 2557 2558 // Get the value in the widest-possible width. 2559 llvm::APInt ResultVal(Context.getTargetInfo().getIntMaxTWidth(), 0); 2560 2561 if (Literal.GetIntegerValue(ResultVal)) { 2562 // If this value didn't fit into uintmax_t, warn and force to ull. 2563 Diag(Tok.getLocation(), diag::warn_integer_too_large); 2564 Ty = Context.UnsignedLongLongTy; 2565 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 2566 "long long is not intmax_t?"); 2567 } else { 2568 // If this value fits into a ULL, try to figure out what else it fits into 2569 // according to the rules of C99 6.4.4.1p5. 2570 2571 // Octal, Hexadecimal, and integers with a U suffix are allowed to 2572 // be an unsigned int. 2573 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 2574 2575 // Check from smallest to largest, picking the smallest type we can. 2576 unsigned Width = 0; 2577 if (!Literal.isLong && !Literal.isLongLong) { 2578 // Are int/unsigned possibilities? 2579 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2580 2581 // Does it fit in a unsigned int? 2582 if (ResultVal.isIntN(IntSize)) { 2583 // Does it fit in a signed int? 2584 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 2585 Ty = Context.IntTy; 2586 else if (AllowUnsigned) 2587 Ty = Context.UnsignedIntTy; 2588 Width = IntSize; 2589 } 2590 } 2591 2592 // Are long/unsigned long possibilities? 2593 if (Ty.isNull() && !Literal.isLongLong) { 2594 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 2595 2596 // Does it fit in a unsigned long? 2597 if (ResultVal.isIntN(LongSize)) { 2598 // Does it fit in a signed long? 2599 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 2600 Ty = Context.LongTy; 2601 else if (AllowUnsigned) 2602 Ty = Context.UnsignedLongTy; 2603 Width = LongSize; 2604 } 2605 } 2606 2607 // Finally, check long long if needed. 2608 if (Ty.isNull()) { 2609 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 2610 2611 // Does it fit in a unsigned long long? 2612 if (ResultVal.isIntN(LongLongSize)) { 2613 // Does it fit in a signed long long? 2614 // To be compatible with MSVC, hex integer literals ending with the 2615 // LL or i64 suffix are always signed in Microsoft mode. 2616 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 2617 (getLangOptions().Microsoft && Literal.isLongLong))) 2618 Ty = Context.LongLongTy; 2619 else if (AllowUnsigned) 2620 Ty = Context.UnsignedLongLongTy; 2621 Width = LongLongSize; 2622 } 2623 } 2624 2625 // If we still couldn't decide a type, we probably have something that 2626 // does not fit in a signed long long, but has no U suffix. 2627 if (Ty.isNull()) { 2628 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 2629 Ty = Context.UnsignedLongLongTy; 2630 Width = Context.getTargetInfo().getLongLongWidth(); 2631 } 2632 2633 if (ResultVal.getBitWidth() != Width) 2634 ResultVal = ResultVal.trunc(Width); 2635 } 2636 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 2637 } 2638 2639 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 2640 if (Literal.isImaginary) 2641 Res = new (Context) ImaginaryLiteral(Res, 2642 Context.getComplexType(Res->getType())); 2643 2644 return Owned(Res); 2645} 2646 2647ExprResult Sema::ActOnParenExpr(SourceLocation L, 2648 SourceLocation R, Expr *E) { 2649 assert((E != 0) && "ActOnParenExpr() missing expr"); 2650 return Owned(new (Context) ParenExpr(L, R, E)); 2651} 2652 2653static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 2654 SourceLocation Loc, 2655 SourceRange ArgRange) { 2656 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 2657 // scalar or vector data type argument..." 2658 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 2659 // type (C99 6.2.5p18) or void. 2660 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 2661 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 2662 << T << ArgRange; 2663 return true; 2664 } 2665 2666 assert((T->isVoidType() || !T->isIncompleteType()) && 2667 "Scalar types should always be complete"); 2668 return false; 2669} 2670 2671static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 2672 SourceLocation Loc, 2673 SourceRange ArgRange, 2674 UnaryExprOrTypeTrait TraitKind) { 2675 // C99 6.5.3.4p1: 2676 if (T->isFunctionType()) { 2677 // alignof(function) is allowed as an extension. 2678 if (TraitKind == UETT_SizeOf) 2679 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange; 2680 return false; 2681 } 2682 2683 // Allow sizeof(void)/alignof(void) as an extension. 2684 if (T->isVoidType()) { 2685 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange; 2686 return false; 2687 } 2688 2689 return true; 2690} 2691 2692static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 2693 SourceLocation Loc, 2694 SourceRange ArgRange, 2695 UnaryExprOrTypeTrait TraitKind) { 2696 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode. 2697 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) { 2698 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 2699 << T << (TraitKind == UETT_SizeOf) 2700 << ArgRange; 2701 return true; 2702 } 2703 2704 return false; 2705} 2706 2707/// \brief Check the constrains on expression operands to unary type expression 2708/// and type traits. 2709/// 2710/// Completes any types necessary and validates the constraints on the operand 2711/// expression. The logic mostly mirrors the type-based overload, but may modify 2712/// the expression as it completes the type for that expression through template 2713/// instantiation, etc. 2714bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *Op, 2715 UnaryExprOrTypeTrait ExprKind) { 2716 QualType ExprTy = Op->getType(); 2717 2718 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 2719 // the result is the size of the referenced type." 2720 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 2721 // result shall be the alignment of the referenced type." 2722 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>()) 2723 ExprTy = Ref->getPointeeType(); 2724 2725 if (ExprKind == UETT_VecStep) 2726 return CheckVecStepTraitOperandType(*this, ExprTy, Op->getExprLoc(), 2727 Op->getSourceRange()); 2728 2729 // Whitelist some types as extensions 2730 if (!CheckExtensionTraitOperandType(*this, ExprTy, Op->getExprLoc(), 2731 Op->getSourceRange(), ExprKind)) 2732 return false; 2733 2734 if (RequireCompleteExprType(Op, 2735 PDiag(diag::err_sizeof_alignof_incomplete_type) 2736 << ExprKind << Op->getSourceRange(), 2737 std::make_pair(SourceLocation(), PDiag(0)))) 2738 return true; 2739 2740 // Completeing the expression's type may have changed it. 2741 ExprTy = Op->getType(); 2742 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>()) 2743 ExprTy = Ref->getPointeeType(); 2744 2745 if (CheckObjCTraitOperandConstraints(*this, ExprTy, Op->getExprLoc(), 2746 Op->getSourceRange(), ExprKind)) 2747 return true; 2748 2749 if (ExprKind == UETT_SizeOf) { 2750 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(Op->IgnoreParens())) { 2751 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 2752 QualType OType = PVD->getOriginalType(); 2753 QualType Type = PVD->getType(); 2754 if (Type->isPointerType() && OType->isArrayType()) { 2755 Diag(Op->getExprLoc(), diag::warn_sizeof_array_param) 2756 << Type << OType; 2757 Diag(PVD->getLocation(), diag::note_declared_at); 2758 } 2759 } 2760 } 2761 } 2762 2763 return false; 2764} 2765 2766/// \brief Check the constraints on operands to unary expression and type 2767/// traits. 2768/// 2769/// This will complete any types necessary, and validate the various constraints 2770/// on those operands. 2771/// 2772/// The UsualUnaryConversions() function is *not* called by this routine. 2773/// C99 6.3.2.1p[2-4] all state: 2774/// Except when it is the operand of the sizeof operator ... 2775/// 2776/// C++ [expr.sizeof]p4 2777/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 2778/// standard conversions are not applied to the operand of sizeof. 2779/// 2780/// This policy is followed for all of the unary trait expressions. 2781bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType exprType, 2782 SourceLocation OpLoc, 2783 SourceRange ExprRange, 2784 UnaryExprOrTypeTrait ExprKind) { 2785 if (exprType->isDependentType()) 2786 return false; 2787 2788 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 2789 // the result is the size of the referenced type." 2790 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 2791 // result shall be the alignment of the referenced type." 2792 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>()) 2793 exprType = Ref->getPointeeType(); 2794 2795 if (ExprKind == UETT_VecStep) 2796 return CheckVecStepTraitOperandType(*this, exprType, OpLoc, ExprRange); 2797 2798 // Whitelist some types as extensions 2799 if (!CheckExtensionTraitOperandType(*this, exprType, OpLoc, ExprRange, 2800 ExprKind)) 2801 return false; 2802 2803 if (RequireCompleteType(OpLoc, exprType, 2804 PDiag(diag::err_sizeof_alignof_incomplete_type) 2805 << ExprKind << ExprRange)) 2806 return true; 2807 2808 if (CheckObjCTraitOperandConstraints(*this, exprType, OpLoc, ExprRange, 2809 ExprKind)) 2810 return true; 2811 2812 return false; 2813} 2814 2815static bool CheckAlignOfExpr(Sema &S, Expr *E) { 2816 E = E->IgnoreParens(); 2817 2818 // alignof decl is always ok. 2819 if (isa<DeclRefExpr>(E)) 2820 return false; 2821 2822 // Cannot know anything else if the expression is dependent. 2823 if (E->isTypeDependent()) 2824 return false; 2825 2826 if (E->getBitField()) { 2827 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) 2828 << 1 << E->getSourceRange(); 2829 return true; 2830 } 2831 2832 // Alignment of a field access is always okay, so long as it isn't a 2833 // bit-field. 2834 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) 2835 if (isa<FieldDecl>(ME->getMemberDecl())) 2836 return false; 2837 2838 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 2839} 2840 2841bool Sema::CheckVecStepExpr(Expr *E) { 2842 E = E->IgnoreParens(); 2843 2844 // Cannot know anything else if the expression is dependent. 2845 if (E->isTypeDependent()) 2846 return false; 2847 2848 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 2849} 2850 2851/// \brief Build a sizeof or alignof expression given a type operand. 2852ExprResult 2853Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 2854 SourceLocation OpLoc, 2855 UnaryExprOrTypeTrait ExprKind, 2856 SourceRange R) { 2857 if (!TInfo) 2858 return ExprError(); 2859 2860 QualType T = TInfo->getType(); 2861 2862 if (!T->isDependentType() && 2863 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 2864 return ExprError(); 2865 2866 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 2867 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo, 2868 Context.getSizeType(), 2869 OpLoc, R.getEnd())); 2870} 2871 2872/// \brief Build a sizeof or alignof expression given an expression 2873/// operand. 2874ExprResult 2875Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 2876 UnaryExprOrTypeTrait ExprKind) { 2877 ExprResult PE = CheckPlaceholderExpr(E); 2878 if (PE.isInvalid()) 2879 return ExprError(); 2880 2881 E = PE.get(); 2882 2883 // Verify that the operand is valid. 2884 bool isInvalid = false; 2885 if (E->isTypeDependent()) { 2886 // Delay type-checking for type-dependent expressions. 2887 } else if (ExprKind == UETT_AlignOf) { 2888 isInvalid = CheckAlignOfExpr(*this, E); 2889 } else if (ExprKind == UETT_VecStep) { 2890 isInvalid = CheckVecStepExpr(E); 2891 } else if (E->getBitField()) { // C99 6.5.3.4p1. 2892 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0; 2893 isInvalid = true; 2894 } else { 2895 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 2896 } 2897 2898 if (isInvalid) 2899 return ExprError(); 2900 2901 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 2902 return Owned(new (Context) UnaryExprOrTypeTraitExpr( 2903 ExprKind, E, Context.getSizeType(), OpLoc, 2904 E->getSourceRange().getEnd())); 2905} 2906 2907/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 2908/// expr and the same for @c alignof and @c __alignof 2909/// Note that the ArgRange is invalid if isType is false. 2910ExprResult 2911Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 2912 UnaryExprOrTypeTrait ExprKind, bool isType, 2913 void *TyOrEx, const SourceRange &ArgRange) { 2914 // If error parsing type, ignore. 2915 if (TyOrEx == 0) return ExprError(); 2916 2917 if (isType) { 2918 TypeSourceInfo *TInfo; 2919 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 2920 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 2921 } 2922 2923 Expr *ArgEx = (Expr *)TyOrEx; 2924 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 2925 return move(Result); 2926} 2927 2928static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 2929 bool isReal) { 2930 if (V.get()->isTypeDependent()) 2931 return S.Context.DependentTy; 2932 2933 // _Real and _Imag are only l-values for normal l-values. 2934 if (V.get()->getObjectKind() != OK_Ordinary) { 2935 V = S.DefaultLvalueConversion(V.take()); 2936 if (V.isInvalid()) 2937 return QualType(); 2938 } 2939 2940 // These operators return the element type of a complex type. 2941 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 2942 return CT->getElementType(); 2943 2944 // Otherwise they pass through real integer and floating point types here. 2945 if (V.get()->getType()->isArithmeticType()) 2946 return V.get()->getType(); 2947 2948 // Test for placeholders. 2949 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 2950 if (PR.isInvalid()) return QualType(); 2951 if (PR.get() != V.get()) { 2952 V = move(PR); 2953 return CheckRealImagOperand(S, V, Loc, isReal); 2954 } 2955 2956 // Reject anything else. 2957 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 2958 << (isReal ? "__real" : "__imag"); 2959 return QualType(); 2960} 2961 2962 2963 2964ExprResult 2965Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 2966 tok::TokenKind Kind, Expr *Input) { 2967 UnaryOperatorKind Opc; 2968 switch (Kind) { 2969 default: assert(0 && "Unknown unary op!"); 2970 case tok::plusplus: Opc = UO_PostInc; break; 2971 case tok::minusminus: Opc = UO_PostDec; break; 2972 } 2973 2974 return BuildUnaryOp(S, OpLoc, Opc, Input); 2975} 2976 2977ExprResult 2978Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, 2979 Expr *Idx, SourceLocation RLoc) { 2980 // Since this might be a postfix expression, get rid of ParenListExprs. 2981 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 2982 if (Result.isInvalid()) return ExprError(); 2983 Base = Result.take(); 2984 2985 Expr *LHSExp = Base, *RHSExp = Idx; 2986 2987 if (getLangOptions().CPlusPlus && 2988 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) { 2989 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 2990 Context.DependentTy, 2991 VK_LValue, OK_Ordinary, 2992 RLoc)); 2993 } 2994 2995 if (getLangOptions().CPlusPlus && 2996 (LHSExp->getType()->isRecordType() || 2997 LHSExp->getType()->isEnumeralType() || 2998 RHSExp->getType()->isRecordType() || 2999 RHSExp->getType()->isEnumeralType())) { 3000 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx); 3001 } 3002 3003 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc); 3004} 3005 3006 3007ExprResult 3008Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 3009 Expr *Idx, SourceLocation RLoc) { 3010 Expr *LHSExp = Base; 3011 Expr *RHSExp = Idx; 3012 3013 // Perform default conversions. 3014 if (!LHSExp->getType()->getAs<VectorType>()) { 3015 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 3016 if (Result.isInvalid()) 3017 return ExprError(); 3018 LHSExp = Result.take(); 3019 } 3020 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 3021 if (Result.isInvalid()) 3022 return ExprError(); 3023 RHSExp = Result.take(); 3024 3025 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 3026 ExprValueKind VK = VK_LValue; 3027 ExprObjectKind OK = OK_Ordinary; 3028 3029 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 3030 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 3031 // in the subscript position. As a result, we need to derive the array base 3032 // and index from the expression types. 3033 Expr *BaseExpr, *IndexExpr; 3034 QualType ResultType; 3035 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 3036 BaseExpr = LHSExp; 3037 IndexExpr = RHSExp; 3038 ResultType = Context.DependentTy; 3039 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 3040 BaseExpr = LHSExp; 3041 IndexExpr = RHSExp; 3042 ResultType = PTy->getPointeeType(); 3043 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 3044 // Handle the uncommon case of "123[Ptr]". 3045 BaseExpr = RHSExp; 3046 IndexExpr = LHSExp; 3047 ResultType = PTy->getPointeeType(); 3048 } else if (const ObjCObjectPointerType *PTy = 3049 LHSTy->getAs<ObjCObjectPointerType>()) { 3050 BaseExpr = LHSExp; 3051 IndexExpr = RHSExp; 3052 ResultType = PTy->getPointeeType(); 3053 } else if (const ObjCObjectPointerType *PTy = 3054 RHSTy->getAs<ObjCObjectPointerType>()) { 3055 // Handle the uncommon case of "123[Ptr]". 3056 BaseExpr = RHSExp; 3057 IndexExpr = LHSExp; 3058 ResultType = PTy->getPointeeType(); 3059 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 3060 BaseExpr = LHSExp; // vectors: V[123] 3061 IndexExpr = RHSExp; 3062 VK = LHSExp->getValueKind(); 3063 if (VK != VK_RValue) 3064 OK = OK_VectorComponent; 3065 3066 // FIXME: need to deal with const... 3067 ResultType = VTy->getElementType(); 3068 } else if (LHSTy->isArrayType()) { 3069 // If we see an array that wasn't promoted by 3070 // DefaultFunctionArrayLvalueConversion, it must be an array that 3071 // wasn't promoted because of the C90 rule that doesn't 3072 // allow promoting non-lvalue arrays. Warn, then 3073 // force the promotion here. 3074 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3075 LHSExp->getSourceRange(); 3076 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 3077 CK_ArrayToPointerDecay).take(); 3078 LHSTy = LHSExp->getType(); 3079 3080 BaseExpr = LHSExp; 3081 IndexExpr = RHSExp; 3082 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 3083 } else if (RHSTy->isArrayType()) { 3084 // Same as previous, except for 123[f().a] case 3085 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3086 RHSExp->getSourceRange(); 3087 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 3088 CK_ArrayToPointerDecay).take(); 3089 RHSTy = RHSExp->getType(); 3090 3091 BaseExpr = RHSExp; 3092 IndexExpr = LHSExp; 3093 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 3094 } else { 3095 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 3096 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 3097 } 3098 // C99 6.5.2.1p1 3099 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 3100 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 3101 << IndexExpr->getSourceRange()); 3102 3103 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 3104 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 3105 && !IndexExpr->isTypeDependent()) 3106 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 3107 3108 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 3109 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 3110 // type. Note that Functions are not objects, and that (in C99 parlance) 3111 // incomplete types are not object types. 3112 if (ResultType->isFunctionType()) { 3113 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 3114 << ResultType << BaseExpr->getSourceRange(); 3115 return ExprError(); 3116 } 3117 3118 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) { 3119 // GNU extension: subscripting on pointer to void 3120 Diag(LLoc, diag::ext_gnu_subscript_void_type) 3121 << BaseExpr->getSourceRange(); 3122 3123 // C forbids expressions of unqualified void type from being l-values. 3124 // See IsCForbiddenLValueType. 3125 if (!ResultType.hasQualifiers()) VK = VK_RValue; 3126 } else if (!ResultType->isDependentType() && 3127 RequireCompleteType(LLoc, ResultType, 3128 PDiag(diag::err_subscript_incomplete_type) 3129 << BaseExpr->getSourceRange())) 3130 return ExprError(); 3131 3132 // Diagnose bad cases where we step over interface counts. 3133 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) { 3134 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3135 << ResultType << BaseExpr->getSourceRange(); 3136 return ExprError(); 3137 } 3138 3139 assert(VK == VK_RValue || LangOpts.CPlusPlus || 3140 !ResultType.isCForbiddenLValueType()); 3141 3142 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 3143 ResultType, VK, OK, RLoc)); 3144} 3145 3146ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3147 FunctionDecl *FD, 3148 ParmVarDecl *Param) { 3149 if (Param->hasUnparsedDefaultArg()) { 3150 Diag(CallLoc, 3151 diag::err_use_of_default_argument_to_function_declared_later) << 3152 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 3153 Diag(UnparsedDefaultArgLocs[Param], 3154 diag::note_default_argument_declared_here); 3155 return ExprError(); 3156 } 3157 3158 if (Param->hasUninstantiatedDefaultArg()) { 3159 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 3160 3161 // Instantiate the expression. 3162 MultiLevelTemplateArgumentList ArgList 3163 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true); 3164 3165 std::pair<const TemplateArgument *, unsigned> Innermost 3166 = ArgList.getInnermost(); 3167 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first, 3168 Innermost.second); 3169 3170 ExprResult Result; 3171 { 3172 // C++ [dcl.fct.default]p5: 3173 // The names in the [default argument] expression are bound, and 3174 // the semantic constraints are checked, at the point where the 3175 // default argument expression appears. 3176 ContextRAII SavedContext(*this, FD); 3177 Result = SubstExpr(UninstExpr, ArgList); 3178 } 3179 if (Result.isInvalid()) 3180 return ExprError(); 3181 3182 // Check the expression as an initializer for the parameter. 3183 InitializedEntity Entity 3184 = InitializedEntity::InitializeParameter(Context, Param); 3185 InitializationKind Kind 3186 = InitializationKind::CreateCopy(Param->getLocation(), 3187 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin()); 3188 Expr *ResultE = Result.takeAs<Expr>(); 3189 3190 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1); 3191 Result = InitSeq.Perform(*this, Entity, Kind, 3192 MultiExprArg(*this, &ResultE, 1)); 3193 if (Result.isInvalid()) 3194 return ExprError(); 3195 3196 // Build the default argument expression. 3197 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, 3198 Result.takeAs<Expr>())); 3199 } 3200 3201 // If the default expression creates temporaries, we need to 3202 // push them to the current stack of expression temporaries so they'll 3203 // be properly destroyed. 3204 // FIXME: We should really be rebuilding the default argument with new 3205 // bound temporaries; see the comment in PR5810. 3206 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) { 3207 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i); 3208 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(), 3209 const_cast<CXXDestructorDecl*>(Temporary->getDestructor())); 3210 ExprTemporaries.push_back(Temporary); 3211 ExprNeedsCleanups = true; 3212 } 3213 3214 // We already type-checked the argument, so we know it works. 3215 // Just mark all of the declarations in this potentially-evaluated expression 3216 // as being "referenced". 3217 MarkDeclarationsReferencedInExpr(Param->getDefaultArg()); 3218 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param)); 3219} 3220 3221/// ConvertArgumentsForCall - Converts the arguments specified in 3222/// Args/NumArgs to the parameter types of the function FDecl with 3223/// function prototype Proto. Call is the call expression itself, and 3224/// Fn is the function expression. For a C++ member function, this 3225/// routine does not attempt to convert the object argument. Returns 3226/// true if the call is ill-formed. 3227bool 3228Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 3229 FunctionDecl *FDecl, 3230 const FunctionProtoType *Proto, 3231 Expr **Args, unsigned NumArgs, 3232 SourceLocation RParenLoc) { 3233 // Bail out early if calling a builtin with custom typechecking. 3234 // We don't need to do this in the 3235 if (FDecl) 3236 if (unsigned ID = FDecl->getBuiltinID()) 3237 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 3238 return false; 3239 3240 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 3241 // assignment, to the types of the corresponding parameter, ... 3242 unsigned NumArgsInProto = Proto->getNumArgs(); 3243 bool Invalid = false; 3244 3245 // If too few arguments are available (and we don't have default 3246 // arguments for the remaining parameters), don't make the call. 3247 if (NumArgs < NumArgsInProto) { 3248 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments()) { 3249 Diag(RParenLoc, diag::err_typecheck_call_too_few_args) 3250 << Fn->getType()->isBlockPointerType() 3251 << NumArgsInProto << NumArgs << Fn->getSourceRange(); 3252 3253 // Emit the location of the prototype. 3254 if (FDecl && !FDecl->getBuiltinID()) 3255 Diag(FDecl->getLocStart(), diag::note_callee_decl) 3256 << FDecl; 3257 3258 return true; 3259 } 3260 Call->setNumArgs(Context, NumArgsInProto); 3261 } 3262 3263 // If too many are passed and not variadic, error on the extras and drop 3264 // them. 3265 if (NumArgs > NumArgsInProto) { 3266 if (!Proto->isVariadic()) { 3267 Diag(Args[NumArgsInProto]->getLocStart(), 3268 diag::err_typecheck_call_too_many_args) 3269 << Fn->getType()->isBlockPointerType() 3270 << NumArgsInProto << NumArgs << Fn->getSourceRange() 3271 << SourceRange(Args[NumArgsInProto]->getLocStart(), 3272 Args[NumArgs-1]->getLocEnd()); 3273 3274 // Emit the location of the prototype. 3275 if (FDecl && !FDecl->getBuiltinID()) 3276 Diag(FDecl->getLocStart(), diag::note_callee_decl) 3277 << FDecl; 3278 3279 // This deletes the extra arguments. 3280 Call->setNumArgs(Context, NumArgsInProto); 3281 return true; 3282 } 3283 } 3284 SmallVector<Expr *, 8> AllArgs; 3285 VariadicCallType CallType = 3286 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply; 3287 if (Fn->getType()->isBlockPointerType()) 3288 CallType = VariadicBlock; // Block 3289 else if (isa<MemberExpr>(Fn)) 3290 CallType = VariadicMethod; 3291 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl, 3292 Proto, 0, Args, NumArgs, AllArgs, CallType); 3293 if (Invalid) 3294 return true; 3295 unsigned TotalNumArgs = AllArgs.size(); 3296 for (unsigned i = 0; i < TotalNumArgs; ++i) 3297 Call->setArg(i, AllArgs[i]); 3298 3299 return false; 3300} 3301 3302bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, 3303 FunctionDecl *FDecl, 3304 const FunctionProtoType *Proto, 3305 unsigned FirstProtoArg, 3306 Expr **Args, unsigned NumArgs, 3307 SmallVector<Expr *, 8> &AllArgs, 3308 VariadicCallType CallType) { 3309 unsigned NumArgsInProto = Proto->getNumArgs(); 3310 unsigned NumArgsToCheck = NumArgs; 3311 bool Invalid = false; 3312 if (NumArgs != NumArgsInProto) 3313 // Use default arguments for missing arguments 3314 NumArgsToCheck = NumArgsInProto; 3315 unsigned ArgIx = 0; 3316 // Continue to check argument types (even if we have too few/many args). 3317 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) { 3318 QualType ProtoArgType = Proto->getArgType(i); 3319 3320 Expr *Arg; 3321 if (ArgIx < NumArgs) { 3322 Arg = Args[ArgIx++]; 3323 3324 if (RequireCompleteType(Arg->getSourceRange().getBegin(), 3325 ProtoArgType, 3326 PDiag(diag::err_call_incomplete_argument) 3327 << Arg->getSourceRange())) 3328 return true; 3329 3330 // Pass the argument 3331 ParmVarDecl *Param = 0; 3332 if (FDecl && i < FDecl->getNumParams()) 3333 Param = FDecl->getParamDecl(i); 3334 3335 InitializedEntity Entity = 3336 Param? InitializedEntity::InitializeParameter(Context, Param) 3337 : InitializedEntity::InitializeParameter(Context, ProtoArgType, 3338 Proto->isArgConsumed(i)); 3339 ExprResult ArgE = PerformCopyInitialization(Entity, 3340 SourceLocation(), 3341 Owned(Arg)); 3342 if (ArgE.isInvalid()) 3343 return true; 3344 3345 Arg = ArgE.takeAs<Expr>(); 3346 } else { 3347 ParmVarDecl *Param = FDecl->getParamDecl(i); 3348 3349 ExprResult ArgExpr = 3350 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 3351 if (ArgExpr.isInvalid()) 3352 return true; 3353 3354 Arg = ArgExpr.takeAs<Expr>(); 3355 } 3356 3357 // Check for array bounds violations for each argument to the call. This 3358 // check only triggers warnings when the argument isn't a more complex Expr 3359 // with its own checking, such as a BinaryOperator. 3360 CheckArrayAccess(Arg); 3361 3362 AllArgs.push_back(Arg); 3363 } 3364 3365 // If this is a variadic call, handle args passed through "...". 3366 if (CallType != VariadicDoesNotApply) { 3367 3368 // Assume that extern "C" functions with variadic arguments that 3369 // return __unknown_anytype aren't *really* variadic. 3370 if (Proto->getResultType() == Context.UnknownAnyTy && 3371 FDecl && FDecl->isExternC()) { 3372 for (unsigned i = ArgIx; i != NumArgs; ++i) { 3373 ExprResult arg; 3374 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens())) 3375 arg = DefaultFunctionArrayLvalueConversion(Args[i]); 3376 else 3377 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl); 3378 Invalid |= arg.isInvalid(); 3379 AllArgs.push_back(arg.take()); 3380 } 3381 3382 // Otherwise do argument promotion, (C99 6.5.2.2p7). 3383 } else { 3384 for (unsigned i = ArgIx; i != NumArgs; ++i) { 3385 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 3386 FDecl); 3387 Invalid |= Arg.isInvalid(); 3388 AllArgs.push_back(Arg.take()); 3389 } 3390 } 3391 } 3392 return Invalid; 3393} 3394 3395/// Given a function expression of unknown-any type, try to rebuild it 3396/// to have a function type. 3397static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 3398 3399/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 3400/// This provides the location of the left/right parens and a list of comma 3401/// locations. 3402ExprResult 3403Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 3404 MultiExprArg args, SourceLocation RParenLoc, 3405 Expr *ExecConfig) { 3406 unsigned NumArgs = args.size(); 3407 3408 // Since this might be a postfix expression, get rid of ParenListExprs. 3409 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 3410 if (Result.isInvalid()) return ExprError(); 3411 Fn = Result.take(); 3412 3413 Expr **Args = args.release(); 3414 3415 if (getLangOptions().CPlusPlus) { 3416 // If this is a pseudo-destructor expression, build the call immediately. 3417 if (isa<CXXPseudoDestructorExpr>(Fn)) { 3418 if (NumArgs > 0) { 3419 // Pseudo-destructor calls should not have any arguments. 3420 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 3421 << FixItHint::CreateRemoval( 3422 SourceRange(Args[0]->getLocStart(), 3423 Args[NumArgs-1]->getLocEnd())); 3424 3425 NumArgs = 0; 3426 } 3427 3428 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy, 3429 VK_RValue, RParenLoc)); 3430 } 3431 3432 // Determine whether this is a dependent call inside a C++ template, 3433 // in which case we won't do any semantic analysis now. 3434 // FIXME: Will need to cache the results of name lookup (including ADL) in 3435 // Fn. 3436 bool Dependent = false; 3437 if (Fn->isTypeDependent()) 3438 Dependent = true; 3439 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs)) 3440 Dependent = true; 3441 3442 if (Dependent) { 3443 if (ExecConfig) { 3444 return Owned(new (Context) CUDAKernelCallExpr( 3445 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs, 3446 Context.DependentTy, VK_RValue, RParenLoc)); 3447 } else { 3448 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs, 3449 Context.DependentTy, VK_RValue, 3450 RParenLoc)); 3451 } 3452 } 3453 3454 // Determine whether this is a call to an object (C++ [over.call.object]). 3455 if (Fn->getType()->isRecordType()) 3456 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs, 3457 RParenLoc)); 3458 3459 if (Fn->getType() == Context.UnknownAnyTy) { 3460 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 3461 if (result.isInvalid()) return ExprError(); 3462 Fn = result.take(); 3463 } 3464 3465 if (Fn->getType() == Context.BoundMemberTy) { 3466 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs, 3467 RParenLoc); 3468 } 3469 } 3470 3471 // Check for overloaded calls. This can happen even in C due to extensions. 3472 if (Fn->getType() == Context.OverloadTy) { 3473 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 3474 3475 // We aren't supposed to apply this logic if there's an '&' involved. 3476 if (!find.IsAddressOfOperand) { 3477 OverloadExpr *ovl = find.Expression; 3478 if (isa<UnresolvedLookupExpr>(ovl)) { 3479 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 3480 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs, 3481 RParenLoc, ExecConfig); 3482 } else { 3483 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs, 3484 RParenLoc); 3485 } 3486 } 3487 } 3488 3489 // If we're directly calling a function, get the appropriate declaration. 3490 3491 Expr *NakedFn = Fn->IgnoreParens(); 3492 3493 NamedDecl *NDecl = 0; 3494 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 3495 if (UnOp->getOpcode() == UO_AddrOf) 3496 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 3497 3498 if (isa<DeclRefExpr>(NakedFn)) 3499 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 3500 else if (isa<MemberExpr>(NakedFn)) 3501 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 3502 3503 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc, 3504 ExecConfig); 3505} 3506 3507ExprResult 3508Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 3509 MultiExprArg execConfig, SourceLocation GGGLoc) { 3510 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl(); 3511 if (!ConfigDecl) 3512 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use) 3513 << "cudaConfigureCall"); 3514 QualType ConfigQTy = ConfigDecl->getType(); 3515 3516 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr( 3517 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc); 3518 3519 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0); 3520} 3521 3522/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 3523/// 3524/// __builtin_astype( value, dst type ) 3525/// 3526ExprResult Sema::ActOnAsTypeExpr(Expr *expr, ParsedType destty, 3527 SourceLocation BuiltinLoc, 3528 SourceLocation RParenLoc) { 3529 ExprValueKind VK = VK_RValue; 3530 ExprObjectKind OK = OK_Ordinary; 3531 QualType DstTy = GetTypeFromParser(destty); 3532 QualType SrcTy = expr->getType(); 3533 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 3534 return ExprError(Diag(BuiltinLoc, 3535 diag::err_invalid_astype_of_different_size) 3536 << DstTy 3537 << SrcTy 3538 << expr->getSourceRange()); 3539 return Owned(new (Context) AsTypeExpr(expr, DstTy, VK, OK, BuiltinLoc, 3540 RParenLoc)); 3541} 3542 3543/// BuildResolvedCallExpr - Build a call to a resolved expression, 3544/// i.e. an expression not of \p OverloadTy. The expression should 3545/// unary-convert to an expression of function-pointer or 3546/// block-pointer type. 3547/// 3548/// \param NDecl the declaration being called, if available 3549ExprResult 3550Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 3551 SourceLocation LParenLoc, 3552 Expr **Args, unsigned NumArgs, 3553 SourceLocation RParenLoc, 3554 Expr *Config) { 3555 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 3556 3557 // Promote the function operand. 3558 ExprResult Result = UsualUnaryConversions(Fn); 3559 if (Result.isInvalid()) 3560 return ExprError(); 3561 Fn = Result.take(); 3562 3563 // Make the call expr early, before semantic checks. This guarantees cleanup 3564 // of arguments and function on error. 3565 CallExpr *TheCall; 3566 if (Config) { 3567 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 3568 cast<CallExpr>(Config), 3569 Args, NumArgs, 3570 Context.BoolTy, 3571 VK_RValue, 3572 RParenLoc); 3573 } else { 3574 TheCall = new (Context) CallExpr(Context, Fn, 3575 Args, NumArgs, 3576 Context.BoolTy, 3577 VK_RValue, 3578 RParenLoc); 3579 } 3580 3581 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 3582 3583 // Bail out early if calling a builtin with custom typechecking. 3584 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 3585 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 3586 3587 retry: 3588 const FunctionType *FuncT; 3589 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 3590 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 3591 // have type pointer to function". 3592 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 3593 if (FuncT == 0) 3594 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 3595 << Fn->getType() << Fn->getSourceRange()); 3596 } else if (const BlockPointerType *BPT = 3597 Fn->getType()->getAs<BlockPointerType>()) { 3598 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 3599 } else { 3600 // Handle calls to expressions of unknown-any type. 3601 if (Fn->getType() == Context.UnknownAnyTy) { 3602 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 3603 if (rewrite.isInvalid()) return ExprError(); 3604 Fn = rewrite.take(); 3605 TheCall->setCallee(Fn); 3606 goto retry; 3607 } 3608 3609 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 3610 << Fn->getType() << Fn->getSourceRange()); 3611 } 3612 3613 if (getLangOptions().CUDA) { 3614 if (Config) { 3615 // CUDA: Kernel calls must be to global functions 3616 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 3617 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 3618 << FDecl->getName() << Fn->getSourceRange()); 3619 3620 // CUDA: Kernel function must have 'void' return type 3621 if (!FuncT->getResultType()->isVoidType()) 3622 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 3623 << Fn->getType() << Fn->getSourceRange()); 3624 } 3625 } 3626 3627 // Check for a valid return type 3628 if (CheckCallReturnType(FuncT->getResultType(), 3629 Fn->getSourceRange().getBegin(), TheCall, 3630 FDecl)) 3631 return ExprError(); 3632 3633 // We know the result type of the call, set it. 3634 TheCall->setType(FuncT->getCallResultType(Context)); 3635 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType())); 3636 3637 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) { 3638 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs, 3639 RParenLoc)) 3640 return ExprError(); 3641 } else { 3642 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 3643 3644 if (FDecl) { 3645 // Check if we have too few/too many template arguments, based 3646 // on our knowledge of the function definition. 3647 const FunctionDecl *Def = 0; 3648 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) { 3649 const FunctionProtoType *Proto 3650 = Def->getType()->getAs<FunctionProtoType>(); 3651 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) 3652 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 3653 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange(); 3654 } 3655 3656 // If the function we're calling isn't a function prototype, but we have 3657 // a function prototype from a prior declaratiom, use that prototype. 3658 if (!FDecl->hasPrototype()) 3659 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 3660 } 3661 3662 // Promote the arguments (C99 6.5.2.2p6). 3663 for (unsigned i = 0; i != NumArgs; i++) { 3664 Expr *Arg = Args[i]; 3665 3666 if (Proto && i < Proto->getNumArgs()) { 3667 InitializedEntity Entity 3668 = InitializedEntity::InitializeParameter(Context, 3669 Proto->getArgType(i), 3670 Proto->isArgConsumed(i)); 3671 ExprResult ArgE = PerformCopyInitialization(Entity, 3672 SourceLocation(), 3673 Owned(Arg)); 3674 if (ArgE.isInvalid()) 3675 return true; 3676 3677 Arg = ArgE.takeAs<Expr>(); 3678 3679 } else { 3680 ExprResult ArgE = DefaultArgumentPromotion(Arg); 3681 3682 if (ArgE.isInvalid()) 3683 return true; 3684 3685 Arg = ArgE.takeAs<Expr>(); 3686 } 3687 3688 if (RequireCompleteType(Arg->getSourceRange().getBegin(), 3689 Arg->getType(), 3690 PDiag(diag::err_call_incomplete_argument) 3691 << Arg->getSourceRange())) 3692 return ExprError(); 3693 3694 TheCall->setArg(i, Arg); 3695 } 3696 } 3697 3698 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 3699 if (!Method->isStatic()) 3700 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 3701 << Fn->getSourceRange()); 3702 3703 // Check for sentinels 3704 if (NDecl) 3705 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs); 3706 3707 // Do special checking on direct calls to functions. 3708 if (FDecl) { 3709 if (CheckFunctionCall(FDecl, TheCall)) 3710 return ExprError(); 3711 3712 if (BuiltinID) 3713 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 3714 } else if (NDecl) { 3715 if (CheckBlockCall(NDecl, TheCall)) 3716 return ExprError(); 3717 } 3718 3719 return MaybeBindToTemporary(TheCall); 3720} 3721 3722ExprResult 3723Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 3724 SourceLocation RParenLoc, Expr *InitExpr) { 3725 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type"); 3726 // FIXME: put back this assert when initializers are worked out. 3727 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 3728 3729 TypeSourceInfo *TInfo; 3730 QualType literalType = GetTypeFromParser(Ty, &TInfo); 3731 if (!TInfo) 3732 TInfo = Context.getTrivialTypeSourceInfo(literalType); 3733 3734 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 3735} 3736 3737ExprResult 3738Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 3739 SourceLocation RParenLoc, Expr *literalExpr) { 3740 QualType literalType = TInfo->getType(); 3741 3742 if (literalType->isArrayType()) { 3743 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 3744 PDiag(diag::err_illegal_decl_array_incomplete_type) 3745 << SourceRange(LParenLoc, 3746 literalExpr->getSourceRange().getEnd()))) 3747 return ExprError(); 3748 if (literalType->isVariableArrayType()) 3749 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 3750 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())); 3751 } else if (!literalType->isDependentType() && 3752 RequireCompleteType(LParenLoc, literalType, 3753 PDiag(diag::err_typecheck_decl_incomplete_type) 3754 << SourceRange(LParenLoc, 3755 literalExpr->getSourceRange().getEnd()))) 3756 return ExprError(); 3757 3758 InitializedEntity Entity 3759 = InitializedEntity::InitializeTemporary(literalType); 3760 InitializationKind Kind 3761 = InitializationKind::CreateCStyleCast(LParenLoc, 3762 SourceRange(LParenLoc, RParenLoc)); 3763 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1); 3764 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 3765 MultiExprArg(*this, &literalExpr, 1), 3766 &literalType); 3767 if (Result.isInvalid()) 3768 return ExprError(); 3769 literalExpr = Result.get(); 3770 3771 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 3772 if (isFileScope) { // 6.5.2.5p3 3773 if (CheckForConstantInitializer(literalExpr, literalType)) 3774 return ExprError(); 3775 } 3776 3777 // In C, compound literals are l-values for some reason. 3778 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue; 3779 3780 return MaybeBindToTemporary( 3781 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 3782 VK, literalExpr, isFileScope)); 3783} 3784 3785ExprResult 3786Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist, 3787 SourceLocation RBraceLoc) { 3788 unsigned NumInit = initlist.size(); 3789 Expr **InitList = initlist.release(); 3790 3791 // Semantic analysis for initializers is done by ActOnDeclarator() and 3792 // CheckInitializer() - it requires knowledge of the object being intialized. 3793 3794 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList, 3795 NumInit, RBraceLoc); 3796 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 3797 return Owned(E); 3798} 3799 3800/// Prepares for a scalar cast, performing all the necessary stages 3801/// except the final cast and returning the kind required. 3802static CastKind PrepareScalarCast(Sema &S, ExprResult &Src, QualType DestTy) { 3803 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 3804 // Also, callers should have filtered out the invalid cases with 3805 // pointers. Everything else should be possible. 3806 3807 QualType SrcTy = Src.get()->getType(); 3808 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy)) 3809 return CK_NoOp; 3810 3811 switch (SrcTy->getScalarTypeKind()) { 3812 case Type::STK_MemberPointer: 3813 llvm_unreachable("member pointer type in C"); 3814 3815 case Type::STK_Pointer: 3816 switch (DestTy->getScalarTypeKind()) { 3817 case Type::STK_Pointer: 3818 return DestTy->isObjCObjectPointerType() ? 3819 CK_AnyPointerToObjCPointerCast : 3820 CK_BitCast; 3821 case Type::STK_Bool: 3822 return CK_PointerToBoolean; 3823 case Type::STK_Integral: 3824 return CK_PointerToIntegral; 3825 case Type::STK_Floating: 3826 case Type::STK_FloatingComplex: 3827 case Type::STK_IntegralComplex: 3828 case Type::STK_MemberPointer: 3829 llvm_unreachable("illegal cast from pointer"); 3830 } 3831 break; 3832 3833 case Type::STK_Bool: // casting from bool is like casting from an integer 3834 case Type::STK_Integral: 3835 switch (DestTy->getScalarTypeKind()) { 3836 case Type::STK_Pointer: 3837 if (Src.get()->isNullPointerConstant(S.Context, 3838 Expr::NPC_ValueDependentIsNull)) 3839 return CK_NullToPointer; 3840 return CK_IntegralToPointer; 3841 case Type::STK_Bool: 3842 return CK_IntegralToBoolean; 3843 case Type::STK_Integral: 3844 return CK_IntegralCast; 3845 case Type::STK_Floating: 3846 return CK_IntegralToFloating; 3847 case Type::STK_IntegralComplex: 3848 Src = S.ImpCastExprToType(Src.take(), 3849 DestTy->getAs<ComplexType>()->getElementType(), 3850 CK_IntegralCast); 3851 return CK_IntegralRealToComplex; 3852 case Type::STK_FloatingComplex: 3853 Src = S.ImpCastExprToType(Src.take(), 3854 DestTy->getAs<ComplexType>()->getElementType(), 3855 CK_IntegralToFloating); 3856 return CK_FloatingRealToComplex; 3857 case Type::STK_MemberPointer: 3858 llvm_unreachable("member pointer type in C"); 3859 } 3860 break; 3861 3862 case Type::STK_Floating: 3863 switch (DestTy->getScalarTypeKind()) { 3864 case Type::STK_Floating: 3865 return CK_FloatingCast; 3866 case Type::STK_Bool: 3867 return CK_FloatingToBoolean; 3868 case Type::STK_Integral: 3869 return CK_FloatingToIntegral; 3870 case Type::STK_FloatingComplex: 3871 Src = S.ImpCastExprToType(Src.take(), 3872 DestTy->getAs<ComplexType>()->getElementType(), 3873 CK_FloatingCast); 3874 return CK_FloatingRealToComplex; 3875 case Type::STK_IntegralComplex: 3876 Src = S.ImpCastExprToType(Src.take(), 3877 DestTy->getAs<ComplexType>()->getElementType(), 3878 CK_FloatingToIntegral); 3879 return CK_IntegralRealToComplex; 3880 case Type::STK_Pointer: 3881 llvm_unreachable("valid float->pointer cast?"); 3882 case Type::STK_MemberPointer: 3883 llvm_unreachable("member pointer type in C"); 3884 } 3885 break; 3886 3887 case Type::STK_FloatingComplex: 3888 switch (DestTy->getScalarTypeKind()) { 3889 case Type::STK_FloatingComplex: 3890 return CK_FloatingComplexCast; 3891 case Type::STK_IntegralComplex: 3892 return CK_FloatingComplexToIntegralComplex; 3893 case Type::STK_Floating: { 3894 QualType ET = SrcTy->getAs<ComplexType>()->getElementType(); 3895 if (S.Context.hasSameType(ET, DestTy)) 3896 return CK_FloatingComplexToReal; 3897 Src = S.ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal); 3898 return CK_FloatingCast; 3899 } 3900 case Type::STK_Bool: 3901 return CK_FloatingComplexToBoolean; 3902 case Type::STK_Integral: 3903 Src = S.ImpCastExprToType(Src.take(), 3904 SrcTy->getAs<ComplexType>()->getElementType(), 3905 CK_FloatingComplexToReal); 3906 return CK_FloatingToIntegral; 3907 case Type::STK_Pointer: 3908 llvm_unreachable("valid complex float->pointer cast?"); 3909 case Type::STK_MemberPointer: 3910 llvm_unreachable("member pointer type in C"); 3911 } 3912 break; 3913 3914 case Type::STK_IntegralComplex: 3915 switch (DestTy->getScalarTypeKind()) { 3916 case Type::STK_FloatingComplex: 3917 return CK_IntegralComplexToFloatingComplex; 3918 case Type::STK_IntegralComplex: 3919 return CK_IntegralComplexCast; 3920 case Type::STK_Integral: { 3921 QualType ET = SrcTy->getAs<ComplexType>()->getElementType(); 3922 if (S.Context.hasSameType(ET, DestTy)) 3923 return CK_IntegralComplexToReal; 3924 Src = S.ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal); 3925 return CK_IntegralCast; 3926 } 3927 case Type::STK_Bool: 3928 return CK_IntegralComplexToBoolean; 3929 case Type::STK_Floating: 3930 Src = S.ImpCastExprToType(Src.take(), 3931 SrcTy->getAs<ComplexType>()->getElementType(), 3932 CK_IntegralComplexToReal); 3933 return CK_IntegralToFloating; 3934 case Type::STK_Pointer: 3935 llvm_unreachable("valid complex int->pointer cast?"); 3936 case Type::STK_MemberPointer: 3937 llvm_unreachable("member pointer type in C"); 3938 } 3939 break; 3940 } 3941 3942 llvm_unreachable("Unhandled scalar cast"); 3943 return CK_BitCast; 3944} 3945 3946/// CheckCastTypes - Check type constraints for casting between types. 3947ExprResult Sema::CheckCastTypes(SourceLocation CastStartLoc, SourceRange TyR, 3948 QualType castType, Expr *castExpr, 3949 CastKind& Kind, ExprValueKind &VK, 3950 CXXCastPath &BasePath, bool FunctionalStyle) { 3951 if (castExpr->getType() == Context.UnknownAnyTy) 3952 return checkUnknownAnyCast(TyR, castType, castExpr, Kind, VK, BasePath); 3953 3954 if (getLangOptions().CPlusPlus) 3955 return CXXCheckCStyleCast(SourceRange(CastStartLoc, 3956 castExpr->getLocEnd()), 3957 castType, VK, castExpr, Kind, BasePath, 3958 FunctionalStyle); 3959 3960 assert(!castExpr->getType()->isPlaceholderType()); 3961 3962 // We only support r-value casts in C. 3963 VK = VK_RValue; 3964 3965 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression 3966 // type needs to be scalar. 3967 if (castType->isVoidType()) { 3968 // We don't necessarily do lvalue-to-rvalue conversions on this. 3969 ExprResult castExprRes = IgnoredValueConversions(castExpr); 3970 if (castExprRes.isInvalid()) 3971 return ExprError(); 3972 castExpr = castExprRes.take(); 3973 3974 // Cast to void allows any expr type. 3975 Kind = CK_ToVoid; 3976 return Owned(castExpr); 3977 } 3978 3979 ExprResult castExprRes = DefaultFunctionArrayLvalueConversion(castExpr); 3980 if (castExprRes.isInvalid()) 3981 return ExprError(); 3982 castExpr = castExprRes.take(); 3983 3984 if (RequireCompleteType(TyR.getBegin(), castType, 3985 diag::err_typecheck_cast_to_incomplete)) 3986 return ExprError(); 3987 3988 if (!castType->isScalarType() && !castType->isVectorType()) { 3989 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) && 3990 (castType->isStructureType() || castType->isUnionType())) { 3991 // GCC struct/union extension: allow cast to self. 3992 // FIXME: Check that the cast destination type is complete. 3993 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar) 3994 << castType << castExpr->getSourceRange(); 3995 Kind = CK_NoOp; 3996 return Owned(castExpr); 3997 } 3998 3999 if (castType->isUnionType()) { 4000 // GCC cast to union extension 4001 RecordDecl *RD = castType->getAs<RecordType>()->getDecl(); 4002 RecordDecl::field_iterator Field, FieldEnd; 4003 for (Field = RD->field_begin(), FieldEnd = RD->field_end(); 4004 Field != FieldEnd; ++Field) { 4005 if (Context.hasSameUnqualifiedType(Field->getType(), 4006 castExpr->getType()) && 4007 !Field->isUnnamedBitfield()) { 4008 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union) 4009 << castExpr->getSourceRange(); 4010 break; 4011 } 4012 } 4013 if (Field == FieldEnd) { 4014 Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type) 4015 << castExpr->getType() << castExpr->getSourceRange(); 4016 return ExprError(); 4017 } 4018 Kind = CK_ToUnion; 4019 return Owned(castExpr); 4020 } 4021 4022 // Reject any other conversions to non-scalar types. 4023 Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar) 4024 << castType << castExpr->getSourceRange(); 4025 return ExprError(); 4026 } 4027 4028 // The type we're casting to is known to be a scalar or vector. 4029 4030 // Require the operand to be a scalar or vector. 4031 if (!castExpr->getType()->isScalarType() && 4032 !castExpr->getType()->isVectorType()) { 4033 Diag(castExpr->getLocStart(), 4034 diag::err_typecheck_expect_scalar_operand) 4035 << castExpr->getType() << castExpr->getSourceRange(); 4036 return ExprError(); 4037 } 4038 4039 if (castType->isExtVectorType()) 4040 return CheckExtVectorCast(TyR, castType, castExpr, Kind); 4041 4042 if (castType->isVectorType()) { 4043 if (castType->getAs<VectorType>()->getVectorKind() == 4044 VectorType::AltiVecVector && 4045 (castExpr->getType()->isIntegerType() || 4046 castExpr->getType()->isFloatingType())) { 4047 Kind = CK_VectorSplat; 4048 return Owned(castExpr); 4049 } else if (CheckVectorCast(TyR, castType, castExpr->getType(), Kind)) { 4050 return ExprError(); 4051 } else 4052 return Owned(castExpr); 4053 } 4054 if (castExpr->getType()->isVectorType()) { 4055 if (CheckVectorCast(TyR, castExpr->getType(), castType, Kind)) 4056 return ExprError(); 4057 else 4058 return Owned(castExpr); 4059 } 4060 4061 // The source and target types are both scalars, i.e. 4062 // - arithmetic types (fundamental, enum, and complex) 4063 // - all kinds of pointers 4064 // Note that member pointers were filtered out with C++, above. 4065 4066 if (isa<ObjCSelectorExpr>(castExpr)) { 4067 Diag(castExpr->getLocStart(), diag::err_cast_selector_expr); 4068 return ExprError(); 4069 } 4070 4071 // If either type is a pointer, the other type has to be either an 4072 // integer or a pointer. 4073 QualType castExprType = castExpr->getType(); 4074 if (!castType->isArithmeticType()) { 4075 if (!castExprType->isIntegralType(Context) && 4076 castExprType->isArithmeticType()) { 4077 Diag(castExpr->getLocStart(), 4078 diag::err_cast_pointer_from_non_pointer_int) 4079 << castExprType << castExpr->getSourceRange(); 4080 return ExprError(); 4081 } 4082 } else if (!castExpr->getType()->isArithmeticType()) { 4083 if (!castType->isIntegralType(Context) && castType->isArithmeticType()) { 4084 Diag(castExpr->getLocStart(), diag::err_cast_pointer_to_non_pointer_int) 4085 << castType << castExpr->getSourceRange(); 4086 return ExprError(); 4087 } 4088 } 4089 4090 if (getLangOptions().ObjCAutoRefCount) { 4091 // Diagnose problems with Objective-C casts involving lifetime qualifiers. 4092 CheckObjCARCConversion(SourceRange(CastStartLoc, castExpr->getLocEnd()), 4093 castType, castExpr, CCK_CStyleCast); 4094 4095 if (const PointerType *CastPtr = castType->getAs<PointerType>()) { 4096 if (const PointerType *ExprPtr = castExprType->getAs<PointerType>()) { 4097 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers(); 4098 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers(); 4099 if (CastPtr->getPointeeType()->isObjCLifetimeType() && 4100 ExprPtr->getPointeeType()->isObjCLifetimeType() && 4101 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) { 4102 Diag(castExpr->getLocStart(), 4103 diag::err_typecheck_incompatible_ownership) 4104 << castExprType << castType << AA_Casting 4105 << castExpr->getSourceRange(); 4106 4107 return ExprError(); 4108 } 4109 } 4110 } 4111 else if (!CheckObjCARCUnavailableWeakConversion(castType, castExprType)) { 4112 Diag(castExpr->getLocStart(), 4113 diag::err_arc_convesion_of_weak_unavailable) << 1 4114 << castExprType << castType 4115 << castExpr->getSourceRange(); 4116 return ExprError(); 4117 } 4118 } 4119 4120 castExprRes = Owned(castExpr); 4121 Kind = PrepareScalarCast(*this, castExprRes, castType); 4122 if (castExprRes.isInvalid()) 4123 return ExprError(); 4124 castExpr = castExprRes.take(); 4125 4126 if (Kind == CK_BitCast) 4127 CheckCastAlign(castExpr, castType, TyR); 4128 4129 return Owned(castExpr); 4130} 4131 4132bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 4133 CastKind &Kind) { 4134 assert(VectorTy->isVectorType() && "Not a vector type!"); 4135 4136 if (Ty->isVectorType() || Ty->isIntegerType()) { 4137 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 4138 return Diag(R.getBegin(), 4139 Ty->isVectorType() ? 4140 diag::err_invalid_conversion_between_vectors : 4141 diag::err_invalid_conversion_between_vector_and_integer) 4142 << VectorTy << Ty << R; 4143 } else 4144 return Diag(R.getBegin(), 4145 diag::err_invalid_conversion_between_vector_and_scalar) 4146 << VectorTy << Ty << R; 4147 4148 Kind = CK_BitCast; 4149 return false; 4150} 4151 4152ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 4153 Expr *CastExpr, CastKind &Kind) { 4154 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 4155 4156 QualType SrcTy = CastExpr->getType(); 4157 4158 // If SrcTy is a VectorType, the total size must match to explicitly cast to 4159 // an ExtVectorType. 4160 if (SrcTy->isVectorType()) { 4161 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) { 4162 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 4163 << DestTy << SrcTy << R; 4164 return ExprError(); 4165 } 4166 Kind = CK_BitCast; 4167 return Owned(CastExpr); 4168 } 4169 4170 // All non-pointer scalars can be cast to ExtVector type. The appropriate 4171 // conversion will take place first from scalar to elt type, and then 4172 // splat from elt type to vector. 4173 if (SrcTy->isPointerType()) 4174 return Diag(R.getBegin(), 4175 diag::err_invalid_conversion_between_vector_and_scalar) 4176 << DestTy << SrcTy << R; 4177 4178 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 4179 ExprResult CastExprRes = Owned(CastExpr); 4180 CastKind CK = PrepareScalarCast(*this, CastExprRes, DestElemTy); 4181 if (CastExprRes.isInvalid()) 4182 return ExprError(); 4183 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take(); 4184 4185 Kind = CK_VectorSplat; 4186 return Owned(CastExpr); 4187} 4188 4189ExprResult 4190Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 4191 Declarator &D, ParsedType &Ty, 4192 SourceLocation RParenLoc, Expr *castExpr) { 4193 assert(!D.isInvalidType() && (castExpr != 0) && 4194 "ActOnCastExpr(): missing type or expr"); 4195 4196 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, castExpr->getType()); 4197 if (D.isInvalidType()) 4198 return ExprError(); 4199 4200 if (getLangOptions().CPlusPlus) { 4201 // Check that there are no default arguments (C++ only). 4202 CheckExtraCXXDefaultArguments(D); 4203 } 4204 4205 QualType castType = castTInfo->getType(); 4206 Ty = CreateParsedType(castType, castTInfo); 4207 4208 bool isVectorLiteral = false; 4209 4210 // Check for an altivec or OpenCL literal, 4211 // i.e. all the elements are integer constants. 4212 ParenExpr *PE = dyn_cast<ParenExpr>(castExpr); 4213 ParenListExpr *PLE = dyn_cast<ParenListExpr>(castExpr); 4214 if (getLangOptions().AltiVec && castType->isVectorType() && (PE || PLE)) { 4215 if (PLE && PLE->getNumExprs() == 0) { 4216 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 4217 return ExprError(); 4218 } 4219 if (PE || PLE->getNumExprs() == 1) { 4220 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 4221 if (!E->getType()->isVectorType()) 4222 isVectorLiteral = true; 4223 } 4224 else 4225 isVectorLiteral = true; 4226 } 4227 4228 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 4229 // then handle it as such. 4230 if (isVectorLiteral) 4231 return BuildVectorLiteral(LParenLoc, RParenLoc, castExpr, castTInfo); 4232 4233 // If the Expr being casted is a ParenListExpr, handle it specially. 4234 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 4235 // sequence of BinOp comma operators. 4236 if (isa<ParenListExpr>(castExpr)) { 4237 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, castExpr); 4238 if (Result.isInvalid()) return ExprError(); 4239 castExpr = Result.take(); 4240 } 4241 4242 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr); 4243} 4244 4245ExprResult 4246Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, 4247 SourceLocation RParenLoc, Expr *castExpr) { 4248 CastKind Kind = CK_Invalid; 4249 ExprValueKind VK = VK_RValue; 4250 CXXCastPath BasePath; 4251 ExprResult CastResult = 4252 CheckCastTypes(LParenLoc, SourceRange(LParenLoc, RParenLoc), Ty->getType(), 4253 castExpr, Kind, VK, BasePath); 4254 if (CastResult.isInvalid()) 4255 return ExprError(); 4256 castExpr = CastResult.take(); 4257 4258 return Owned(CStyleCastExpr::Create( 4259 Context, Ty->getType().getNonLValueExprType(Context), VK, Kind, castExpr, 4260 &BasePath, Ty, LParenLoc, RParenLoc)); 4261} 4262 4263ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 4264 SourceLocation RParenLoc, Expr *E, 4265 TypeSourceInfo *TInfo) { 4266 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 4267 "Expected paren or paren list expression"); 4268 4269 Expr **exprs; 4270 unsigned numExprs; 4271 Expr *subExpr; 4272 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 4273 exprs = PE->getExprs(); 4274 numExprs = PE->getNumExprs(); 4275 } else { 4276 subExpr = cast<ParenExpr>(E)->getSubExpr(); 4277 exprs = &subExpr; 4278 numExprs = 1; 4279 } 4280 4281 QualType Ty = TInfo->getType(); 4282 assert(Ty->isVectorType() && "Expected vector type"); 4283 4284 SmallVector<Expr *, 8> initExprs; 4285 const VectorType *VTy = Ty->getAs<VectorType>(); 4286 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 4287 4288 // '(...)' form of vector initialization in AltiVec: the number of 4289 // initializers must be one or must match the size of the vector. 4290 // If a single value is specified in the initializer then it will be 4291 // replicated to all the components of the vector 4292 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 4293 // The number of initializers must be one or must match the size of the 4294 // vector. If a single value is specified in the initializer then it will 4295 // be replicated to all the components of the vector 4296 if (numExprs == 1) { 4297 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 4298 ExprResult Literal = Owned(exprs[0]); 4299 Literal = ImpCastExprToType(Literal.take(), ElemTy, 4300 PrepareScalarCast(*this, Literal, ElemTy)); 4301 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 4302 } 4303 else if (numExprs < numElems) { 4304 Diag(E->getExprLoc(), 4305 diag::err_incorrect_number_of_vector_initializers); 4306 return ExprError(); 4307 } 4308 else 4309 for (unsigned i = 0, e = numExprs; i != e; ++i) 4310 initExprs.push_back(exprs[i]); 4311 } 4312 else { 4313 // For OpenCL, when the number of initializers is a single value, 4314 // it will be replicated to all components of the vector. 4315 if (getLangOptions().OpenCL && 4316 VTy->getVectorKind() == VectorType::GenericVector && 4317 numExprs == 1) { 4318 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 4319 ExprResult Literal = Owned(exprs[0]); 4320 Literal = ImpCastExprToType(Literal.take(), ElemTy, 4321 PrepareScalarCast(*this, Literal, ElemTy)); 4322 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 4323 } 4324 4325 for (unsigned i = 0, e = numExprs; i != e; ++i) 4326 initExprs.push_back(exprs[i]); 4327 } 4328 // FIXME: This means that pretty-printing the final AST will produce curly 4329 // braces instead of the original commas. 4330 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc, 4331 &initExprs[0], 4332 initExprs.size(), RParenLoc); 4333 initE->setType(Ty); 4334 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 4335} 4336 4337/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence 4338/// of comma binary operators. 4339ExprResult 4340Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) { 4341 ParenListExpr *E = dyn_cast<ParenListExpr>(expr); 4342 if (!E) 4343 return Owned(expr); 4344 4345 ExprResult Result(E->getExpr(0)); 4346 4347 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 4348 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 4349 E->getExpr(i)); 4350 4351 if (Result.isInvalid()) return ExprError(); 4352 4353 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 4354} 4355 4356ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L, 4357 SourceLocation R, 4358 MultiExprArg Val) { 4359 unsigned nexprs = Val.size(); 4360 Expr **exprs = reinterpret_cast<Expr**>(Val.release()); 4361 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list"); 4362 Expr *expr; 4363 if (nexprs == 1) 4364 expr = new (Context) ParenExpr(L, R, exprs[0]); 4365 else 4366 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R, 4367 exprs[nexprs-1]->getType()); 4368 return Owned(expr); 4369} 4370 4371/// \brief Emit a specialized diagnostic when one expression is a null pointer 4372/// constant and the other is not a pointer. Returns true if a diagnostic is 4373/// emitted. 4374bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 4375 SourceLocation QuestionLoc) { 4376 Expr *NullExpr = LHSExpr; 4377 Expr *NonPointerExpr = RHSExpr; 4378 Expr::NullPointerConstantKind NullKind = 4379 NullExpr->isNullPointerConstant(Context, 4380 Expr::NPC_ValueDependentIsNotNull); 4381 4382 if (NullKind == Expr::NPCK_NotNull) { 4383 NullExpr = RHSExpr; 4384 NonPointerExpr = LHSExpr; 4385 NullKind = 4386 NullExpr->isNullPointerConstant(Context, 4387 Expr::NPC_ValueDependentIsNotNull); 4388 } 4389 4390 if (NullKind == Expr::NPCK_NotNull) 4391 return false; 4392 4393 if (NullKind == Expr::NPCK_ZeroInteger) { 4394 // In this case, check to make sure that we got here from a "NULL" 4395 // string in the source code. 4396 NullExpr = NullExpr->IgnoreParenImpCasts(); 4397 SourceLocation loc = NullExpr->getExprLoc(); 4398 if (!findMacroSpelling(loc, "NULL")) 4399 return false; 4400 } 4401 4402 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr); 4403 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 4404 << NonPointerExpr->getType() << DiagType 4405 << NonPointerExpr->getSourceRange(); 4406 return true; 4407} 4408 4409/// \brief Return false if the condition expression is valid, true otherwise. 4410static bool checkCondition(Sema &S, Expr *Cond) { 4411 QualType CondTy = Cond->getType(); 4412 4413 // C99 6.5.15p2 4414 if (CondTy->isScalarType()) return false; 4415 4416 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar. 4417 if (S.getLangOptions().OpenCL && CondTy->isVectorType()) 4418 return false; 4419 4420 // Emit the proper error message. 4421 S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ? 4422 diag::err_typecheck_cond_expect_scalar : 4423 diag::err_typecheck_cond_expect_scalar_or_vector) 4424 << CondTy; 4425 return true; 4426} 4427 4428/// \brief Return false if the two expressions can be converted to a vector, 4429/// true otherwise 4430static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS, 4431 ExprResult &RHS, 4432 QualType CondTy) { 4433 // Both operands should be of scalar type. 4434 if (!LHS.get()->getType()->isScalarType()) { 4435 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 4436 << CondTy; 4437 return true; 4438 } 4439 if (!RHS.get()->getType()->isScalarType()) { 4440 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 4441 << CondTy; 4442 return true; 4443 } 4444 4445 // Implicity convert these scalars to the type of the condition. 4446 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast); 4447 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast); 4448 return false; 4449} 4450 4451/// \brief Handle when one or both operands are void type. 4452static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 4453 ExprResult &RHS) { 4454 Expr *LHSExpr = LHS.get(); 4455 Expr *RHSExpr = RHS.get(); 4456 4457 if (!LHSExpr->getType()->isVoidType()) 4458 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 4459 << RHSExpr->getSourceRange(); 4460 if (!RHSExpr->getType()->isVoidType()) 4461 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 4462 << LHSExpr->getSourceRange(); 4463 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid); 4464 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid); 4465 return S.Context.VoidTy; 4466} 4467 4468/// \brief Return false if the NullExpr can be promoted to PointerTy, 4469/// true otherwise. 4470static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 4471 QualType PointerTy) { 4472 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 4473 !NullExpr.get()->isNullPointerConstant(S.Context, 4474 Expr::NPC_ValueDependentIsNull)) 4475 return true; 4476 4477 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer); 4478 return false; 4479} 4480 4481/// \brief Checks compatibility between two pointers and return the resulting 4482/// type. 4483static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 4484 ExprResult &RHS, 4485 SourceLocation Loc) { 4486 QualType LHSTy = LHS.get()->getType(); 4487 QualType RHSTy = RHS.get()->getType(); 4488 4489 if (S.Context.hasSameType(LHSTy, RHSTy)) { 4490 // Two identical pointers types are always compatible. 4491 return LHSTy; 4492 } 4493 4494 QualType lhptee, rhptee; 4495 4496 // Get the pointee types. 4497 if (LHSTy->isBlockPointerType()) { 4498 lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType(); 4499 rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType(); 4500 } else { 4501 lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 4502 rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 4503 } 4504 4505 if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(), 4506 rhptee.getUnqualifiedType())) { 4507 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers) 4508 << LHSTy << RHSTy << LHS.get()->getSourceRange() 4509 << RHS.get()->getSourceRange(); 4510 // In this situation, we assume void* type. No especially good 4511 // reason, but this is what gcc does, and we do have to pick 4512 // to get a consistent AST. 4513 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 4514 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 4515 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 4516 return incompatTy; 4517 } 4518 4519 // The pointer types are compatible. 4520 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to 4521 // differently qualified versions of compatible types, the result type is 4522 // a pointer to an appropriately qualified version of the *composite* 4523 // type. 4524 // FIXME: Need to calculate the composite type. 4525 // FIXME: Need to add qualifiers 4526 4527 LHS = S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast); 4528 RHS = S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast); 4529 return LHSTy; 4530} 4531 4532/// \brief Return the resulting type when the operands are both block pointers. 4533static QualType checkConditionalBlockPointerCompatibility(Sema &S, 4534 ExprResult &LHS, 4535 ExprResult &RHS, 4536 SourceLocation Loc) { 4537 QualType LHSTy = LHS.get()->getType(); 4538 QualType RHSTy = RHS.get()->getType(); 4539 4540 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 4541 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 4542 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 4543 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 4544 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 4545 return destType; 4546 } 4547 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 4548 << LHSTy << RHSTy << LHS.get()->getSourceRange() 4549 << RHS.get()->getSourceRange(); 4550 return QualType(); 4551 } 4552 4553 // We have 2 block pointer types. 4554 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 4555} 4556 4557/// \brief Return the resulting type when the operands are both pointers. 4558static QualType 4559checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 4560 ExprResult &RHS, 4561 SourceLocation Loc) { 4562 // get the pointer types 4563 QualType LHSTy = LHS.get()->getType(); 4564 QualType RHSTy = RHS.get()->getType(); 4565 4566 // get the "pointed to" types 4567 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 4568 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 4569 4570 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 4571 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 4572 // Figure out necessary qualifiers (C99 6.5.15p6) 4573 QualType destPointee 4574 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 4575 QualType destType = S.Context.getPointerType(destPointee); 4576 // Add qualifiers if necessary. 4577 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp); 4578 // Promote to void*. 4579 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 4580 return destType; 4581 } 4582 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 4583 QualType destPointee 4584 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 4585 QualType destType = S.Context.getPointerType(destPointee); 4586 // Add qualifiers if necessary. 4587 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp); 4588 // Promote to void*. 4589 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 4590 return destType; 4591 } 4592 4593 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 4594} 4595 4596/// \brief Return false if the first expression is not an integer and the second 4597/// expression is not a pointer, true otherwise. 4598static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 4599 Expr* PointerExpr, SourceLocation Loc, 4600 bool isIntFirstExpr) { 4601 if (!PointerExpr->getType()->isPointerType() || 4602 !Int.get()->getType()->isIntegerType()) 4603 return false; 4604 4605 Expr *Expr1 = isIntFirstExpr ? Int.get() : PointerExpr; 4606 Expr *Expr2 = isIntFirstExpr ? PointerExpr : Int.get(); 4607 4608 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch) 4609 << Expr1->getType() << Expr2->getType() 4610 << Expr1->getSourceRange() << Expr2->getSourceRange(); 4611 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(), 4612 CK_IntegralToPointer); 4613 return true; 4614} 4615 4616/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 4617/// In that case, LHS = cond. 4618/// C99 6.5.15 4619QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 4620 ExprResult &RHS, ExprValueKind &VK, 4621 ExprObjectKind &OK, 4622 SourceLocation QuestionLoc) { 4623 4624 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 4625 if (!LHSResult.isUsable()) return QualType(); 4626 LHS = move(LHSResult); 4627 4628 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 4629 if (!RHSResult.isUsable()) return QualType(); 4630 RHS = move(RHSResult); 4631 4632 // C++ is sufficiently different to merit its own checker. 4633 if (getLangOptions().CPlusPlus) 4634 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 4635 4636 VK = VK_RValue; 4637 OK = OK_Ordinary; 4638 4639 Cond = UsualUnaryConversions(Cond.take()); 4640 if (Cond.isInvalid()) 4641 return QualType(); 4642 LHS = UsualUnaryConversions(LHS.take()); 4643 if (LHS.isInvalid()) 4644 return QualType(); 4645 RHS = UsualUnaryConversions(RHS.take()); 4646 if (RHS.isInvalid()) 4647 return QualType(); 4648 4649 QualType CondTy = Cond.get()->getType(); 4650 QualType LHSTy = LHS.get()->getType(); 4651 QualType RHSTy = RHS.get()->getType(); 4652 4653 // first, check the condition. 4654 if (checkCondition(*this, Cond.get())) 4655 return QualType(); 4656 4657 // Now check the two expressions. 4658 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 4659 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false); 4660 4661 // OpenCL: If the condition is a vector, and both operands are scalar, 4662 // attempt to implicity convert them to the vector type to act like the 4663 // built in select. 4664 if (getLangOptions().OpenCL && CondTy->isVectorType()) 4665 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy)) 4666 return QualType(); 4667 4668 // If both operands have arithmetic type, do the usual arithmetic conversions 4669 // to find a common type: C99 6.5.15p3,5. 4670 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 4671 UsualArithmeticConversions(LHS, RHS); 4672 if (LHS.isInvalid() || RHS.isInvalid()) 4673 return QualType(); 4674 return LHS.get()->getType(); 4675 } 4676 4677 // If both operands are the same structure or union type, the result is that 4678 // type. 4679 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 4680 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 4681 if (LHSRT->getDecl() == RHSRT->getDecl()) 4682 // "If both the operands have structure or union type, the result has 4683 // that type." This implies that CV qualifiers are dropped. 4684 return LHSTy.getUnqualifiedType(); 4685 // FIXME: Type of conditional expression must be complete in C mode. 4686 } 4687 4688 // C99 6.5.15p5: "If both operands have void type, the result has void type." 4689 // The following || allows only one side to be void (a GCC-ism). 4690 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 4691 return checkConditionalVoidType(*this, LHS, RHS); 4692 } 4693 4694 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 4695 // the type of the other operand." 4696 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 4697 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 4698 4699 // All objective-c pointer type analysis is done here. 4700 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 4701 QuestionLoc); 4702 if (LHS.isInvalid() || RHS.isInvalid()) 4703 return QualType(); 4704 if (!compositeType.isNull()) 4705 return compositeType; 4706 4707 4708 // Handle block pointer types. 4709 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 4710 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 4711 QuestionLoc); 4712 4713 // Check constraints for C object pointers types (C99 6.5.15p3,6). 4714 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 4715 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 4716 QuestionLoc); 4717 4718 // GCC compatibility: soften pointer/integer mismatch. Note that 4719 // null pointers have been filtered out by this point. 4720 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 4721 /*isIntFirstExpr=*/true)) 4722 return RHSTy; 4723 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 4724 /*isIntFirstExpr=*/false)) 4725 return LHSTy; 4726 4727 // Emit a better diagnostic if one of the expressions is a null pointer 4728 // constant and the other is not a pointer type. In this case, the user most 4729 // likely forgot to take the address of the other expression. 4730 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 4731 return QualType(); 4732 4733 // Otherwise, the operands are not compatible. 4734 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 4735 << LHSTy << RHSTy << LHS.get()->getSourceRange() 4736 << RHS.get()->getSourceRange(); 4737 return QualType(); 4738} 4739 4740/// FindCompositeObjCPointerType - Helper method to find composite type of 4741/// two objective-c pointer types of the two input expressions. 4742QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 4743 SourceLocation QuestionLoc) { 4744 QualType LHSTy = LHS.get()->getType(); 4745 QualType RHSTy = RHS.get()->getType(); 4746 4747 // Handle things like Class and struct objc_class*. Here we case the result 4748 // to the pseudo-builtin, because that will be implicitly cast back to the 4749 // redefinition type if an attempt is made to access its fields. 4750 if (LHSTy->isObjCClassType() && 4751 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 4752 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast); 4753 return LHSTy; 4754 } 4755 if (RHSTy->isObjCClassType() && 4756 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 4757 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast); 4758 return RHSTy; 4759 } 4760 // And the same for struct objc_object* / id 4761 if (LHSTy->isObjCIdType() && 4762 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 4763 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast); 4764 return LHSTy; 4765 } 4766 if (RHSTy->isObjCIdType() && 4767 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 4768 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast); 4769 return RHSTy; 4770 } 4771 // And the same for struct objc_selector* / SEL 4772 if (Context.isObjCSelType(LHSTy) && 4773 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 4774 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast); 4775 return LHSTy; 4776 } 4777 if (Context.isObjCSelType(RHSTy) && 4778 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 4779 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast); 4780 return RHSTy; 4781 } 4782 // Check constraints for Objective-C object pointers types. 4783 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 4784 4785 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 4786 // Two identical object pointer types are always compatible. 4787 return LHSTy; 4788 } 4789 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>(); 4790 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>(); 4791 QualType compositeType = LHSTy; 4792 4793 // If both operands are interfaces and either operand can be 4794 // assigned to the other, use that type as the composite 4795 // type. This allows 4796 // xxx ? (A*) a : (B*) b 4797 // where B is a subclass of A. 4798 // 4799 // Additionally, as for assignment, if either type is 'id' 4800 // allow silent coercion. Finally, if the types are 4801 // incompatible then make sure to use 'id' as the composite 4802 // type so the result is acceptable for sending messages to. 4803 4804 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 4805 // It could return the composite type. 4806 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 4807 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 4808 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 4809 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 4810 } else if ((LHSTy->isObjCQualifiedIdType() || 4811 RHSTy->isObjCQualifiedIdType()) && 4812 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 4813 // Need to handle "id<xx>" explicitly. 4814 // GCC allows qualified id and any Objective-C type to devolve to 4815 // id. Currently localizing to here until clear this should be 4816 // part of ObjCQualifiedIdTypesAreCompatible. 4817 compositeType = Context.getObjCIdType(); 4818 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 4819 compositeType = Context.getObjCIdType(); 4820 } else if (!(compositeType = 4821 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 4822 ; 4823 else { 4824 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 4825 << LHSTy << RHSTy 4826 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 4827 QualType incompatTy = Context.getObjCIdType(); 4828 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 4829 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 4830 return incompatTy; 4831 } 4832 // The object pointer types are compatible. 4833 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast); 4834 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast); 4835 return compositeType; 4836 } 4837 // Check Objective-C object pointer types and 'void *' 4838 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 4839 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 4840 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 4841 QualType destPointee 4842 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 4843 QualType destType = Context.getPointerType(destPointee); 4844 // Add qualifiers if necessary. 4845 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp); 4846 // Promote to void*. 4847 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast); 4848 return destType; 4849 } 4850 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 4851 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 4852 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 4853 QualType destPointee 4854 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 4855 QualType destType = Context.getPointerType(destPointee); 4856 // Add qualifiers if necessary. 4857 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp); 4858 // Promote to void*. 4859 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast); 4860 return destType; 4861 } 4862 return QualType(); 4863} 4864 4865/// SuggestParentheses - Emit a note with a fixit hint that wraps 4866/// ParenRange in parentheses. 4867static void SuggestParentheses(Sema &Self, SourceLocation Loc, 4868 const PartialDiagnostic &Note, 4869 SourceRange ParenRange) { 4870 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 4871 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 4872 EndLoc.isValid()) { 4873 Self.Diag(Loc, Note) 4874 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 4875 << FixItHint::CreateInsertion(EndLoc, ")"); 4876 } else { 4877 // We can't display the parentheses, so just show the bare note. 4878 Self.Diag(Loc, Note) << ParenRange; 4879 } 4880} 4881 4882static bool IsArithmeticOp(BinaryOperatorKind Opc) { 4883 return Opc >= BO_Mul && Opc <= BO_Shr; 4884} 4885 4886/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 4887/// expression, either using a built-in or overloaded operator, 4888/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 4889/// expression. 4890static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 4891 Expr **RHSExprs) { 4892 E = E->IgnoreParenImpCasts(); 4893 E = E->IgnoreConversionOperator(); 4894 E = E->IgnoreParenImpCasts(); 4895 4896 // Built-in binary operator. 4897 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 4898 if (IsArithmeticOp(OP->getOpcode())) { 4899 *Opcode = OP->getOpcode(); 4900 *RHSExprs = OP->getRHS(); 4901 return true; 4902 } 4903 } 4904 4905 // Overloaded operator. 4906 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 4907 if (Call->getNumArgs() != 2) 4908 return false; 4909 4910 // Make sure this is really a binary operator that is safe to pass into 4911 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 4912 OverloadedOperatorKind OO = Call->getOperator(); 4913 if (OO < OO_Plus || OO > OO_Arrow) 4914 return false; 4915 4916 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 4917 if (IsArithmeticOp(OpKind)) { 4918 *Opcode = OpKind; 4919 *RHSExprs = Call->getArg(1); 4920 return true; 4921 } 4922 } 4923 4924 return false; 4925} 4926 4927static bool IsLogicOp(BinaryOperatorKind Opc) { 4928 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 4929} 4930 4931/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 4932/// or is a logical expression such as (x==y) which has int type, but is 4933/// commonly interpreted as boolean. 4934static bool ExprLooksBoolean(Expr *E) { 4935 E = E->IgnoreParenImpCasts(); 4936 4937 if (E->getType()->isBooleanType()) 4938 return true; 4939 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 4940 return IsLogicOp(OP->getOpcode()); 4941 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 4942 return OP->getOpcode() == UO_LNot; 4943 4944 return false; 4945} 4946 4947/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 4948/// and binary operator are mixed in a way that suggests the programmer assumed 4949/// the conditional operator has higher precedence, for example: 4950/// "int x = a + someBinaryCondition ? 1 : 2". 4951static void DiagnoseConditionalPrecedence(Sema &Self, 4952 SourceLocation OpLoc, 4953 Expr *Condition, 4954 Expr *LHSExpr, 4955 Expr *RHSExpr) { 4956 BinaryOperatorKind CondOpcode; 4957 Expr *CondRHS; 4958 4959 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 4960 return; 4961 if (!ExprLooksBoolean(CondRHS)) 4962 return; 4963 4964 // The condition is an arithmetic binary expression, with a right- 4965 // hand side that looks boolean, so warn. 4966 4967 Self.Diag(OpLoc, diag::warn_precedence_conditional) 4968 << Condition->getSourceRange() 4969 << BinaryOperator::getOpcodeStr(CondOpcode); 4970 4971 SuggestParentheses(Self, OpLoc, 4972 Self.PDiag(diag::note_precedence_conditional_silence) 4973 << BinaryOperator::getOpcodeStr(CondOpcode), 4974 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 4975 4976 SuggestParentheses(Self, OpLoc, 4977 Self.PDiag(diag::note_precedence_conditional_first), 4978 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 4979} 4980 4981/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 4982/// in the case of a the GNU conditional expr extension. 4983ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 4984 SourceLocation ColonLoc, 4985 Expr *CondExpr, Expr *LHSExpr, 4986 Expr *RHSExpr) { 4987 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 4988 // was the condition. 4989 OpaqueValueExpr *opaqueValue = 0; 4990 Expr *commonExpr = 0; 4991 if (LHSExpr == 0) { 4992 commonExpr = CondExpr; 4993 4994 // We usually want to apply unary conversions *before* saving, except 4995 // in the special case of a C++ l-value conditional. 4996 if (!(getLangOptions().CPlusPlus 4997 && !commonExpr->isTypeDependent() 4998 && commonExpr->getValueKind() == RHSExpr->getValueKind() 4999 && commonExpr->isGLValue() 5000 && commonExpr->isOrdinaryOrBitFieldObject() 5001 && RHSExpr->isOrdinaryOrBitFieldObject() 5002 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 5003 ExprResult commonRes = UsualUnaryConversions(commonExpr); 5004 if (commonRes.isInvalid()) 5005 return ExprError(); 5006 commonExpr = commonRes.take(); 5007 } 5008 5009 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 5010 commonExpr->getType(), 5011 commonExpr->getValueKind(), 5012 commonExpr->getObjectKind()); 5013 LHSExpr = CondExpr = opaqueValue; 5014 } 5015 5016 ExprValueKind VK = VK_RValue; 5017 ExprObjectKind OK = OK_Ordinary; 5018 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 5019 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 5020 VK, OK, QuestionLoc); 5021 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 5022 RHS.isInvalid()) 5023 return ExprError(); 5024 5025 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 5026 RHS.get()); 5027 5028 if (!commonExpr) 5029 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc, 5030 LHS.take(), ColonLoc, 5031 RHS.take(), result, VK, OK)); 5032 5033 return Owned(new (Context) 5034 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(), 5035 RHS.take(), QuestionLoc, ColonLoc, result, VK, 5036 OK)); 5037} 5038 5039// checkPointerTypesForAssignment - This is a very tricky routine (despite 5040// being closely modeled after the C99 spec:-). The odd characteristic of this 5041// routine is it effectively iqnores the qualifiers on the top level pointee. 5042// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 5043// FIXME: add a couple examples in this comment. 5044static Sema::AssignConvertType 5045checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 5046 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 5047 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 5048 5049 // get the "pointed to" type (ignoring qualifiers at the top level) 5050 const Type *lhptee, *rhptee; 5051 Qualifiers lhq, rhq; 5052 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split(); 5053 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split(); 5054 5055 Sema::AssignConvertType ConvTy = Sema::Compatible; 5056 5057 // C99 6.5.16.1p1: This following citation is common to constraints 5058 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 5059 // qualifiers of the type *pointed to* by the right; 5060 Qualifiers lq; 5061 5062 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 5063 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 5064 lhq.compatiblyIncludesObjCLifetime(rhq)) { 5065 // Ignore lifetime for further calculation. 5066 lhq.removeObjCLifetime(); 5067 rhq.removeObjCLifetime(); 5068 } 5069 5070 if (!lhq.compatiblyIncludes(rhq)) { 5071 // Treat address-space mismatches as fatal. TODO: address subspaces 5072 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 5073 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5074 5075 // It's okay to add or remove GC or lifetime qualifiers when converting to 5076 // and from void*. 5077 else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime() 5078 .compatiblyIncludes( 5079 rhq.withoutObjCGCAttr().withoutObjCGLifetime()) 5080 && (lhptee->isVoidType() || rhptee->isVoidType())) 5081 ; // keep old 5082 5083 // Treat lifetime mismatches as fatal. 5084 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 5085 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5086 5087 // For GCC compatibility, other qualifier mismatches are treated 5088 // as still compatible in C. 5089 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 5090 } 5091 5092 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 5093 // incomplete type and the other is a pointer to a qualified or unqualified 5094 // version of void... 5095 if (lhptee->isVoidType()) { 5096 if (rhptee->isIncompleteOrObjectType()) 5097 return ConvTy; 5098 5099 // As an extension, we allow cast to/from void* to function pointer. 5100 assert(rhptee->isFunctionType()); 5101 return Sema::FunctionVoidPointer; 5102 } 5103 5104 if (rhptee->isVoidType()) { 5105 if (lhptee->isIncompleteOrObjectType()) 5106 return ConvTy; 5107 5108 // As an extension, we allow cast to/from void* to function pointer. 5109 assert(lhptee->isFunctionType()); 5110 return Sema::FunctionVoidPointer; 5111 } 5112 5113 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 5114 // unqualified versions of compatible types, ... 5115 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 5116 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 5117 // Check if the pointee types are compatible ignoring the sign. 5118 // We explicitly check for char so that we catch "char" vs 5119 // "unsigned char" on systems where "char" is unsigned. 5120 if (lhptee->isCharType()) 5121 ltrans = S.Context.UnsignedCharTy; 5122 else if (lhptee->hasSignedIntegerRepresentation()) 5123 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 5124 5125 if (rhptee->isCharType()) 5126 rtrans = S.Context.UnsignedCharTy; 5127 else if (rhptee->hasSignedIntegerRepresentation()) 5128 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 5129 5130 if (ltrans == rtrans) { 5131 // Types are compatible ignoring the sign. Qualifier incompatibility 5132 // takes priority over sign incompatibility because the sign 5133 // warning can be disabled. 5134 if (ConvTy != Sema::Compatible) 5135 return ConvTy; 5136 5137 return Sema::IncompatiblePointerSign; 5138 } 5139 5140 // If we are a multi-level pointer, it's possible that our issue is simply 5141 // one of qualification - e.g. char ** -> const char ** is not allowed. If 5142 // the eventual target type is the same and the pointers have the same 5143 // level of indirection, this must be the issue. 5144 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 5145 do { 5146 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 5147 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 5148 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 5149 5150 if (lhptee == rhptee) 5151 return Sema::IncompatibleNestedPointerQualifiers; 5152 } 5153 5154 // General pointer incompatibility takes priority over qualifiers. 5155 return Sema::IncompatiblePointer; 5156 } 5157 return ConvTy; 5158} 5159 5160/// checkBlockPointerTypesForAssignment - This routine determines whether two 5161/// block pointer types are compatible or whether a block and normal pointer 5162/// are compatible. It is more restrict than comparing two function pointer 5163// types. 5164static Sema::AssignConvertType 5165checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 5166 QualType RHSType) { 5167 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 5168 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 5169 5170 QualType lhptee, rhptee; 5171 5172 // get the "pointed to" type (ignoring qualifiers at the top level) 5173 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 5174 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 5175 5176 // In C++, the types have to match exactly. 5177 if (S.getLangOptions().CPlusPlus) 5178 return Sema::IncompatibleBlockPointer; 5179 5180 Sema::AssignConvertType ConvTy = Sema::Compatible; 5181 5182 // For blocks we enforce that qualifiers are identical. 5183 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 5184 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 5185 5186 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 5187 return Sema::IncompatibleBlockPointer; 5188 5189 return ConvTy; 5190} 5191 5192/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 5193/// for assignment compatibility. 5194static Sema::AssignConvertType 5195checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 5196 QualType RHSType) { 5197 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 5198 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 5199 5200 if (LHSType->isObjCBuiltinType()) { 5201 // Class is not compatible with ObjC object pointers. 5202 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 5203 !RHSType->isObjCQualifiedClassType()) 5204 return Sema::IncompatiblePointer; 5205 return Sema::Compatible; 5206 } 5207 if (RHSType->isObjCBuiltinType()) { 5208 // Class is not compatible with ObjC object pointers. 5209 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 5210 !LHSType->isObjCQualifiedClassType()) 5211 return Sema::IncompatiblePointer; 5212 return Sema::Compatible; 5213 } 5214 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 5215 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 5216 5217 if (!lhptee.isAtLeastAsQualifiedAs(rhptee)) 5218 return Sema::CompatiblePointerDiscardsQualifiers; 5219 5220 if (S.Context.typesAreCompatible(LHSType, RHSType)) 5221 return Sema::Compatible; 5222 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 5223 return Sema::IncompatibleObjCQualifiedId; 5224 return Sema::IncompatiblePointer; 5225} 5226 5227Sema::AssignConvertType 5228Sema::CheckAssignmentConstraints(SourceLocation Loc, 5229 QualType LHSType, QualType RHSType) { 5230 // Fake up an opaque expression. We don't actually care about what 5231 // cast operations are required, so if CheckAssignmentConstraints 5232 // adds casts to this they'll be wasted, but fortunately that doesn't 5233 // usually happen on valid code. 5234 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 5235 ExprResult RHSPtr = &RHSExpr; 5236 CastKind K = CK_Invalid; 5237 5238 return CheckAssignmentConstraints(LHSType, RHSPtr, K); 5239} 5240 5241/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 5242/// has code to accommodate several GCC extensions when type checking 5243/// pointers. Here are some objectionable examples that GCC considers warnings: 5244/// 5245/// int a, *pint; 5246/// short *pshort; 5247/// struct foo *pfoo; 5248/// 5249/// pint = pshort; // warning: assignment from incompatible pointer type 5250/// a = pint; // warning: assignment makes integer from pointer without a cast 5251/// pint = a; // warning: assignment makes pointer from integer without a cast 5252/// pint = pfoo; // warning: assignment from incompatible pointer type 5253/// 5254/// As a result, the code for dealing with pointers is more complex than the 5255/// C99 spec dictates. 5256/// 5257/// Sets 'Kind' for any result kind except Incompatible. 5258Sema::AssignConvertType 5259Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 5260 CastKind &Kind) { 5261 QualType RHSType = RHS.get()->getType(); 5262 QualType OrigLHSType = LHSType; 5263 5264 // Get canonical types. We're not formatting these types, just comparing 5265 // them. 5266 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 5267 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 5268 5269 // Common case: no conversion required. 5270 if (LHSType == RHSType) { 5271 Kind = CK_NoOp; 5272 return Compatible; 5273 } 5274 5275 // If the left-hand side is a reference type, then we are in a 5276 // (rare!) case where we've allowed the use of references in C, 5277 // e.g., as a parameter type in a built-in function. In this case, 5278 // just make sure that the type referenced is compatible with the 5279 // right-hand side type. The caller is responsible for adjusting 5280 // LHSType so that the resulting expression does not have reference 5281 // type. 5282 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 5283 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 5284 Kind = CK_LValueBitCast; 5285 return Compatible; 5286 } 5287 return Incompatible; 5288 } 5289 5290 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 5291 // to the same ExtVector type. 5292 if (LHSType->isExtVectorType()) { 5293 if (RHSType->isExtVectorType()) 5294 return Incompatible; 5295 if (RHSType->isArithmeticType()) { 5296 // CK_VectorSplat does T -> vector T, so first cast to the 5297 // element type. 5298 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 5299 if (elType != RHSType) { 5300 Kind = PrepareScalarCast(*this, RHS, elType); 5301 RHS = ImpCastExprToType(RHS.take(), elType, Kind); 5302 } 5303 Kind = CK_VectorSplat; 5304 return Compatible; 5305 } 5306 } 5307 5308 // Conversions to or from vector type. 5309 if (LHSType->isVectorType() || RHSType->isVectorType()) { 5310 if (LHSType->isVectorType() && RHSType->isVectorType()) { 5311 // Allow assignments of an AltiVec vector type to an equivalent GCC 5312 // vector type and vice versa 5313 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 5314 Kind = CK_BitCast; 5315 return Compatible; 5316 } 5317 5318 // If we are allowing lax vector conversions, and LHS and RHS are both 5319 // vectors, the total size only needs to be the same. This is a bitcast; 5320 // no bits are changed but the result type is different. 5321 if (getLangOptions().LaxVectorConversions && 5322 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) { 5323 Kind = CK_BitCast; 5324 return IncompatibleVectors; 5325 } 5326 } 5327 return Incompatible; 5328 } 5329 5330 // Arithmetic conversions. 5331 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 5332 !(getLangOptions().CPlusPlus && LHSType->isEnumeralType())) { 5333 Kind = PrepareScalarCast(*this, RHS, LHSType); 5334 return Compatible; 5335 } 5336 5337 // Conversions to normal pointers. 5338 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 5339 // U* -> T* 5340 if (isa<PointerType>(RHSType)) { 5341 Kind = CK_BitCast; 5342 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 5343 } 5344 5345 // int -> T* 5346 if (RHSType->isIntegerType()) { 5347 Kind = CK_IntegralToPointer; // FIXME: null? 5348 return IntToPointer; 5349 } 5350 5351 // C pointers are not compatible with ObjC object pointers, 5352 // with two exceptions: 5353 if (isa<ObjCObjectPointerType>(RHSType)) { 5354 // - conversions to void* 5355 if (LHSPointer->getPointeeType()->isVoidType()) { 5356 Kind = CK_AnyPointerToObjCPointerCast; 5357 return Compatible; 5358 } 5359 5360 // - conversions from 'Class' to the redefinition type 5361 if (RHSType->isObjCClassType() && 5362 Context.hasSameType(LHSType, 5363 Context.getObjCClassRedefinitionType())) { 5364 Kind = CK_BitCast; 5365 return Compatible; 5366 } 5367 5368 Kind = CK_BitCast; 5369 return IncompatiblePointer; 5370 } 5371 5372 // U^ -> void* 5373 if (RHSType->getAs<BlockPointerType>()) { 5374 if (LHSPointer->getPointeeType()->isVoidType()) { 5375 Kind = CK_BitCast; 5376 return Compatible; 5377 } 5378 } 5379 5380 return Incompatible; 5381 } 5382 5383 // Conversions to block pointers. 5384 if (isa<BlockPointerType>(LHSType)) { 5385 // U^ -> T^ 5386 if (RHSType->isBlockPointerType()) { 5387 Kind = CK_AnyPointerToBlockPointerCast; 5388 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 5389 } 5390 5391 // int or null -> T^ 5392 if (RHSType->isIntegerType()) { 5393 Kind = CK_IntegralToPointer; // FIXME: null 5394 return IntToBlockPointer; 5395 } 5396 5397 // id -> T^ 5398 if (getLangOptions().ObjC1 && RHSType->isObjCIdType()) { 5399 Kind = CK_AnyPointerToBlockPointerCast; 5400 return Compatible; 5401 } 5402 5403 // void* -> T^ 5404 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 5405 if (RHSPT->getPointeeType()->isVoidType()) { 5406 Kind = CK_AnyPointerToBlockPointerCast; 5407 return Compatible; 5408 } 5409 5410 return Incompatible; 5411 } 5412 5413 // Conversions to Objective-C pointers. 5414 if (isa<ObjCObjectPointerType>(LHSType)) { 5415 // A* -> B* 5416 if (RHSType->isObjCObjectPointerType()) { 5417 Kind = CK_BitCast; 5418 Sema::AssignConvertType result = 5419 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 5420 if (getLangOptions().ObjCAutoRefCount && 5421 result == Compatible && 5422 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 5423 result = IncompatibleObjCWeakRef; 5424 return result; 5425 } 5426 5427 // int or null -> A* 5428 if (RHSType->isIntegerType()) { 5429 Kind = CK_IntegralToPointer; // FIXME: null 5430 return IntToPointer; 5431 } 5432 5433 // In general, C pointers are not compatible with ObjC object pointers, 5434 // with two exceptions: 5435 if (isa<PointerType>(RHSType)) { 5436 // - conversions from 'void*' 5437 if (RHSType->isVoidPointerType()) { 5438 Kind = CK_AnyPointerToObjCPointerCast; 5439 return Compatible; 5440 } 5441 5442 // - conversions to 'Class' from its redefinition type 5443 if (LHSType->isObjCClassType() && 5444 Context.hasSameType(RHSType, 5445 Context.getObjCClassRedefinitionType())) { 5446 Kind = CK_BitCast; 5447 return Compatible; 5448 } 5449 5450 Kind = CK_AnyPointerToObjCPointerCast; 5451 return IncompatiblePointer; 5452 } 5453 5454 // T^ -> A* 5455 if (RHSType->isBlockPointerType()) { 5456 Kind = CK_AnyPointerToObjCPointerCast; 5457 return Compatible; 5458 } 5459 5460 return Incompatible; 5461 } 5462 5463 // Conversions from pointers that are not covered by the above. 5464 if (isa<PointerType>(RHSType)) { 5465 // T* -> _Bool 5466 if (LHSType == Context.BoolTy) { 5467 Kind = CK_PointerToBoolean; 5468 return Compatible; 5469 } 5470 5471 // T* -> int 5472 if (LHSType->isIntegerType()) { 5473 Kind = CK_PointerToIntegral; 5474 return PointerToInt; 5475 } 5476 5477 return Incompatible; 5478 } 5479 5480 // Conversions from Objective-C pointers that are not covered by the above. 5481 if (isa<ObjCObjectPointerType>(RHSType)) { 5482 // T* -> _Bool 5483 if (LHSType == Context.BoolTy) { 5484 Kind = CK_PointerToBoolean; 5485 return Compatible; 5486 } 5487 5488 // T* -> int 5489 if (LHSType->isIntegerType()) { 5490 Kind = CK_PointerToIntegral; 5491 return PointerToInt; 5492 } 5493 5494 return Incompatible; 5495 } 5496 5497 // struct A -> struct B 5498 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 5499 if (Context.typesAreCompatible(LHSType, RHSType)) { 5500 Kind = CK_NoOp; 5501 return Compatible; 5502 } 5503 } 5504 5505 return Incompatible; 5506} 5507 5508/// \brief Constructs a transparent union from an expression that is 5509/// used to initialize the transparent union. 5510static void ConstructTransparentUnion(Sema &S, ASTContext &C, 5511 ExprResult &EResult, QualType UnionType, 5512 FieldDecl *Field) { 5513 // Build an initializer list that designates the appropriate member 5514 // of the transparent union. 5515 Expr *E = EResult.take(); 5516 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 5517 &E, 1, 5518 SourceLocation()); 5519 Initializer->setType(UnionType); 5520 Initializer->setInitializedFieldInUnion(Field); 5521 5522 // Build a compound literal constructing a value of the transparent 5523 // union type from this initializer list. 5524 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 5525 EResult = S.Owned( 5526 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 5527 VK_RValue, Initializer, false)); 5528} 5529 5530Sema::AssignConvertType 5531Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 5532 ExprResult &RHS) { 5533 QualType RHSType = RHS.get()->getType(); 5534 5535 // If the ArgType is a Union type, we want to handle a potential 5536 // transparent_union GCC extension. 5537 const RecordType *UT = ArgType->getAsUnionType(); 5538 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 5539 return Incompatible; 5540 5541 // The field to initialize within the transparent union. 5542 RecordDecl *UD = UT->getDecl(); 5543 FieldDecl *InitField = 0; 5544 // It's compatible if the expression matches any of the fields. 5545 for (RecordDecl::field_iterator it = UD->field_begin(), 5546 itend = UD->field_end(); 5547 it != itend; ++it) { 5548 if (it->getType()->isPointerType()) { 5549 // If the transparent union contains a pointer type, we allow: 5550 // 1) void pointer 5551 // 2) null pointer constant 5552 if (RHSType->isPointerType()) 5553 if (RHSType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 5554 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast); 5555 InitField = *it; 5556 break; 5557 } 5558 5559 if (RHS.get()->isNullPointerConstant(Context, 5560 Expr::NPC_ValueDependentIsNull)) { 5561 RHS = ImpCastExprToType(RHS.take(), it->getType(), 5562 CK_NullToPointer); 5563 InitField = *it; 5564 break; 5565 } 5566 } 5567 5568 CastKind Kind = CK_Invalid; 5569 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 5570 == Compatible) { 5571 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind); 5572 InitField = *it; 5573 break; 5574 } 5575 } 5576 5577 if (!InitField) 5578 return Incompatible; 5579 5580 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 5581 return Compatible; 5582} 5583 5584Sema::AssignConvertType 5585Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS) { 5586 if (getLangOptions().CPlusPlus) { 5587 if (!LHSType->isRecordType()) { 5588 // C++ 5.17p3: If the left operand is not of class type, the 5589 // expression is implicitly converted (C++ 4) to the 5590 // cv-unqualified type of the left operand. 5591 ExprResult Res = PerformImplicitConversion(RHS.get(), 5592 LHSType.getUnqualifiedType(), 5593 AA_Assigning); 5594 if (Res.isInvalid()) 5595 return Incompatible; 5596 Sema::AssignConvertType result = Compatible; 5597 if (getLangOptions().ObjCAutoRefCount && 5598 !CheckObjCARCUnavailableWeakConversion(LHSType, 5599 RHS.get()->getType())) 5600 result = IncompatibleObjCWeakRef; 5601 RHS = move(Res); 5602 return result; 5603 } 5604 5605 // FIXME: Currently, we fall through and treat C++ classes like C 5606 // structures. 5607 } 5608 5609 // C99 6.5.16.1p1: the left operand is a pointer and the right is 5610 // a null pointer constant. 5611 if ((LHSType->isPointerType() || 5612 LHSType->isObjCObjectPointerType() || 5613 LHSType->isBlockPointerType()) 5614 && RHS.get()->isNullPointerConstant(Context, 5615 Expr::NPC_ValueDependentIsNull)) { 5616 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 5617 return Compatible; 5618 } 5619 5620 // This check seems unnatural, however it is necessary to ensure the proper 5621 // conversion of functions/arrays. If the conversion were done for all 5622 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 5623 // expressions that suppress this implicit conversion (&, sizeof). 5624 // 5625 // Suppress this for references: C++ 8.5.3p5. 5626 if (!LHSType->isReferenceType()) { 5627 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 5628 if (RHS.isInvalid()) 5629 return Incompatible; 5630 } 5631 5632 CastKind Kind = CK_Invalid; 5633 Sema::AssignConvertType result = 5634 CheckAssignmentConstraints(LHSType, RHS, Kind); 5635 5636 // C99 6.5.16.1p2: The value of the right operand is converted to the 5637 // type of the assignment expression. 5638 // CheckAssignmentConstraints allows the left-hand side to be a reference, 5639 // so that we can use references in built-in functions even in C. 5640 // The getNonReferenceType() call makes sure that the resulting expression 5641 // does not have reference type. 5642 if (result != Incompatible && RHS.get()->getType() != LHSType) 5643 RHS = ImpCastExprToType(RHS.take(), 5644 LHSType.getNonLValueExprType(Context), Kind); 5645 return result; 5646} 5647 5648QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 5649 ExprResult &RHS) { 5650 Diag(Loc, diag::err_typecheck_invalid_operands) 5651 << LHS.get()->getType() << RHS.get()->getType() 5652 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5653 return QualType(); 5654} 5655 5656QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 5657 SourceLocation Loc, bool isCompAssign) { 5658 // For conversion purposes, we ignore any qualifiers. 5659 // For example, "const float" and "float" are equivalent. 5660 QualType LHSType = 5661 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 5662 QualType RHSType = 5663 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 5664 5665 // If the vector types are identical, return. 5666 if (LHSType == RHSType) 5667 return LHSType; 5668 5669 // Handle the case of equivalent AltiVec and GCC vector types 5670 if (LHSType->isVectorType() && RHSType->isVectorType() && 5671 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 5672 if (LHSType->isExtVectorType()) { 5673 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 5674 return LHSType; 5675 } 5676 5677 if (!isCompAssign) 5678 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 5679 return RHSType; 5680 } 5681 5682 if (getLangOptions().LaxVectorConversions && 5683 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) { 5684 // If we are allowing lax vector conversions, and LHS and RHS are both 5685 // vectors, the total size only needs to be the same. This is a 5686 // bitcast; no bits are changed but the result type is different. 5687 // FIXME: Should we really be allowing this? 5688 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 5689 return LHSType; 5690 } 5691 5692 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can 5693 // swap back (so that we don't reverse the inputs to a subtract, for instance. 5694 bool swapped = false; 5695 if (RHSType->isExtVectorType() && !isCompAssign) { 5696 swapped = true; 5697 std::swap(RHS, LHS); 5698 std::swap(RHSType, LHSType); 5699 } 5700 5701 // Handle the case of an ext vector and scalar. 5702 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) { 5703 QualType EltTy = LV->getElementType(); 5704 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) { 5705 int order = Context.getIntegerTypeOrder(EltTy, RHSType); 5706 if (order > 0) 5707 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast); 5708 if (order >= 0) { 5709 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 5710 if (swapped) std::swap(RHS, LHS); 5711 return LHSType; 5712 } 5713 } 5714 if (EltTy->isRealFloatingType() && RHSType->isScalarType() && 5715 RHSType->isRealFloatingType()) { 5716 int order = Context.getFloatingTypeOrder(EltTy, RHSType); 5717 if (order > 0) 5718 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast); 5719 if (order >= 0) { 5720 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 5721 if (swapped) std::swap(RHS, LHS); 5722 return LHSType; 5723 } 5724 } 5725 } 5726 5727 // Vectors of different size or scalar and non-ext-vector are errors. 5728 if (swapped) std::swap(RHS, LHS); 5729 Diag(Loc, diag::err_typecheck_vector_not_convertable) 5730 << LHS.get()->getType() << RHS.get()->getType() 5731 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5732 return QualType(); 5733} 5734 5735QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 5736 SourceLocation Loc, 5737 bool isCompAssign, bool isDiv) { 5738 if (LHS.get()->getType()->isVectorType() || 5739 RHS.get()->getType()->isVectorType()) 5740 return CheckVectorOperands(LHS, RHS, Loc, isCompAssign); 5741 5742 QualType compType = UsualArithmeticConversions(LHS, RHS, isCompAssign); 5743 if (LHS.isInvalid() || RHS.isInvalid()) 5744 return QualType(); 5745 5746 if (!LHS.get()->getType()->isArithmeticType() || 5747 !RHS.get()->getType()->isArithmeticType()) 5748 return InvalidOperands(Loc, LHS, RHS); 5749 5750 // Check for division by zero. 5751 if (isDiv && 5752 RHS.get()->isNullPointerConstant(Context, 5753 Expr::NPC_ValueDependentIsNotNull)) 5754 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero) 5755 << RHS.get()->getSourceRange()); 5756 5757 return compType; 5758} 5759 5760QualType Sema::CheckRemainderOperands( 5761 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool isCompAssign) { 5762 if (LHS.get()->getType()->isVectorType() || 5763 RHS.get()->getType()->isVectorType()) { 5764 if (LHS.get()->getType()->hasIntegerRepresentation() && 5765 RHS.get()->getType()->hasIntegerRepresentation()) 5766 return CheckVectorOperands(LHS, RHS, Loc, isCompAssign); 5767 return InvalidOperands(Loc, LHS, RHS); 5768 } 5769 5770 QualType compType = UsualArithmeticConversions(LHS, RHS, isCompAssign); 5771 if (LHS.isInvalid() || RHS.isInvalid()) 5772 return QualType(); 5773 5774 if (!LHS.get()->getType()->isIntegerType() || 5775 !RHS.get()->getType()->isIntegerType()) 5776 return InvalidOperands(Loc, LHS, RHS); 5777 5778 // Check for remainder by zero. 5779 if (RHS.get()->isNullPointerConstant(Context, 5780 Expr::NPC_ValueDependentIsNotNull)) 5781 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero) 5782 << RHS.get()->getSourceRange()); 5783 5784 return compType; 5785} 5786 5787/// \brief Diagnose invalid arithmetic on two void pointers. 5788static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 5789 Expr *LHSExpr, Expr *RHSExpr) { 5790 S.Diag(Loc, S.getLangOptions().CPlusPlus 5791 ? diag::err_typecheck_pointer_arith_void_type 5792 : diag::ext_gnu_void_ptr) 5793 << 1 /* two pointers */ << LHSExpr->getSourceRange() 5794 << RHSExpr->getSourceRange(); 5795} 5796 5797/// \brief Diagnose invalid arithmetic on a void pointer. 5798static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 5799 Expr *Pointer) { 5800 S.Diag(Loc, S.getLangOptions().CPlusPlus 5801 ? diag::err_typecheck_pointer_arith_void_type 5802 : diag::ext_gnu_void_ptr) 5803 << 0 /* one pointer */ << Pointer->getSourceRange(); 5804} 5805 5806/// \brief Diagnose invalid arithmetic on two function pointers. 5807static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 5808 Expr *LHS, Expr *RHS) { 5809 assert(LHS->getType()->isAnyPointerType()); 5810 assert(RHS->getType()->isAnyPointerType()); 5811 S.Diag(Loc, S.getLangOptions().CPlusPlus 5812 ? diag::err_typecheck_pointer_arith_function_type 5813 : diag::ext_gnu_ptr_func_arith) 5814 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 5815 // We only show the second type if it differs from the first. 5816 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 5817 RHS->getType()) 5818 << RHS->getType()->getPointeeType() 5819 << LHS->getSourceRange() << RHS->getSourceRange(); 5820} 5821 5822/// \brief Diagnose invalid arithmetic on a function pointer. 5823static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 5824 Expr *Pointer) { 5825 assert(Pointer->getType()->isAnyPointerType()); 5826 S.Diag(Loc, S.getLangOptions().CPlusPlus 5827 ? diag::err_typecheck_pointer_arith_function_type 5828 : diag::ext_gnu_ptr_func_arith) 5829 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 5830 << 0 /* one pointer, so only one type */ 5831 << Pointer->getSourceRange(); 5832} 5833 5834/// \brief Warn if Operand is incomplete pointer type 5835/// 5836/// \returns True if pointer has incomplete type 5837static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 5838 Expr *Operand) { 5839 if ((Operand->getType()->isPointerType() && 5840 !Operand->getType()->isDependentType()) || 5841 Operand->getType()->isObjCObjectPointerType()) { 5842 QualType PointeeTy = Operand->getType()->getPointeeType(); 5843 if (S.RequireCompleteType( 5844 Loc, PointeeTy, 5845 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type) 5846 << PointeeTy << Operand->getSourceRange())) 5847 return true; 5848 } 5849 return false; 5850} 5851 5852/// \brief Check the validity of an arithmetic pointer operand. 5853/// 5854/// If the operand has pointer type, this code will check for pointer types 5855/// which are invalid in arithmetic operations. These will be diagnosed 5856/// appropriately, including whether or not the use is supported as an 5857/// extension. 5858/// 5859/// \returns True when the operand is valid to use (even if as an extension). 5860static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 5861 Expr *Operand) { 5862 if (!Operand->getType()->isAnyPointerType()) return true; 5863 5864 QualType PointeeTy = Operand->getType()->getPointeeType(); 5865 if (PointeeTy->isVoidType()) { 5866 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 5867 return !S.getLangOptions().CPlusPlus; 5868 } 5869 if (PointeeTy->isFunctionType()) { 5870 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 5871 return !S.getLangOptions().CPlusPlus; 5872 } 5873 5874 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 5875 5876 return true; 5877} 5878 5879/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 5880/// operands. 5881/// 5882/// This routine will diagnose any invalid arithmetic on pointer operands much 5883/// like \see checkArithmeticOpPointerOperand. However, it has special logic 5884/// for emitting a single diagnostic even for operations where both LHS and RHS 5885/// are (potentially problematic) pointers. 5886/// 5887/// \returns True when the operand is valid to use (even if as an extension). 5888static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 5889 Expr *LHSExpr, Expr *RHSExpr) { 5890 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 5891 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 5892 if (!isLHSPointer && !isRHSPointer) return true; 5893 5894 QualType LHSPointeeTy, RHSPointeeTy; 5895 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 5896 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 5897 5898 // Check for arithmetic on pointers to incomplete types. 5899 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 5900 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 5901 if (isLHSVoidPtr || isRHSVoidPtr) { 5902 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 5903 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 5904 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 5905 5906 return !S.getLangOptions().CPlusPlus; 5907 } 5908 5909 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 5910 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 5911 if (isLHSFuncPtr || isRHSFuncPtr) { 5912 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 5913 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 5914 RHSExpr); 5915 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 5916 5917 return !S.getLangOptions().CPlusPlus; 5918 } 5919 5920 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false; 5921 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false; 5922 5923 return true; 5924} 5925 5926/// \brief Check bad cases where we step over interface counts. 5927static bool checkArithmethicPointerOnNonFragileABI(Sema &S, 5928 SourceLocation OpLoc, 5929 Expr *Op) { 5930 assert(Op->getType()->isAnyPointerType()); 5931 QualType PointeeTy = Op->getType()->getPointeeType(); 5932 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI) 5933 return true; 5934 5935 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface) 5936 << PointeeTy << Op->getSourceRange(); 5937 return false; 5938} 5939 5940/// \brief Warn when two pointers are incompatible. 5941static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 5942 Expr *LHSExpr, Expr *RHSExpr) { 5943 assert(LHSExpr->getType()->isAnyPointerType()); 5944 assert(RHSExpr->getType()->isAnyPointerType()); 5945 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 5946 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 5947 << RHSExpr->getSourceRange(); 5948} 5949 5950QualType Sema::CheckAdditionOperands( // C99 6.5.6 5951 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy) { 5952 if (LHS.get()->getType()->isVectorType() || 5953 RHS.get()->getType()->isVectorType()) { 5954 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 5955 if (CompLHSTy) *CompLHSTy = compType; 5956 return compType; 5957 } 5958 5959 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 5960 if (LHS.isInvalid() || RHS.isInvalid()) 5961 return QualType(); 5962 5963 // handle the common case first (both operands are arithmetic). 5964 if (LHS.get()->getType()->isArithmeticType() && 5965 RHS.get()->getType()->isArithmeticType()) { 5966 if (CompLHSTy) *CompLHSTy = compType; 5967 return compType; 5968 } 5969 5970 // Put any potential pointer into PExp 5971 Expr* PExp = LHS.get(), *IExp = RHS.get(); 5972 if (IExp->getType()->isAnyPointerType()) 5973 std::swap(PExp, IExp); 5974 5975 if (PExp->getType()->isAnyPointerType()) { 5976 if (IExp->getType()->isIntegerType()) { 5977 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 5978 return QualType(); 5979 5980 // Diagnose bad cases where we step over interface counts. 5981 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp)) 5982 return QualType(); 5983 5984 // Check array bounds for pointer arithemtic 5985 CheckArrayAccess(PExp, IExp); 5986 5987 if (CompLHSTy) { 5988 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 5989 if (LHSTy.isNull()) { 5990 LHSTy = LHS.get()->getType(); 5991 if (LHSTy->isPromotableIntegerType()) 5992 LHSTy = Context.getPromotedIntegerType(LHSTy); 5993 } 5994 *CompLHSTy = LHSTy; 5995 } 5996 return PExp->getType(); 5997 } 5998 } 5999 6000 return InvalidOperands(Loc, LHS, RHS); 6001} 6002 6003// C99 6.5.6 6004QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 6005 SourceLocation Loc, 6006 QualType* CompLHSTy) { 6007 if (LHS.get()->getType()->isVectorType() || 6008 RHS.get()->getType()->isVectorType()) { 6009 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 6010 if (CompLHSTy) *CompLHSTy = compType; 6011 return compType; 6012 } 6013 6014 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 6015 if (LHS.isInvalid() || RHS.isInvalid()) 6016 return QualType(); 6017 6018 // Enforce type constraints: C99 6.5.6p3. 6019 6020 // Handle the common case first (both operands are arithmetic). 6021 if (LHS.get()->getType()->isArithmeticType() && 6022 RHS.get()->getType()->isArithmeticType()) { 6023 if (CompLHSTy) *CompLHSTy = compType; 6024 return compType; 6025 } 6026 6027 // Either ptr - int or ptr - ptr. 6028 if (LHS.get()->getType()->isAnyPointerType()) { 6029 QualType lpointee = LHS.get()->getType()->getPointeeType(); 6030 6031 // Diagnose bad cases where we step over interface counts. 6032 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get())) 6033 return QualType(); 6034 6035 // The result type of a pointer-int computation is the pointer type. 6036 if (RHS.get()->getType()->isIntegerType()) { 6037 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 6038 return QualType(); 6039 6040 Expr *IExpr = RHS.get()->IgnoreParenCasts(); 6041 UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue, 6042 OK_Ordinary, IExpr->getExprLoc()); 6043 // Check array bounds for pointer arithemtic 6044 CheckArrayAccess(LHS.get()->IgnoreParenCasts(), &negRex); 6045 6046 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 6047 return LHS.get()->getType(); 6048 } 6049 6050 // Handle pointer-pointer subtractions. 6051 if (const PointerType *RHSPTy 6052 = RHS.get()->getType()->getAs<PointerType>()) { 6053 QualType rpointee = RHSPTy->getPointeeType(); 6054 6055 if (getLangOptions().CPlusPlus) { 6056 // Pointee types must be the same: C++ [expr.add] 6057 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 6058 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 6059 } 6060 } else { 6061 // Pointee types must be compatible C99 6.5.6p3 6062 if (!Context.typesAreCompatible( 6063 Context.getCanonicalType(lpointee).getUnqualifiedType(), 6064 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 6065 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 6066 return QualType(); 6067 } 6068 } 6069 6070 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 6071 LHS.get(), RHS.get())) 6072 return QualType(); 6073 6074 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 6075 return Context.getPointerDiffType(); 6076 } 6077 } 6078 6079 return InvalidOperands(Loc, LHS, RHS); 6080} 6081 6082static bool isScopedEnumerationType(QualType T) { 6083 if (const EnumType *ET = dyn_cast<EnumType>(T)) 6084 return ET->getDecl()->isScoped(); 6085 return false; 6086} 6087 6088static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 6089 SourceLocation Loc, unsigned Opc, 6090 QualType LHSType) { 6091 llvm::APSInt Right; 6092 // Check right/shifter operand 6093 if (RHS.get()->isValueDependent() || 6094 !RHS.get()->isIntegerConstantExpr(Right, S.Context)) 6095 return; 6096 6097 if (Right.isNegative()) { 6098 S.DiagRuntimeBehavior(Loc, RHS.get(), 6099 S.PDiag(diag::warn_shift_negative) 6100 << RHS.get()->getSourceRange()); 6101 return; 6102 } 6103 llvm::APInt LeftBits(Right.getBitWidth(), 6104 S.Context.getTypeSize(LHS.get()->getType())); 6105 if (Right.uge(LeftBits)) { 6106 S.DiagRuntimeBehavior(Loc, RHS.get(), 6107 S.PDiag(diag::warn_shift_gt_typewidth) 6108 << RHS.get()->getSourceRange()); 6109 return; 6110 } 6111 if (Opc != BO_Shl) 6112 return; 6113 6114 // When left shifting an ICE which is signed, we can check for overflow which 6115 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 6116 // integers have defined behavior modulo one more than the maximum value 6117 // representable in the result type, so never warn for those. 6118 llvm::APSInt Left; 6119 if (LHS.get()->isValueDependent() || 6120 !LHS.get()->isIntegerConstantExpr(Left, S.Context) || 6121 LHSType->hasUnsignedIntegerRepresentation()) 6122 return; 6123 llvm::APInt ResultBits = 6124 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 6125 if (LeftBits.uge(ResultBits)) 6126 return; 6127 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 6128 Result = Result.shl(Right); 6129 6130 // Print the bit representation of the signed integer as an unsigned 6131 // hexadecimal number. 6132 llvm::SmallString<40> HexResult; 6133 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 6134 6135 // If we are only missing a sign bit, this is less likely to result in actual 6136 // bugs -- if the result is cast back to an unsigned type, it will have the 6137 // expected value. Thus we place this behind a different warning that can be 6138 // turned off separately if needed. 6139 if (LeftBits == ResultBits - 1) { 6140 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 6141 << HexResult.str() << LHSType 6142 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6143 return; 6144 } 6145 6146 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 6147 << HexResult.str() << Result.getMinSignedBits() << LHSType 6148 << Left.getBitWidth() << LHS.get()->getSourceRange() 6149 << RHS.get()->getSourceRange(); 6150} 6151 6152// C99 6.5.7 6153QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 6154 SourceLocation Loc, unsigned Opc, 6155 bool isCompAssign) { 6156 // C99 6.5.7p2: Each of the operands shall have integer type. 6157 if (!LHS.get()->getType()->hasIntegerRepresentation() || 6158 !RHS.get()->getType()->hasIntegerRepresentation()) 6159 return InvalidOperands(Loc, LHS, RHS); 6160 6161 // C++0x: Don't allow scoped enums. FIXME: Use something better than 6162 // hasIntegerRepresentation() above instead of this. 6163 if (isScopedEnumerationType(LHS.get()->getType()) || 6164 isScopedEnumerationType(RHS.get()->getType())) { 6165 return InvalidOperands(Loc, LHS, RHS); 6166 } 6167 6168 // Vector shifts promote their scalar inputs to vector type. 6169 if (LHS.get()->getType()->isVectorType() || 6170 RHS.get()->getType()->isVectorType()) 6171 return CheckVectorOperands(LHS, RHS, Loc, isCompAssign); 6172 6173 // Shifts don't perform usual arithmetic conversions, they just do integer 6174 // promotions on each operand. C99 6.5.7p3 6175 6176 // For the LHS, do usual unary conversions, but then reset them away 6177 // if this is a compound assignment. 6178 ExprResult OldLHS = LHS; 6179 LHS = UsualUnaryConversions(LHS.take()); 6180 if (LHS.isInvalid()) 6181 return QualType(); 6182 QualType LHSType = LHS.get()->getType(); 6183 if (isCompAssign) LHS = OldLHS; 6184 6185 // The RHS is simpler. 6186 RHS = UsualUnaryConversions(RHS.take()); 6187 if (RHS.isInvalid()) 6188 return QualType(); 6189 6190 // Sanity-check shift operands 6191 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 6192 6193 // "The type of the result is that of the promoted left operand." 6194 return LHSType; 6195} 6196 6197static bool IsWithinTemplateSpecialization(Decl *D) { 6198 if (DeclContext *DC = D->getDeclContext()) { 6199 if (isa<ClassTemplateSpecializationDecl>(DC)) 6200 return true; 6201 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 6202 return FD->isFunctionTemplateSpecialization(); 6203 } 6204 return false; 6205} 6206 6207/// If two different enums are compared, raise a warning. 6208static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, 6209 ExprResult &RHS) { 6210 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType(); 6211 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType(); 6212 6213 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 6214 if (!LHSEnumType) 6215 return; 6216 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 6217 if (!RHSEnumType) 6218 return; 6219 6220 // Ignore anonymous enums. 6221 if (!LHSEnumType->getDecl()->getIdentifier()) 6222 return; 6223 if (!RHSEnumType->getDecl()->getIdentifier()) 6224 return; 6225 6226 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 6227 return; 6228 6229 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 6230 << LHSStrippedType << RHSStrippedType 6231 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6232} 6233 6234/// \brief Diagnose bad pointer comparisons. 6235static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 6236 ExprResult &LHS, ExprResult &RHS, 6237 bool isError) { 6238 S.Diag(Loc, isError ? diag::err_typecheck_comparison_of_distinct_pointers 6239 : diag::ext_typecheck_comparison_of_distinct_pointers) 6240 << LHS.get()->getType() << RHS.get()->getType() 6241 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6242} 6243 6244/// \brief Returns false if the pointers are converted to a composite type, 6245/// true otherwise. 6246static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 6247 ExprResult &LHS, ExprResult &RHS) { 6248 // C++ [expr.rel]p2: 6249 // [...] Pointer conversions (4.10) and qualification 6250 // conversions (4.4) are performed on pointer operands (or on 6251 // a pointer operand and a null pointer constant) to bring 6252 // them to their composite pointer type. [...] 6253 // 6254 // C++ [expr.eq]p1 uses the same notion for (in)equality 6255 // comparisons of pointers. 6256 6257 // C++ [expr.eq]p2: 6258 // In addition, pointers to members can be compared, or a pointer to 6259 // member and a null pointer constant. Pointer to member conversions 6260 // (4.11) and qualification conversions (4.4) are performed to bring 6261 // them to a common type. If one operand is a null pointer constant, 6262 // the common type is the type of the other operand. Otherwise, the 6263 // common type is a pointer to member type similar (4.4) to the type 6264 // of one of the operands, with a cv-qualification signature (4.4) 6265 // that is the union of the cv-qualification signatures of the operand 6266 // types. 6267 6268 QualType LHSType = LHS.get()->getType(); 6269 QualType RHSType = RHS.get()->getType(); 6270 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 6271 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 6272 6273 bool NonStandardCompositeType = false; 6274 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType; 6275 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 6276 if (T.isNull()) { 6277 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 6278 return true; 6279 } 6280 6281 if (NonStandardCompositeType) 6282 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 6283 << LHSType << RHSType << T << LHS.get()->getSourceRange() 6284 << RHS.get()->getSourceRange(); 6285 6286 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast); 6287 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast); 6288 return false; 6289} 6290 6291static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 6292 ExprResult &LHS, 6293 ExprResult &RHS, 6294 bool isError) { 6295 S.Diag(Loc,isError ? diag::err_typecheck_comparison_of_fptr_to_void 6296 : diag::ext_typecheck_comparison_of_fptr_to_void) 6297 << LHS.get()->getType() << RHS.get()->getType() 6298 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6299} 6300 6301// C99 6.5.8, C++ [expr.rel] 6302QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 6303 SourceLocation Loc, unsigned OpaqueOpc, 6304 bool isRelational) { 6305 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 6306 6307 // Handle vector comparisons separately. 6308 if (LHS.get()->getType()->isVectorType() || 6309 RHS.get()->getType()->isVectorType()) 6310 return CheckVectorCompareOperands(LHS, RHS, Loc, isRelational); 6311 6312 QualType LHSType = LHS.get()->getType(); 6313 QualType RHSType = RHS.get()->getType(); 6314 6315 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 6316 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 6317 6318 checkEnumComparison(*this, Loc, LHS, RHS); 6319 6320 if (!LHSType->hasFloatingRepresentation() && 6321 !(LHSType->isBlockPointerType() && isRelational) && 6322 !LHS.get()->getLocStart().isMacroID() && 6323 !RHS.get()->getLocStart().isMacroID()) { 6324 // For non-floating point types, check for self-comparisons of the form 6325 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 6326 // often indicate logic errors in the program. 6327 // 6328 // NOTE: Don't warn about comparison expressions resulting from macro 6329 // expansion. Also don't warn about comparisons which are only self 6330 // comparisons within a template specialization. The warnings should catch 6331 // obvious cases in the definition of the template anyways. The idea is to 6332 // warn when the typed comparison operator will always evaluate to the same 6333 // result. 6334 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) { 6335 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) { 6336 if (DRL->getDecl() == DRR->getDecl() && 6337 !IsWithinTemplateSpecialization(DRL->getDecl())) { 6338 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 6339 << 0 // self- 6340 << (Opc == BO_EQ 6341 || Opc == BO_LE 6342 || Opc == BO_GE)); 6343 } else if (LHSType->isArrayType() && RHSType->isArrayType() && 6344 !DRL->getDecl()->getType()->isReferenceType() && 6345 !DRR->getDecl()->getType()->isReferenceType()) { 6346 // what is it always going to eval to? 6347 char always_evals_to; 6348 switch(Opc) { 6349 case BO_EQ: // e.g. array1 == array2 6350 always_evals_to = 0; // false 6351 break; 6352 case BO_NE: // e.g. array1 != array2 6353 always_evals_to = 1; // true 6354 break; 6355 default: 6356 // best we can say is 'a constant' 6357 always_evals_to = 2; // e.g. array1 <= array2 6358 break; 6359 } 6360 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 6361 << 1 // array 6362 << always_evals_to); 6363 } 6364 } 6365 } 6366 6367 if (isa<CastExpr>(LHSStripped)) 6368 LHSStripped = LHSStripped->IgnoreParenCasts(); 6369 if (isa<CastExpr>(RHSStripped)) 6370 RHSStripped = RHSStripped->IgnoreParenCasts(); 6371 6372 // Warn about comparisons against a string constant (unless the other 6373 // operand is null), the user probably wants strcmp. 6374 Expr *literalString = 0; 6375 Expr *literalStringStripped = 0; 6376 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 6377 !RHSStripped->isNullPointerConstant(Context, 6378 Expr::NPC_ValueDependentIsNull)) { 6379 literalString = LHS.get(); 6380 literalStringStripped = LHSStripped; 6381 } else if ((isa<StringLiteral>(RHSStripped) || 6382 isa<ObjCEncodeExpr>(RHSStripped)) && 6383 !LHSStripped->isNullPointerConstant(Context, 6384 Expr::NPC_ValueDependentIsNull)) { 6385 literalString = RHS.get(); 6386 literalStringStripped = RHSStripped; 6387 } 6388 6389 if (literalString) { 6390 std::string resultComparison; 6391 switch (Opc) { 6392 case BO_LT: resultComparison = ") < 0"; break; 6393 case BO_GT: resultComparison = ") > 0"; break; 6394 case BO_LE: resultComparison = ") <= 0"; break; 6395 case BO_GE: resultComparison = ") >= 0"; break; 6396 case BO_EQ: resultComparison = ") == 0"; break; 6397 case BO_NE: resultComparison = ") != 0"; break; 6398 default: assert(false && "Invalid comparison operator"); 6399 } 6400 6401 DiagRuntimeBehavior(Loc, 0, 6402 PDiag(diag::warn_stringcompare) 6403 << isa<ObjCEncodeExpr>(literalStringStripped) 6404 << literalString->getSourceRange()); 6405 } 6406 } 6407 6408 // C99 6.5.8p3 / C99 6.5.9p4 6409 if (LHS.get()->getType()->isArithmeticType() && 6410 RHS.get()->getType()->isArithmeticType()) { 6411 UsualArithmeticConversions(LHS, RHS); 6412 if (LHS.isInvalid() || RHS.isInvalid()) 6413 return QualType(); 6414 } 6415 else { 6416 LHS = UsualUnaryConversions(LHS.take()); 6417 if (LHS.isInvalid()) 6418 return QualType(); 6419 6420 RHS = UsualUnaryConversions(RHS.take()); 6421 if (RHS.isInvalid()) 6422 return QualType(); 6423 } 6424 6425 LHSType = LHS.get()->getType(); 6426 RHSType = RHS.get()->getType(); 6427 6428 // The result of comparisons is 'bool' in C++, 'int' in C. 6429 QualType ResultTy = Context.getLogicalOperationType(); 6430 6431 if (isRelational) { 6432 if (LHSType->isRealType() && RHSType->isRealType()) 6433 return ResultTy; 6434 } else { 6435 // Check for comparisons of floating point operands using != and ==. 6436 if (LHSType->hasFloatingRepresentation()) 6437 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 6438 6439 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 6440 return ResultTy; 6441 } 6442 6443 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context, 6444 Expr::NPC_ValueDependentIsNull); 6445 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context, 6446 Expr::NPC_ValueDependentIsNull); 6447 6448 // All of the following pointer-related warnings are GCC extensions, except 6449 // when handling null pointer constants. 6450 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 6451 QualType LCanPointeeTy = 6452 Context.getCanonicalType(LHSType->getAs<PointerType>()->getPointeeType()); 6453 QualType RCanPointeeTy = 6454 Context.getCanonicalType(RHSType->getAs<PointerType>()->getPointeeType()); 6455 6456 if (getLangOptions().CPlusPlus) { 6457 if (LCanPointeeTy == RCanPointeeTy) 6458 return ResultTy; 6459 if (!isRelational && 6460 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 6461 // Valid unless comparison between non-null pointer and function pointer 6462 // This is a gcc extension compatibility comparison. 6463 // In a SFINAE context, we treat this as a hard error to maintain 6464 // conformance with the C++ standard. 6465 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 6466 && !LHSIsNull && !RHSIsNull) { 6467 diagnoseFunctionPointerToVoidComparison( 6468 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext()); 6469 6470 if (isSFINAEContext()) 6471 return QualType(); 6472 6473 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6474 return ResultTy; 6475 } 6476 } 6477 6478 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 6479 return QualType(); 6480 else 6481 return ResultTy; 6482 } 6483 // C99 6.5.9p2 and C99 6.5.8p2 6484 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 6485 RCanPointeeTy.getUnqualifiedType())) { 6486 // Valid unless a relational comparison of function pointers 6487 if (isRelational && LCanPointeeTy->isFunctionType()) { 6488 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 6489 << LHSType << RHSType << LHS.get()->getSourceRange() 6490 << RHS.get()->getSourceRange(); 6491 } 6492 } else if (!isRelational && 6493 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 6494 // Valid unless comparison between non-null pointer and function pointer 6495 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 6496 && !LHSIsNull && !RHSIsNull) 6497 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 6498 /*isError*/false); 6499 } else { 6500 // Invalid 6501 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 6502 } 6503 if (LCanPointeeTy != RCanPointeeTy) { 6504 if (LHSIsNull && !RHSIsNull) 6505 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 6506 else 6507 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6508 } 6509 return ResultTy; 6510 } 6511 6512 if (getLangOptions().CPlusPlus) { 6513 // Comparison of nullptr_t with itself. 6514 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 6515 return ResultTy; 6516 6517 // Comparison of pointers with null pointer constants and equality 6518 // comparisons of member pointers to null pointer constants. 6519 if (RHSIsNull && 6520 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 6521 (!isRelational && 6522 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 6523 RHS = ImpCastExprToType(RHS.take(), LHSType, 6524 LHSType->isMemberPointerType() 6525 ? CK_NullToMemberPointer 6526 : CK_NullToPointer); 6527 return ResultTy; 6528 } 6529 if (LHSIsNull && 6530 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 6531 (!isRelational && 6532 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 6533 LHS = ImpCastExprToType(LHS.take(), RHSType, 6534 RHSType->isMemberPointerType() 6535 ? CK_NullToMemberPointer 6536 : CK_NullToPointer); 6537 return ResultTy; 6538 } 6539 6540 // Comparison of member pointers. 6541 if (!isRelational && 6542 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 6543 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 6544 return QualType(); 6545 else 6546 return ResultTy; 6547 } 6548 6549 // Handle scoped enumeration types specifically, since they don't promote 6550 // to integers. 6551 if (LHS.get()->getType()->isEnumeralType() && 6552 Context.hasSameUnqualifiedType(LHS.get()->getType(), 6553 RHS.get()->getType())) 6554 return ResultTy; 6555 } 6556 6557 // Handle block pointer types. 6558 if (!isRelational && LHSType->isBlockPointerType() && 6559 RHSType->isBlockPointerType()) { 6560 QualType lpointee = LHSType->getAs<BlockPointerType>()->getPointeeType(); 6561 QualType rpointee = RHSType->getAs<BlockPointerType>()->getPointeeType(); 6562 6563 if (!LHSIsNull && !RHSIsNull && 6564 !Context.typesAreCompatible(lpointee, rpointee)) { 6565 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 6566 << LHSType << RHSType << LHS.get()->getSourceRange() 6567 << RHS.get()->getSourceRange(); 6568 } 6569 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6570 return ResultTy; 6571 } 6572 6573 // Allow block pointers to be compared with null pointer constants. 6574 if (!isRelational 6575 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 6576 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 6577 if (!LHSIsNull && !RHSIsNull) { 6578 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 6579 ->getPointeeType()->isVoidType()) 6580 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 6581 ->getPointeeType()->isVoidType()))) 6582 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 6583 << LHSType << RHSType << LHS.get()->getSourceRange() 6584 << RHS.get()->getSourceRange(); 6585 } 6586 if (LHSIsNull && !RHSIsNull) 6587 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 6588 else 6589 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6590 return ResultTy; 6591 } 6592 6593 if (LHSType->isObjCObjectPointerType() || 6594 RHSType->isObjCObjectPointerType()) { 6595 const PointerType *LPT = LHSType->getAs<PointerType>(); 6596 const PointerType *RPT = RHSType->getAs<PointerType>(); 6597 if (LPT || RPT) { 6598 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 6599 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 6600 6601 if (!LPtrToVoid && !RPtrToVoid && 6602 !Context.typesAreCompatible(LHSType, RHSType)) { 6603 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 6604 /*isError*/false); 6605 } 6606 if (LHSIsNull && !RHSIsNull) 6607 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 6608 else 6609 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6610 return ResultTy; 6611 } 6612 if (LHSType->isObjCObjectPointerType() && 6613 RHSType->isObjCObjectPointerType()) { 6614 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 6615 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 6616 /*isError*/false); 6617 if (LHSIsNull && !RHSIsNull) 6618 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 6619 else 6620 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6621 return ResultTy; 6622 } 6623 } 6624 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 6625 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 6626 unsigned DiagID = 0; 6627 bool isError = false; 6628 if ((LHSIsNull && LHSType->isIntegerType()) || 6629 (RHSIsNull && RHSType->isIntegerType())) { 6630 if (isRelational && !getLangOptions().CPlusPlus) 6631 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 6632 } else if (isRelational && !getLangOptions().CPlusPlus) 6633 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 6634 else if (getLangOptions().CPlusPlus) { 6635 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 6636 isError = true; 6637 } else 6638 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 6639 6640 if (DiagID) { 6641 Diag(Loc, DiagID) 6642 << LHSType << RHSType << LHS.get()->getSourceRange() 6643 << RHS.get()->getSourceRange(); 6644 if (isError) 6645 return QualType(); 6646 } 6647 6648 if (LHSType->isIntegerType()) 6649 LHS = ImpCastExprToType(LHS.take(), RHSType, 6650 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 6651 else 6652 RHS = ImpCastExprToType(RHS.take(), LHSType, 6653 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 6654 return ResultTy; 6655 } 6656 6657 // Handle block pointers. 6658 if (!isRelational && RHSIsNull 6659 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 6660 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 6661 return ResultTy; 6662 } 6663 if (!isRelational && LHSIsNull 6664 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 6665 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer); 6666 return ResultTy; 6667 } 6668 6669 return InvalidOperands(Loc, LHS, RHS); 6670} 6671 6672/// CheckVectorCompareOperands - vector comparisons are a clang extension that 6673/// operates on extended vector types. Instead of producing an IntTy result, 6674/// like a scalar comparison, a vector comparison produces a vector of integer 6675/// types. 6676QualType Sema::CheckVectorCompareOperands(ExprResult &lex, ExprResult &rex, 6677 SourceLocation Loc, 6678 bool isRelational) { 6679 // Check to make sure we're operating on vectors of the same type and width, 6680 // Allowing one side to be a scalar of element type. 6681 QualType vType = CheckVectorOperands(lex, rex, Loc, /*isCompAssign*/false); 6682 if (vType.isNull()) 6683 return vType; 6684 6685 QualType lType = lex.get()->getType(); 6686 QualType rType = rex.get()->getType(); 6687 6688 // If AltiVec, the comparison results in a numeric type, i.e. 6689 // bool for C++, int for C 6690 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 6691 return Context.getLogicalOperationType(); 6692 6693 // For non-floating point types, check for self-comparisons of the form 6694 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 6695 // often indicate logic errors in the program. 6696 if (!lType->hasFloatingRepresentation()) { 6697 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex.get()->IgnoreParens())) 6698 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex.get()->IgnoreParens())) 6699 if (DRL->getDecl() == DRR->getDecl()) 6700 DiagRuntimeBehavior(Loc, 0, 6701 PDiag(diag::warn_comparison_always) 6702 << 0 // self- 6703 << 2 // "a constant" 6704 ); 6705 } 6706 6707 // Check for comparisons of floating point operands using != and ==. 6708 if (!isRelational && lType->hasFloatingRepresentation()) { 6709 assert (rType->hasFloatingRepresentation()); 6710 CheckFloatComparison(Loc, lex.get(), rex.get()); 6711 } 6712 6713 // Return the type for the comparison, which is the same as vector type for 6714 // integer vectors, or an integer type of identical size and number of 6715 // elements for floating point vectors. 6716 if (lType->hasIntegerRepresentation()) 6717 return lType; 6718 6719 const VectorType *VTy = lType->getAs<VectorType>(); 6720 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 6721 if (TypeSize == Context.getTypeSize(Context.IntTy)) 6722 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 6723 if (TypeSize == Context.getTypeSize(Context.LongTy)) 6724 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 6725 6726 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 6727 "Unhandled vector element size in vector compare"); 6728 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 6729} 6730 6731inline QualType Sema::CheckBitwiseOperands( 6732 ExprResult &lex, ExprResult &rex, SourceLocation Loc, bool isCompAssign) { 6733 if (lex.get()->getType()->isVectorType() || 6734 rex.get()->getType()->isVectorType()) { 6735 if (lex.get()->getType()->hasIntegerRepresentation() && 6736 rex.get()->getType()->hasIntegerRepresentation()) 6737 return CheckVectorOperands(lex, rex, Loc, isCompAssign); 6738 6739 return InvalidOperands(Loc, lex, rex); 6740 } 6741 6742 ExprResult lexResult = Owned(lex), rexResult = Owned(rex); 6743 QualType compType = UsualArithmeticConversions(lexResult, rexResult, 6744 isCompAssign); 6745 if (lexResult.isInvalid() || rexResult.isInvalid()) 6746 return QualType(); 6747 lex = lexResult.take(); 6748 rex = rexResult.take(); 6749 6750 if (lex.get()->getType()->isIntegralOrUnscopedEnumerationType() && 6751 rex.get()->getType()->isIntegralOrUnscopedEnumerationType()) 6752 return compType; 6753 return InvalidOperands(Loc, lex, rex); 6754} 6755 6756inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 6757 ExprResult &lex, ExprResult &rex, SourceLocation Loc, unsigned Opc) { 6758 6759 // Diagnose cases where the user write a logical and/or but probably meant a 6760 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 6761 // is a constant. 6762 if (lex.get()->getType()->isIntegerType() && 6763 !lex.get()->getType()->isBooleanType() && 6764 rex.get()->getType()->isIntegerType() && !rex.get()->isValueDependent() && 6765 // Don't warn in macros or template instantiations. 6766 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 6767 // If the RHS can be constant folded, and if it constant folds to something 6768 // that isn't 0 or 1 (which indicate a potential logical operation that 6769 // happened to fold to true/false) then warn. 6770 // Parens on the RHS are ignored. 6771 Expr::EvalResult Result; 6772 if (rex.get()->Evaluate(Result, Context) && !Result.HasSideEffects) 6773 if ((getLangOptions().Bool && !rex.get()->getType()->isBooleanType()) || 6774 (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) { 6775 Diag(Loc, diag::warn_logical_instead_of_bitwise) 6776 << rex.get()->getSourceRange() 6777 << (Opc == BO_LAnd ? "&&" : "||"); 6778 // Suggest replacing the logical operator with the bitwise version 6779 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 6780 << (Opc == BO_LAnd ? "&" : "|") 6781 << FixItHint::CreateReplacement(SourceRange( 6782 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(), 6783 getLangOptions())), 6784 Opc == BO_LAnd ? "&" : "|"); 6785 if (Opc == BO_LAnd) 6786 // Suggest replacing "Foo() && kNonZero" with "Foo()" 6787 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 6788 << FixItHint::CreateRemoval( 6789 SourceRange( 6790 Lexer::getLocForEndOfToken(lex.get()->getLocEnd(), 6791 0, getSourceManager(), 6792 getLangOptions()), 6793 rex.get()->getLocEnd())); 6794 } 6795 } 6796 6797 if (!Context.getLangOptions().CPlusPlus) { 6798 lex = UsualUnaryConversions(lex.take()); 6799 if (lex.isInvalid()) 6800 return QualType(); 6801 6802 rex = UsualUnaryConversions(rex.take()); 6803 if (rex.isInvalid()) 6804 return QualType(); 6805 6806 if (!lex.get()->getType()->isScalarType() || 6807 !rex.get()->getType()->isScalarType()) 6808 return InvalidOperands(Loc, lex, rex); 6809 6810 return Context.IntTy; 6811 } 6812 6813 // The following is safe because we only use this method for 6814 // non-overloadable operands. 6815 6816 // C++ [expr.log.and]p1 6817 // C++ [expr.log.or]p1 6818 // The operands are both contextually converted to type bool. 6819 ExprResult lexRes = PerformContextuallyConvertToBool(lex.get()); 6820 if (lexRes.isInvalid()) 6821 return InvalidOperands(Loc, lex, rex); 6822 lex = move(lexRes); 6823 6824 ExprResult rexRes = PerformContextuallyConvertToBool(rex.get()); 6825 if (rexRes.isInvalid()) 6826 return InvalidOperands(Loc, lex, rex); 6827 rex = move(rexRes); 6828 6829 // C++ [expr.log.and]p2 6830 // C++ [expr.log.or]p2 6831 // The result is a bool. 6832 return Context.BoolTy; 6833} 6834 6835/// IsReadonlyProperty - Verify that otherwise a valid l-value expression 6836/// is a read-only property; return true if so. A readonly property expression 6837/// depends on various declarations and thus must be treated specially. 6838/// 6839static bool IsReadonlyProperty(Expr *E, Sema &S) { 6840 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) { 6841 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E); 6842 if (PropExpr->isImplicitProperty()) return false; 6843 6844 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty(); 6845 QualType BaseType = PropExpr->isSuperReceiver() ? 6846 PropExpr->getSuperReceiverType() : 6847 PropExpr->getBase()->getType(); 6848 6849 if (const ObjCObjectPointerType *OPT = 6850 BaseType->getAsObjCInterfacePointerType()) 6851 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl()) 6852 if (S.isPropertyReadonly(PDecl, IFace)) 6853 return true; 6854 } 6855 return false; 6856} 6857 6858static bool IsConstProperty(Expr *E, Sema &S) { 6859 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) { 6860 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E); 6861 if (PropExpr->isImplicitProperty()) return false; 6862 6863 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty(); 6864 QualType T = PDecl->getType(); 6865 if (T->isReferenceType()) 6866 T = T->getAs<ReferenceType>()->getPointeeType(); 6867 CanQualType CT = S.Context.getCanonicalType(T); 6868 return CT.isConstQualified(); 6869 } 6870 return false; 6871} 6872 6873static bool IsReadonlyMessage(Expr *E, Sema &S) { 6874 if (E->getStmtClass() != Expr::MemberExprClass) 6875 return false; 6876 const MemberExpr *ME = cast<MemberExpr>(E); 6877 NamedDecl *Member = ME->getMemberDecl(); 6878 if (isa<FieldDecl>(Member)) { 6879 Expr *Base = ME->getBase()->IgnoreParenImpCasts(); 6880 if (Base->getStmtClass() != Expr::ObjCMessageExprClass) 6881 return false; 6882 return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0; 6883 } 6884 return false; 6885} 6886 6887/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 6888/// emit an error and return true. If so, return false. 6889static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 6890 SourceLocation OrigLoc = Loc; 6891 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 6892 &Loc); 6893 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S)) 6894 IsLV = Expr::MLV_ReadonlyProperty; 6895 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S)) 6896 IsLV = Expr::MLV_Valid; 6897 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 6898 IsLV = Expr::MLV_InvalidMessageExpression; 6899 if (IsLV == Expr::MLV_Valid) 6900 return false; 6901 6902 unsigned Diag = 0; 6903 bool NeedType = false; 6904 switch (IsLV) { // C99 6.5.16p2 6905 case Expr::MLV_ConstQualified: 6906 Diag = diag::err_typecheck_assign_const; 6907 6908 // In ARC, use some specialized diagnostics for occasions where we 6909 // infer 'const'. These are always pseudo-strong variables. 6910 if (S.getLangOptions().ObjCAutoRefCount) { 6911 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 6912 if (declRef && isa<VarDecl>(declRef->getDecl())) { 6913 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 6914 6915 // Use the normal diagnostic if it's pseudo-__strong but the 6916 // user actually wrote 'const'. 6917 if (var->isARCPseudoStrong() && 6918 (!var->getTypeSourceInfo() || 6919 !var->getTypeSourceInfo()->getType().isConstQualified())) { 6920 // There are two pseudo-strong cases: 6921 // - self 6922 ObjCMethodDecl *method = S.getCurMethodDecl(); 6923 if (method && var == method->getSelfDecl()) 6924 Diag = diag::err_typecheck_arr_assign_self; 6925 6926 // - fast enumeration variables 6927 else 6928 Diag = diag::err_typecheck_arr_assign_enumeration; 6929 6930 SourceRange Assign; 6931 if (Loc != OrigLoc) 6932 Assign = SourceRange(OrigLoc, OrigLoc); 6933 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 6934 // We need to preserve the AST regardless, so migration tool 6935 // can do its job. 6936 return false; 6937 } 6938 } 6939 } 6940 6941 break; 6942 case Expr::MLV_ArrayType: 6943 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 6944 NeedType = true; 6945 break; 6946 case Expr::MLV_NotObjectType: 6947 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 6948 NeedType = true; 6949 break; 6950 case Expr::MLV_LValueCast: 6951 Diag = diag::err_typecheck_lvalue_casts_not_supported; 6952 break; 6953 case Expr::MLV_Valid: 6954 llvm_unreachable("did not take early return for MLV_Valid"); 6955 case Expr::MLV_InvalidExpression: 6956 case Expr::MLV_MemberFunction: 6957 case Expr::MLV_ClassTemporary: 6958 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 6959 break; 6960 case Expr::MLV_IncompleteType: 6961 case Expr::MLV_IncompleteVoidType: 6962 return S.RequireCompleteType(Loc, E->getType(), 6963 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue) 6964 << E->getSourceRange()); 6965 case Expr::MLV_DuplicateVectorComponents: 6966 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 6967 break; 6968 case Expr::MLV_NotBlockQualified: 6969 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 6970 break; 6971 case Expr::MLV_ReadonlyProperty: 6972 Diag = diag::error_readonly_property_assignment; 6973 break; 6974 case Expr::MLV_NoSetterProperty: 6975 Diag = diag::error_nosetter_property_assignment; 6976 break; 6977 case Expr::MLV_InvalidMessageExpression: 6978 Diag = diag::error_readonly_message_assignment; 6979 break; 6980 case Expr::MLV_SubObjCPropertySetting: 6981 Diag = diag::error_no_subobject_property_setting; 6982 break; 6983 } 6984 6985 SourceRange Assign; 6986 if (Loc != OrigLoc) 6987 Assign = SourceRange(OrigLoc, OrigLoc); 6988 if (NeedType) 6989 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 6990 else 6991 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 6992 return true; 6993} 6994 6995 6996 6997// C99 6.5.16.1 6998QualType Sema::CheckAssignmentOperands(Expr *LHS, ExprResult &RHS, 6999 SourceLocation Loc, 7000 QualType CompoundType) { 7001 // Verify that LHS is a modifiable lvalue, and emit error if not. 7002 if (CheckForModifiableLvalue(LHS, Loc, *this)) 7003 return QualType(); 7004 7005 QualType LHSType = LHS->getType(); 7006 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 7007 CompoundType; 7008 AssignConvertType ConvTy; 7009 if (CompoundType.isNull()) { 7010 QualType LHSTy(LHSType); 7011 // Simple assignment "x = y". 7012 if (LHS->getObjectKind() == OK_ObjCProperty) { 7013 ExprResult LHSResult = Owned(LHS); 7014 ConvertPropertyForLValue(LHSResult, RHS, LHSTy); 7015 if (LHSResult.isInvalid()) 7016 return QualType(); 7017 LHS = LHSResult.take(); 7018 } 7019 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 7020 if (RHS.isInvalid()) 7021 return QualType(); 7022 // Special case of NSObject attributes on c-style pointer types. 7023 if (ConvTy == IncompatiblePointer && 7024 ((Context.isObjCNSObjectType(LHSType) && 7025 RHSType->isObjCObjectPointerType()) || 7026 (Context.isObjCNSObjectType(RHSType) && 7027 LHSType->isObjCObjectPointerType()))) 7028 ConvTy = Compatible; 7029 7030 if (ConvTy == Compatible && 7031 getLangOptions().ObjCNonFragileABI && 7032 LHSType->isObjCObjectType()) 7033 Diag(Loc, diag::err_assignment_requires_nonfragile_object) 7034 << LHSType; 7035 7036 // If the RHS is a unary plus or minus, check to see if they = and + are 7037 // right next to each other. If so, the user may have typo'd "x =+ 4" 7038 // instead of "x += 4". 7039 Expr *RHSCheck = RHS.get(); 7040 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 7041 RHSCheck = ICE->getSubExpr(); 7042 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 7043 if ((UO->getOpcode() == UO_Plus || 7044 UO->getOpcode() == UO_Minus) && 7045 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 7046 // Only if the two operators are exactly adjacent. 7047 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() && 7048 // And there is a space or other character before the subexpr of the 7049 // unary +/-. We don't want to warn on "x=-1". 7050 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 7051 UO->getSubExpr()->getLocStart().isFileID()) { 7052 Diag(Loc, diag::warn_not_compound_assign) 7053 << (UO->getOpcode() == UO_Plus ? "+" : "-") 7054 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 7055 } 7056 } 7057 7058 if (ConvTy == Compatible) { 7059 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) 7060 checkRetainCycles(LHS, RHS.get()); 7061 else if (getLangOptions().ObjCAutoRefCount) 7062 checkUnsafeExprAssigns(Loc, LHS, RHS.get()); 7063 } 7064 } else { 7065 // Compound assignment "x += y" 7066 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 7067 } 7068 7069 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 7070 RHS.get(), AA_Assigning)) 7071 return QualType(); 7072 7073 CheckForNullPointerDereference(*this, LHS); 7074 7075 // C99 6.5.16p3: The type of an assignment expression is the type of the 7076 // left operand unless the left operand has qualified type, in which case 7077 // it is the unqualified version of the type of the left operand. 7078 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 7079 // is converted to the type of the assignment expression (above). 7080 // C++ 5.17p1: the type of the assignment expression is that of its left 7081 // operand. 7082 return (getLangOptions().CPlusPlus 7083 ? LHSType : LHSType.getUnqualifiedType()); 7084} 7085 7086// C99 6.5.17 7087static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 7088 SourceLocation Loc) { 7089 S.DiagnoseUnusedExprResult(LHS.get()); 7090 7091 LHS = S.CheckPlaceholderExpr(LHS.take()); 7092 RHS = S.CheckPlaceholderExpr(RHS.take()); 7093 if (LHS.isInvalid() || RHS.isInvalid()) 7094 return QualType(); 7095 7096 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 7097 // operands, but not unary promotions. 7098 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 7099 7100 // So we treat the LHS as a ignored value, and in C++ we allow the 7101 // containing site to determine what should be done with the RHS. 7102 LHS = S.IgnoredValueConversions(LHS.take()); 7103 if (LHS.isInvalid()) 7104 return QualType(); 7105 7106 if (!S.getLangOptions().CPlusPlus) { 7107 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take()); 7108 if (RHS.isInvalid()) 7109 return QualType(); 7110 if (!RHS.get()->getType()->isVoidType()) 7111 S.RequireCompleteType(Loc, RHS.get()->getType(), 7112 diag::err_incomplete_type); 7113 } 7114 7115 return RHS.get()->getType(); 7116} 7117 7118/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 7119/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 7120static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 7121 ExprValueKind &VK, 7122 SourceLocation OpLoc, 7123 bool isInc, bool isPrefix) { 7124 if (Op->isTypeDependent()) 7125 return S.Context.DependentTy; 7126 7127 QualType ResType = Op->getType(); 7128 assert(!ResType.isNull() && "no type for increment/decrement expression"); 7129 7130 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) { 7131 // Decrement of bool is not allowed. 7132 if (!isInc) { 7133 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 7134 return QualType(); 7135 } 7136 // Increment of bool sets it to true, but is deprecated. 7137 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 7138 } else if (ResType->isRealType()) { 7139 // OK! 7140 } else if (ResType->isAnyPointerType()) { 7141 // C99 6.5.2.4p2, 6.5.6p2 7142 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 7143 return QualType(); 7144 7145 // Diagnose bad cases where we step over interface counts. 7146 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op)) 7147 return QualType(); 7148 } else if (ResType->isAnyComplexType()) { 7149 // C99 does not support ++/-- on complex types, we allow as an extension. 7150 S.Diag(OpLoc, diag::ext_integer_increment_complex) 7151 << ResType << Op->getSourceRange(); 7152 } else if (ResType->isPlaceholderType()) { 7153 ExprResult PR = S.CheckPlaceholderExpr(Op); 7154 if (PR.isInvalid()) return QualType(); 7155 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc, 7156 isInc, isPrefix); 7157 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) { 7158 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 7159 } else { 7160 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 7161 << ResType << int(isInc) << Op->getSourceRange(); 7162 return QualType(); 7163 } 7164 // At this point, we know we have a real, complex or pointer type. 7165 // Now make sure the operand is a modifiable lvalue. 7166 if (CheckForModifiableLvalue(Op, OpLoc, S)) 7167 return QualType(); 7168 // In C++, a prefix increment is the same type as the operand. Otherwise 7169 // (in C or with postfix), the increment is the unqualified type of the 7170 // operand. 7171 if (isPrefix && S.getLangOptions().CPlusPlus) { 7172 VK = VK_LValue; 7173 return ResType; 7174 } else { 7175 VK = VK_RValue; 7176 return ResType.getUnqualifiedType(); 7177 } 7178} 7179 7180ExprResult Sema::ConvertPropertyForRValue(Expr *E) { 7181 assert(E->getValueKind() == VK_LValue && 7182 E->getObjectKind() == OK_ObjCProperty); 7183 const ObjCPropertyRefExpr *PRE = E->getObjCProperty(); 7184 7185 QualType T = E->getType(); 7186 QualType ReceiverType; 7187 if (PRE->isObjectReceiver()) 7188 ReceiverType = PRE->getBase()->getType(); 7189 else if (PRE->isSuperReceiver()) 7190 ReceiverType = PRE->getSuperReceiverType(); 7191 else 7192 ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver()); 7193 7194 ExprValueKind VK = VK_RValue; 7195 if (PRE->isImplicitProperty()) { 7196 if (ObjCMethodDecl *GetterMethod = 7197 PRE->getImplicitPropertyGetter()) { 7198 T = getMessageSendResultType(ReceiverType, GetterMethod, 7199 PRE->isClassReceiver(), 7200 PRE->isSuperReceiver()); 7201 VK = Expr::getValueKindForType(GetterMethod->getResultType()); 7202 } 7203 else { 7204 Diag(PRE->getLocation(), diag::err_getter_not_found) 7205 << PRE->getBase()->getType(); 7206 } 7207 } 7208 7209 E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty, 7210 E, 0, VK); 7211 7212 ExprResult Result = MaybeBindToTemporary(E); 7213 if (!Result.isInvalid()) 7214 E = Result.take(); 7215 7216 return Owned(E); 7217} 7218 7219void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, 7220 QualType &LHSTy) { 7221 assert(LHS.get()->getValueKind() == VK_LValue && 7222 LHS.get()->getObjectKind() == OK_ObjCProperty); 7223 const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty(); 7224 7225 bool Consumed = false; 7226 7227 if (PropRef->isImplicitProperty()) { 7228 // If using property-dot syntax notation for assignment, and there is a 7229 // setter, RHS expression is being passed to the setter argument. So, 7230 // type conversion (and comparison) is RHS to setter's argument type. 7231 if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) { 7232 ObjCMethodDecl::param_iterator P = SetterMD->param_begin(); 7233 LHSTy = (*P)->getType(); 7234 Consumed = (getLangOptions().ObjCAutoRefCount && 7235 (*P)->hasAttr<NSConsumedAttr>()); 7236 7237 // Otherwise, if the getter returns an l-value, just call that. 7238 } else { 7239 QualType Result = PropRef->getImplicitPropertyGetter()->getResultType(); 7240 ExprValueKind VK = Expr::getValueKindForType(Result); 7241 if (VK == VK_LValue) { 7242 LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(), 7243 CK_GetObjCProperty, LHS.take(), 0, VK); 7244 return; 7245 } 7246 } 7247 } else if (getLangOptions().ObjCAutoRefCount) { 7248 const ObjCMethodDecl *setter 7249 = PropRef->getExplicitProperty()->getSetterMethodDecl(); 7250 if (setter) { 7251 ObjCMethodDecl::param_iterator P = setter->param_begin(); 7252 LHSTy = (*P)->getType(); 7253 Consumed = (*P)->hasAttr<NSConsumedAttr>(); 7254 } 7255 } 7256 7257 if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) || 7258 getLangOptions().ObjCAutoRefCount) { 7259 InitializedEntity Entity = 7260 InitializedEntity::InitializeParameter(Context, LHSTy, Consumed); 7261 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS); 7262 if (!ArgE.isInvalid()) { 7263 RHS = ArgE; 7264 if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver()) 7265 checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get()); 7266 } 7267 } 7268} 7269 7270 7271/// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 7272/// This routine allows us to typecheck complex/recursive expressions 7273/// where the declaration is needed for type checking. We only need to 7274/// handle cases when the expression references a function designator 7275/// or is an lvalue. Here are some examples: 7276/// - &(x) => x 7277/// - &*****f => f for f a function designator. 7278/// - &s.xx => s 7279/// - &s.zz[1].yy -> s, if zz is an array 7280/// - *(x + 1) -> x, if x is an array 7281/// - &"123"[2] -> 0 7282/// - & __real__ x -> x 7283static ValueDecl *getPrimaryDecl(Expr *E) { 7284 switch (E->getStmtClass()) { 7285 case Stmt::DeclRefExprClass: 7286 return cast<DeclRefExpr>(E)->getDecl(); 7287 case Stmt::MemberExprClass: 7288 // If this is an arrow operator, the address is an offset from 7289 // the base's value, so the object the base refers to is 7290 // irrelevant. 7291 if (cast<MemberExpr>(E)->isArrow()) 7292 return 0; 7293 // Otherwise, the expression refers to a part of the base 7294 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 7295 case Stmt::ArraySubscriptExprClass: { 7296 // FIXME: This code shouldn't be necessary! We should catch the implicit 7297 // promotion of register arrays earlier. 7298 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 7299 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 7300 if (ICE->getSubExpr()->getType()->isArrayType()) 7301 return getPrimaryDecl(ICE->getSubExpr()); 7302 } 7303 return 0; 7304 } 7305 case Stmt::UnaryOperatorClass: { 7306 UnaryOperator *UO = cast<UnaryOperator>(E); 7307 7308 switch(UO->getOpcode()) { 7309 case UO_Real: 7310 case UO_Imag: 7311 case UO_Extension: 7312 return getPrimaryDecl(UO->getSubExpr()); 7313 default: 7314 return 0; 7315 } 7316 } 7317 case Stmt::ParenExprClass: 7318 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 7319 case Stmt::ImplicitCastExprClass: 7320 // If the result of an implicit cast is an l-value, we care about 7321 // the sub-expression; otherwise, the result here doesn't matter. 7322 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 7323 default: 7324 return 0; 7325 } 7326} 7327 7328/// \brief Diagnose invalid operand for address of operations. 7329/// 7330/// \param Type The type of operand which cannot have its address taken. 7331/// 0:bit-field 1:vector element 2:property expression 3:register variable 7332static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 7333 Expr *E, unsigned Type) { 7334 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 7335} 7336 7337/// CheckAddressOfOperand - The operand of & must be either a function 7338/// designator or an lvalue designating an object. If it is an lvalue, the 7339/// object cannot be declared with storage class register or be a bit field. 7340/// Note: The usual conversions are *not* applied to the operand of the & 7341/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 7342/// In C++, the operand might be an overloaded function name, in which case 7343/// we allow the '&' but retain the overloaded-function type. 7344static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp, 7345 SourceLocation OpLoc) { 7346 if (OrigOp->isTypeDependent()) 7347 return S.Context.DependentTy; 7348 if (OrigOp->getType() == S.Context.OverloadTy) 7349 return S.Context.OverloadTy; 7350 if (OrigOp->getType() == S.Context.UnknownAnyTy) 7351 return S.Context.UnknownAnyTy; 7352 if (OrigOp->getType() == S.Context.BoundMemberTy) { 7353 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 7354 << OrigOp->getSourceRange(); 7355 return QualType(); 7356 } 7357 7358 assert(!OrigOp->getType()->isPlaceholderType()); 7359 7360 // Make sure to ignore parentheses in subsequent checks 7361 Expr *op = OrigOp->IgnoreParens(); 7362 7363 if (S.getLangOptions().C99) { 7364 // Implement C99-only parts of addressof rules. 7365 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 7366 if (uOp->getOpcode() == UO_Deref) 7367 // Per C99 6.5.3.2, the address of a deref always returns a valid result 7368 // (assuming the deref expression is valid). 7369 return uOp->getSubExpr()->getType(); 7370 } 7371 // Technically, there should be a check for array subscript 7372 // expressions here, but the result of one is always an lvalue anyway. 7373 } 7374 ValueDecl *dcl = getPrimaryDecl(op); 7375 Expr::LValueClassification lval = op->ClassifyLValue(S.Context); 7376 7377 if (lval == Expr::LV_ClassTemporary) { 7378 bool sfinae = S.isSFINAEContext(); 7379 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary 7380 : diag::ext_typecheck_addrof_class_temporary) 7381 << op->getType() << op->getSourceRange(); 7382 if (sfinae) 7383 return QualType(); 7384 } else if (isa<ObjCSelectorExpr>(op)) { 7385 return S.Context.getPointerType(op->getType()); 7386 } else if (lval == Expr::LV_MemberFunction) { 7387 // If it's an instance method, make a member pointer. 7388 // The expression must have exactly the form &A::foo. 7389 7390 // If the underlying expression isn't a decl ref, give up. 7391 if (!isa<DeclRefExpr>(op)) { 7392 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 7393 << OrigOp->getSourceRange(); 7394 return QualType(); 7395 } 7396 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 7397 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 7398 7399 // The id-expression was parenthesized. 7400 if (OrigOp != DRE) { 7401 S.Diag(OpLoc, diag::err_parens_pointer_member_function) 7402 << OrigOp->getSourceRange(); 7403 7404 // The method was named without a qualifier. 7405 } else if (!DRE->getQualifier()) { 7406 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function) 7407 << op->getSourceRange(); 7408 } 7409 7410 return S.Context.getMemberPointerType(op->getType(), 7411 S.Context.getTypeDeclType(MD->getParent()).getTypePtr()); 7412 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 7413 // C99 6.5.3.2p1 7414 // The operand must be either an l-value or a function designator 7415 if (!op->getType()->isFunctionType()) { 7416 // FIXME: emit more specific diag... 7417 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 7418 << op->getSourceRange(); 7419 return QualType(); 7420 } 7421 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 7422 // The operand cannot be a bit-field 7423 diagnoseAddressOfInvalidType(S, OpLoc, op, /*bit-field*/ 0); 7424 return QualType(); 7425 } else if (op->getObjectKind() == OK_VectorComponent) { 7426 // The operand cannot be an element of a vector 7427 diagnoseAddressOfInvalidType(S, OpLoc, op, /*vector element*/ 1); 7428 return QualType(); 7429 } else if (op->getObjectKind() == OK_ObjCProperty) { 7430 // cannot take address of a property expression. 7431 diagnoseAddressOfInvalidType(S, OpLoc, op, /*property expression*/ 2); 7432 return QualType(); 7433 } else if (dcl) { // C99 6.5.3.2p1 7434 // We have an lvalue with a decl. Make sure the decl is not declared 7435 // with the register storage-class specifier. 7436 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 7437 // in C++ it is not error to take address of a register 7438 // variable (c++03 7.1.1P3) 7439 if (vd->getStorageClass() == SC_Register && 7440 !S.getLangOptions().CPlusPlus) { 7441 diagnoseAddressOfInvalidType(S, OpLoc, op, /*register variable*/ 3); 7442 return QualType(); 7443 } 7444 } else if (isa<FunctionTemplateDecl>(dcl)) { 7445 return S.Context.OverloadTy; 7446 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 7447 // Okay: we can take the address of a field. 7448 // Could be a pointer to member, though, if there is an explicit 7449 // scope qualifier for the class. 7450 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 7451 DeclContext *Ctx = dcl->getDeclContext(); 7452 if (Ctx && Ctx->isRecord()) { 7453 if (dcl->getType()->isReferenceType()) { 7454 S.Diag(OpLoc, 7455 diag::err_cannot_form_pointer_to_member_of_reference_type) 7456 << dcl->getDeclName() << dcl->getType(); 7457 return QualType(); 7458 } 7459 7460 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 7461 Ctx = Ctx->getParent(); 7462 return S.Context.getMemberPointerType(op->getType(), 7463 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 7464 } 7465 } 7466 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 7467 assert(0 && "Unknown/unexpected decl type"); 7468 } 7469 7470 if (lval == Expr::LV_IncompleteVoidType) { 7471 // Taking the address of a void variable is technically illegal, but we 7472 // allow it in cases which are otherwise valid. 7473 // Example: "extern void x; void* y = &x;". 7474 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 7475 } 7476 7477 // If the operand has type "type", the result has type "pointer to type". 7478 if (op->getType()->isObjCObjectType()) 7479 return S.Context.getObjCObjectPointerType(op->getType()); 7480 return S.Context.getPointerType(op->getType()); 7481} 7482 7483/// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 7484static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 7485 SourceLocation OpLoc) { 7486 if (Op->isTypeDependent()) 7487 return S.Context.DependentTy; 7488 7489 ExprResult ConvResult = S.UsualUnaryConversions(Op); 7490 if (ConvResult.isInvalid()) 7491 return QualType(); 7492 Op = ConvResult.take(); 7493 QualType OpTy = Op->getType(); 7494 QualType Result; 7495 7496 if (isa<CXXReinterpretCastExpr>(Op)) { 7497 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 7498 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 7499 Op->getSourceRange()); 7500 } 7501 7502 // Note that per both C89 and C99, indirection is always legal, even if OpTy 7503 // is an incomplete type or void. It would be possible to warn about 7504 // dereferencing a void pointer, but it's completely well-defined, and such a 7505 // warning is unlikely to catch any mistakes. 7506 if (const PointerType *PT = OpTy->getAs<PointerType>()) 7507 Result = PT->getPointeeType(); 7508 else if (const ObjCObjectPointerType *OPT = 7509 OpTy->getAs<ObjCObjectPointerType>()) 7510 Result = OPT->getPointeeType(); 7511 else { 7512 ExprResult PR = S.CheckPlaceholderExpr(Op); 7513 if (PR.isInvalid()) return QualType(); 7514 if (PR.take() != Op) 7515 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc); 7516 } 7517 7518 if (Result.isNull()) { 7519 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 7520 << OpTy << Op->getSourceRange(); 7521 return QualType(); 7522 } 7523 7524 // Dereferences are usually l-values... 7525 VK = VK_LValue; 7526 7527 // ...except that certain expressions are never l-values in C. 7528 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType()) 7529 VK = VK_RValue; 7530 7531 return Result; 7532} 7533 7534static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode( 7535 tok::TokenKind Kind) { 7536 BinaryOperatorKind Opc; 7537 switch (Kind) { 7538 default: assert(0 && "Unknown binop!"); 7539 case tok::periodstar: Opc = BO_PtrMemD; break; 7540 case tok::arrowstar: Opc = BO_PtrMemI; break; 7541 case tok::star: Opc = BO_Mul; break; 7542 case tok::slash: Opc = BO_Div; break; 7543 case tok::percent: Opc = BO_Rem; break; 7544 case tok::plus: Opc = BO_Add; break; 7545 case tok::minus: Opc = BO_Sub; break; 7546 case tok::lessless: Opc = BO_Shl; break; 7547 case tok::greatergreater: Opc = BO_Shr; break; 7548 case tok::lessequal: Opc = BO_LE; break; 7549 case tok::less: Opc = BO_LT; break; 7550 case tok::greaterequal: Opc = BO_GE; break; 7551 case tok::greater: Opc = BO_GT; break; 7552 case tok::exclaimequal: Opc = BO_NE; break; 7553 case tok::equalequal: Opc = BO_EQ; break; 7554 case tok::amp: Opc = BO_And; break; 7555 case tok::caret: Opc = BO_Xor; break; 7556 case tok::pipe: Opc = BO_Or; break; 7557 case tok::ampamp: Opc = BO_LAnd; break; 7558 case tok::pipepipe: Opc = BO_LOr; break; 7559 case tok::equal: Opc = BO_Assign; break; 7560 case tok::starequal: Opc = BO_MulAssign; break; 7561 case tok::slashequal: Opc = BO_DivAssign; break; 7562 case tok::percentequal: Opc = BO_RemAssign; break; 7563 case tok::plusequal: Opc = BO_AddAssign; break; 7564 case tok::minusequal: Opc = BO_SubAssign; break; 7565 case tok::lesslessequal: Opc = BO_ShlAssign; break; 7566 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 7567 case tok::ampequal: Opc = BO_AndAssign; break; 7568 case tok::caretequal: Opc = BO_XorAssign; break; 7569 case tok::pipeequal: Opc = BO_OrAssign; break; 7570 case tok::comma: Opc = BO_Comma; break; 7571 } 7572 return Opc; 7573} 7574 7575static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 7576 tok::TokenKind Kind) { 7577 UnaryOperatorKind Opc; 7578 switch (Kind) { 7579 default: assert(0 && "Unknown unary op!"); 7580 case tok::plusplus: Opc = UO_PreInc; break; 7581 case tok::minusminus: Opc = UO_PreDec; break; 7582 case tok::amp: Opc = UO_AddrOf; break; 7583 case tok::star: Opc = UO_Deref; break; 7584 case tok::plus: Opc = UO_Plus; break; 7585 case tok::minus: Opc = UO_Minus; break; 7586 case tok::tilde: Opc = UO_Not; break; 7587 case tok::exclaim: Opc = UO_LNot; break; 7588 case tok::kw___real: Opc = UO_Real; break; 7589 case tok::kw___imag: Opc = UO_Imag; break; 7590 case tok::kw___extension__: Opc = UO_Extension; break; 7591 } 7592 return Opc; 7593} 7594 7595/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 7596/// This warning is only emitted for builtin assignment operations. It is also 7597/// suppressed in the event of macro expansions. 7598static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs, 7599 SourceLocation OpLoc) { 7600 if (!S.ActiveTemplateInstantiations.empty()) 7601 return; 7602 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 7603 return; 7604 lhs = lhs->IgnoreParenImpCasts(); 7605 rhs = rhs->IgnoreParenImpCasts(); 7606 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs); 7607 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs); 7608 if (!LeftDeclRef || !RightDeclRef || 7609 LeftDeclRef->getLocation().isMacroID() || 7610 RightDeclRef->getLocation().isMacroID()) 7611 return; 7612 const ValueDecl *LeftDecl = 7613 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl()); 7614 const ValueDecl *RightDecl = 7615 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl()); 7616 if (LeftDecl != RightDecl) 7617 return; 7618 if (LeftDecl->getType().isVolatileQualified()) 7619 return; 7620 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>()) 7621 if (RefTy->getPointeeType().isVolatileQualified()) 7622 return; 7623 7624 S.Diag(OpLoc, diag::warn_self_assignment) 7625 << LeftDeclRef->getType() 7626 << lhs->getSourceRange() << rhs->getSourceRange(); 7627} 7628 7629// checkArithmeticNull - Detect when a NULL constant is used improperly in an 7630// expression. These are mainly cases where the null pointer is used as an 7631// integer instead of a pointer. 7632static void checkArithmeticNull(Sema &S, ExprResult &lex, ExprResult &rex, 7633 SourceLocation Loc, bool isCompare) { 7634 // The canonical way to check for a GNU null is with isNullPointerConstant, 7635 // but we use a bit of a hack here for speed; this is a relatively 7636 // hot path, and isNullPointerConstant is slow. 7637 bool LeftNull = isa<GNUNullExpr>(lex.get()->IgnoreParenImpCasts()); 7638 bool RightNull = isa<GNUNullExpr>(rex.get()->IgnoreParenImpCasts()); 7639 7640 // Detect when a NULL constant is used improperly in an expression. These 7641 // are mainly cases where the null pointer is used as an integer instead 7642 // of a pointer. 7643 if (!LeftNull && !RightNull) 7644 return; 7645 7646 QualType LeftType = lex.get()->getType(); 7647 QualType RightType = rex.get()->getType(); 7648 7649 // Avoid analyzing cases where the result will either be invalid (and 7650 // diagnosed as such) or entirely valid and not something to warn about. 7651 if (LeftType->isBlockPointerType() || LeftType->isMemberPointerType() || 7652 LeftType->isFunctionType() || RightType->isBlockPointerType() || 7653 RightType->isMemberPointerType() || RightType->isFunctionType()) 7654 return; 7655 7656 // Comparison operations would not make sense with a null pointer no matter 7657 // what the other expression is. 7658 if (!isCompare) { 7659 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 7660 << (LeftNull ? lex.get()->getSourceRange() : SourceRange()) 7661 << (RightNull ? rex.get()->getSourceRange() : SourceRange()); 7662 return; 7663 } 7664 7665 // The rest of the operations only make sense with a null pointer 7666 // if the other expression is a pointer. 7667 if (LeftNull == RightNull || LeftType->isAnyPointerType() || 7668 LeftType->canDecayToPointerType() || RightType->isAnyPointerType() || 7669 RightType->canDecayToPointerType()) 7670 return; 7671 7672 S.Diag(Loc, diag::warn_null_in_comparison_operation) 7673 << LeftNull /* LHS is NULL */ 7674 << (LeftNull ? rex.get()->getType() : lex.get()->getType()) 7675 << lex.get()->getSourceRange() << rex.get()->getSourceRange(); 7676} 7677/// CreateBuiltinBinOp - Creates a new built-in binary operation with 7678/// operator @p Opc at location @c TokLoc. This routine only supports 7679/// built-in operations; ActOnBinOp handles overloaded operators. 7680ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 7681 BinaryOperatorKind Opc, 7682 Expr *lhsExpr, Expr *rhsExpr) { 7683 ExprResult lhs = Owned(lhsExpr), rhs = Owned(rhsExpr); 7684 QualType ResultTy; // Result type of the binary operator. 7685 // The following two variables are used for compound assignment operators 7686 QualType CompLHSTy; // Type of LHS after promotions for computation 7687 QualType CompResultTy; // Type of computation result 7688 ExprValueKind VK = VK_RValue; 7689 ExprObjectKind OK = OK_Ordinary; 7690 7691 // Check if a 'foo<int>' involved in a binary op, identifies a single 7692 // function unambiguously (i.e. an lvalue ala 13.4) 7693 // But since an assignment can trigger target based overload, exclude it in 7694 // our blind search. i.e: 7695 // template<class T> void f(); template<class T, class U> void f(U); 7696 // f<int> == 0; // resolve f<int> blindly 7697 // void (*p)(int); p = f<int>; // resolve f<int> using target 7698 if (Opc != BO_Assign) { 7699 ExprResult resolvedLHS = CheckPlaceholderExpr(lhs.get()); 7700 if (!resolvedLHS.isUsable()) return ExprError(); 7701 lhs = move(resolvedLHS); 7702 7703 ExprResult resolvedRHS = CheckPlaceholderExpr(rhs.get()); 7704 if (!resolvedRHS.isUsable()) return ExprError(); 7705 rhs = move(resolvedRHS); 7706 } 7707 7708 if (Opc == BO_Mul || Opc == BO_Div || Opc == BO_Rem || Opc == BO_Add || 7709 Opc == BO_Sub || Opc == BO_Shl || Opc == BO_Shr || Opc == BO_And || 7710 Opc == BO_Xor || Opc == BO_Or || Opc == BO_MulAssign || 7711 Opc == BO_DivAssign || Opc == BO_AddAssign || Opc == BO_SubAssign || 7712 Opc == BO_RemAssign || Opc == BO_ShlAssign || Opc == BO_ShrAssign || 7713 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign) 7714 checkArithmeticNull(*this, lhs, rhs, OpLoc, /*isCompare=*/false); 7715 else if (Opc == BO_LE || Opc == BO_LT || Opc == BO_GE || Opc == BO_GT || 7716 Opc == BO_EQ || Opc == BO_NE) 7717 checkArithmeticNull(*this, lhs, rhs, OpLoc, /*isCompare=*/true); 7718 7719 switch (Opc) { 7720 case BO_Assign: 7721 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, QualType()); 7722 if (getLangOptions().CPlusPlus && 7723 lhs.get()->getObjectKind() != OK_ObjCProperty) { 7724 VK = lhs.get()->getValueKind(); 7725 OK = lhs.get()->getObjectKind(); 7726 } 7727 if (!ResultTy.isNull()) 7728 DiagnoseSelfAssignment(*this, lhs.get(), rhs.get(), OpLoc); 7729 break; 7730 case BO_PtrMemD: 7731 case BO_PtrMemI: 7732 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc, 7733 Opc == BO_PtrMemI); 7734 break; 7735 case BO_Mul: 7736 case BO_Div: 7737 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false, 7738 Opc == BO_Div); 7739 break; 7740 case BO_Rem: 7741 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc); 7742 break; 7743 case BO_Add: 7744 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc); 7745 break; 7746 case BO_Sub: 7747 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc); 7748 break; 7749 case BO_Shl: 7750 case BO_Shr: 7751 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc); 7752 break; 7753 case BO_LE: 7754 case BO_LT: 7755 case BO_GE: 7756 case BO_GT: 7757 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true); 7758 break; 7759 case BO_EQ: 7760 case BO_NE: 7761 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false); 7762 break; 7763 case BO_And: 7764 case BO_Xor: 7765 case BO_Or: 7766 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc); 7767 break; 7768 case BO_LAnd: 7769 case BO_LOr: 7770 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc); 7771 break; 7772 case BO_MulAssign: 7773 case BO_DivAssign: 7774 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true, 7775 Opc == BO_DivAssign); 7776 CompLHSTy = CompResultTy; 7777 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid()) 7778 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy); 7779 break; 7780 case BO_RemAssign: 7781 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true); 7782 CompLHSTy = CompResultTy; 7783 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid()) 7784 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy); 7785 break; 7786 case BO_AddAssign: 7787 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy); 7788 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid()) 7789 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy); 7790 break; 7791 case BO_SubAssign: 7792 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy); 7793 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid()) 7794 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy); 7795 break; 7796 case BO_ShlAssign: 7797 case BO_ShrAssign: 7798 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, Opc, true); 7799 CompLHSTy = CompResultTy; 7800 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid()) 7801 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy); 7802 break; 7803 case BO_AndAssign: 7804 case BO_XorAssign: 7805 case BO_OrAssign: 7806 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true); 7807 CompLHSTy = CompResultTy; 7808 if (!CompResultTy.isNull() && !lhs.isInvalid() && !rhs.isInvalid()) 7809 ResultTy = CheckAssignmentOperands(lhs.get(), rhs, OpLoc, CompResultTy); 7810 break; 7811 case BO_Comma: 7812 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc); 7813 if (getLangOptions().CPlusPlus && !rhs.isInvalid()) { 7814 VK = rhs.get()->getValueKind(); 7815 OK = rhs.get()->getObjectKind(); 7816 } 7817 break; 7818 } 7819 if (ResultTy.isNull() || lhs.isInvalid() || rhs.isInvalid()) 7820 return ExprError(); 7821 7822 // Check for array bounds violations for both sides of the BinaryOperator 7823 CheckArrayAccess(lhs.get()); 7824 CheckArrayAccess(rhs.get()); 7825 7826 if (CompResultTy.isNull()) 7827 return Owned(new (Context) BinaryOperator(lhs.take(), rhs.take(), Opc, 7828 ResultTy, VK, OK, OpLoc)); 7829 if (getLangOptions().CPlusPlus && lhs.get()->getObjectKind() != 7830 OK_ObjCProperty) { 7831 VK = VK_LValue; 7832 OK = lhs.get()->getObjectKind(); 7833 } 7834 return Owned(new (Context) CompoundAssignOperator(lhs.take(), rhs.take(), Opc, 7835 ResultTy, VK, OK, CompLHSTy, 7836 CompResultTy, OpLoc)); 7837} 7838 7839/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 7840/// operators are mixed in a way that suggests that the programmer forgot that 7841/// comparison operators have higher precedence. The most typical example of 7842/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 7843static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 7844 SourceLocation OpLoc,Expr *lhs,Expr *rhs){ 7845 typedef BinaryOperator BinOp; 7846 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1), 7847 rhsopc = static_cast<BinOp::Opcode>(-1); 7848 if (BinOp *BO = dyn_cast<BinOp>(lhs)) 7849 lhsopc = BO->getOpcode(); 7850 if (BinOp *BO = dyn_cast<BinOp>(rhs)) 7851 rhsopc = BO->getOpcode(); 7852 7853 // Subs are not binary operators. 7854 if (lhsopc == -1 && rhsopc == -1) 7855 return; 7856 7857 // Bitwise operations are sometimes used as eager logical ops. 7858 // Don't diagnose this. 7859 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) && 7860 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc))) 7861 return; 7862 7863 bool isLeftComp = BinOp::isComparisonOp(lhsopc); 7864 bool isRightComp = BinOp::isComparisonOp(rhsopc); 7865 if (!isLeftComp && !isRightComp) return; 7866 7867 SourceRange DiagRange = isLeftComp ? SourceRange(lhs->getLocStart(), OpLoc) 7868 : SourceRange(OpLoc, rhs->getLocEnd()); 7869 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(lhsopc) 7870 : BinOp::getOpcodeStr(rhsopc); 7871 SourceRange ParensRange = isLeftComp ? 7872 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), 7873 rhs->getLocEnd()) 7874 : SourceRange(lhs->getLocStart(), 7875 cast<BinOp>(rhs)->getLHS()->getLocStart()); 7876 7877 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 7878 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr; 7879 SuggestParentheses(Self, OpLoc, 7880 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr, 7881 rhs->getSourceRange()); 7882 SuggestParentheses(Self, OpLoc, 7883 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc), 7884 ParensRange); 7885} 7886 7887/// \brief It accepts a '&' expr that is inside a '|' one. 7888/// Emit a diagnostic together with a fixit hint that wraps the '&' expression 7889/// in parentheses. 7890static void 7891EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 7892 BinaryOperator *Bop) { 7893 assert(Bop->getOpcode() == BO_And); 7894 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 7895 << Bop->getSourceRange() << OpLoc; 7896 SuggestParentheses(Self, Bop->getOperatorLoc(), 7897 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence), 7898 Bop->getSourceRange()); 7899} 7900 7901/// \brief It accepts a '&&' expr that is inside a '||' one. 7902/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 7903/// in parentheses. 7904static void 7905EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 7906 BinaryOperator *Bop) { 7907 assert(Bop->getOpcode() == BO_LAnd); 7908 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 7909 << Bop->getSourceRange() << OpLoc; 7910 SuggestParentheses(Self, Bop->getOperatorLoc(), 7911 Self.PDiag(diag::note_logical_and_in_logical_or_silence), 7912 Bop->getSourceRange()); 7913} 7914 7915/// \brief Returns true if the given expression can be evaluated as a constant 7916/// 'true'. 7917static bool EvaluatesAsTrue(Sema &S, Expr *E) { 7918 bool Res; 7919 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 7920} 7921 7922/// \brief Returns true if the given expression can be evaluated as a constant 7923/// 'false'. 7924static bool EvaluatesAsFalse(Sema &S, Expr *E) { 7925 bool Res; 7926 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 7927} 7928 7929/// \brief Look for '&&' in the left hand of a '||' expr. 7930static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 7931 Expr *OrLHS, Expr *OrRHS) { 7932 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) { 7933 if (Bop->getOpcode() == BO_LAnd) { 7934 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 7935 if (EvaluatesAsFalse(S, OrRHS)) 7936 return; 7937 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 7938 if (!EvaluatesAsTrue(S, Bop->getLHS())) 7939 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 7940 } else if (Bop->getOpcode() == BO_LOr) { 7941 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 7942 // If it's "a || b && 1 || c" we didn't warn earlier for 7943 // "a || b && 1", but warn now. 7944 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 7945 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 7946 } 7947 } 7948 } 7949} 7950 7951/// \brief Look for '&&' in the right hand of a '||' expr. 7952static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 7953 Expr *OrLHS, Expr *OrRHS) { 7954 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) { 7955 if (Bop->getOpcode() == BO_LAnd) { 7956 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 7957 if (EvaluatesAsFalse(S, OrLHS)) 7958 return; 7959 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 7960 if (!EvaluatesAsTrue(S, Bop->getRHS())) 7961 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 7962 } 7963 } 7964} 7965 7966/// \brief Look for '&' in the left or right hand of a '|' expr. 7967static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 7968 Expr *OrArg) { 7969 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 7970 if (Bop->getOpcode() == BO_And) 7971 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 7972 } 7973} 7974 7975/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 7976/// precedence. 7977static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 7978 SourceLocation OpLoc, Expr *lhs, Expr *rhs){ 7979 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 7980 if (BinaryOperator::isBitwiseOp(Opc)) 7981 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs); 7982 7983 // Diagnose "arg1 & arg2 | arg3" 7984 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 7985 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, lhs); 7986 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, rhs); 7987 } 7988 7989 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 7990 // We don't warn for 'assert(a || b && "bad")' since this is safe. 7991 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 7992 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs); 7993 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs); 7994 } 7995} 7996 7997// Binary Operators. 'Tok' is the token for the operator. 7998ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 7999 tok::TokenKind Kind, 8000 Expr *lhs, Expr *rhs) { 8001 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 8002 assert((lhs != 0) && "ActOnBinOp(): missing left expression"); 8003 assert((rhs != 0) && "ActOnBinOp(): missing right expression"); 8004 8005 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 8006 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs); 8007 8008 return BuildBinOp(S, TokLoc, Opc, lhs, rhs); 8009} 8010 8011ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 8012 BinaryOperatorKind Opc, 8013 Expr *lhs, Expr *rhs) { 8014 if (getLangOptions().CPlusPlus) { 8015 bool UseBuiltinOperator; 8016 8017 if (lhs->isTypeDependent() || rhs->isTypeDependent()) { 8018 UseBuiltinOperator = false; 8019 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) { 8020 UseBuiltinOperator = true; 8021 } else { 8022 UseBuiltinOperator = !lhs->getType()->isOverloadableType() && 8023 !rhs->getType()->isOverloadableType(); 8024 } 8025 8026 if (!UseBuiltinOperator) { 8027 // Find all of the overloaded operators visible from this 8028 // point. We perform both an operator-name lookup from the local 8029 // scope and an argument-dependent lookup based on the types of 8030 // the arguments. 8031 UnresolvedSet<16> Functions; 8032 OverloadedOperatorKind OverOp 8033 = BinaryOperator::getOverloadedOperator(Opc); 8034 if (S && OverOp != OO_None) 8035 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(), 8036 Functions); 8037 8038 // Build the (potentially-overloaded, potentially-dependent) 8039 // binary operation. 8040 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs); 8041 } 8042 } 8043 8044 // Build a built-in binary operation. 8045 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs); 8046} 8047 8048ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 8049 UnaryOperatorKind Opc, 8050 Expr *InputExpr) { 8051 ExprResult Input = Owned(InputExpr); 8052 ExprValueKind VK = VK_RValue; 8053 ExprObjectKind OK = OK_Ordinary; 8054 QualType resultType; 8055 switch (Opc) { 8056 case UO_PreInc: 8057 case UO_PreDec: 8058 case UO_PostInc: 8059 case UO_PostDec: 8060 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc, 8061 Opc == UO_PreInc || 8062 Opc == UO_PostInc, 8063 Opc == UO_PreInc || 8064 Opc == UO_PreDec); 8065 break; 8066 case UO_AddrOf: 8067 resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc); 8068 break; 8069 case UO_Deref: { 8070 ExprResult resolved = CheckPlaceholderExpr(Input.get()); 8071 if (!resolved.isUsable()) return ExprError(); 8072 Input = move(resolved); 8073 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 8074 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 8075 break; 8076 } 8077 case UO_Plus: 8078 case UO_Minus: 8079 Input = UsualUnaryConversions(Input.take()); 8080 if (Input.isInvalid()) return ExprError(); 8081 resultType = Input.get()->getType(); 8082 if (resultType->isDependentType()) 8083 break; 8084 if (resultType->isArithmeticType() || // C99 6.5.3.3p1 8085 resultType->isVectorType()) 8086 break; 8087 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7 8088 resultType->isEnumeralType()) 8089 break; 8090 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6 8091 Opc == UO_Plus && 8092 resultType->isPointerType()) 8093 break; 8094 else if (resultType->isPlaceholderType()) { 8095 Input = CheckPlaceholderExpr(Input.take()); 8096 if (Input.isInvalid()) return ExprError(); 8097 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take()); 8098 } 8099 8100 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 8101 << resultType << Input.get()->getSourceRange()); 8102 8103 case UO_Not: // bitwise complement 8104 Input = UsualUnaryConversions(Input.take()); 8105 if (Input.isInvalid()) return ExprError(); 8106 resultType = Input.get()->getType(); 8107 if (resultType->isDependentType()) 8108 break; 8109 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 8110 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 8111 // C99 does not support '~' for complex conjugation. 8112 Diag(OpLoc, diag::ext_integer_complement_complex) 8113 << resultType << Input.get()->getSourceRange(); 8114 else if (resultType->hasIntegerRepresentation()) 8115 break; 8116 else if (resultType->isPlaceholderType()) { 8117 Input = CheckPlaceholderExpr(Input.take()); 8118 if (Input.isInvalid()) return ExprError(); 8119 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take()); 8120 } else { 8121 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 8122 << resultType << Input.get()->getSourceRange()); 8123 } 8124 break; 8125 8126 case UO_LNot: // logical negation 8127 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 8128 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 8129 if (Input.isInvalid()) return ExprError(); 8130 resultType = Input.get()->getType(); 8131 if (resultType->isDependentType()) 8132 break; 8133 if (resultType->isScalarType()) { 8134 // C99 6.5.3.3p1: ok, fallthrough; 8135 if (Context.getLangOptions().CPlusPlus) { 8136 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 8137 // operand contextually converted to bool. 8138 Input = ImpCastExprToType(Input.take(), Context.BoolTy, 8139 ScalarTypeToBooleanCastKind(resultType)); 8140 } 8141 } else if (resultType->isPlaceholderType()) { 8142 Input = CheckPlaceholderExpr(Input.take()); 8143 if (Input.isInvalid()) return ExprError(); 8144 return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take()); 8145 } else { 8146 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 8147 << resultType << Input.get()->getSourceRange()); 8148 } 8149 8150 // LNot always has type int. C99 6.5.3.3p5. 8151 // In C++, it's bool. C++ 5.3.1p8 8152 resultType = Context.getLogicalOperationType(); 8153 break; 8154 case UO_Real: 8155 case UO_Imag: 8156 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 8157 // _Real and _Imag map ordinary l-values into ordinary l-values. 8158 if (Input.isInvalid()) return ExprError(); 8159 if (Input.get()->getValueKind() != VK_RValue && 8160 Input.get()->getObjectKind() == OK_Ordinary) 8161 VK = Input.get()->getValueKind(); 8162 break; 8163 case UO_Extension: 8164 resultType = Input.get()->getType(); 8165 VK = Input.get()->getValueKind(); 8166 OK = Input.get()->getObjectKind(); 8167 break; 8168 } 8169 if (resultType.isNull() || Input.isInvalid()) 8170 return ExprError(); 8171 8172 // Check for array bounds violations in the operand of the UnaryOperator, 8173 // except for the '*' and '&' operators that have to be handled specially 8174 // by CheckArrayAccess (as there are special cases like &array[arraysize] 8175 // that are explicitly defined as valid by the standard). 8176 if (Opc != UO_AddrOf && Opc != UO_Deref) 8177 CheckArrayAccess(Input.get()); 8178 8179 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType, 8180 VK, OK, OpLoc)); 8181} 8182 8183ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 8184 UnaryOperatorKind Opc, 8185 Expr *Input) { 8186 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() && 8187 UnaryOperator::getOverloadedOperator(Opc) != OO_None) { 8188 // Find all of the overloaded operators visible from this 8189 // point. We perform both an operator-name lookup from the local 8190 // scope and an argument-dependent lookup based on the types of 8191 // the arguments. 8192 UnresolvedSet<16> Functions; 8193 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 8194 if (S && OverOp != OO_None) 8195 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 8196 Functions); 8197 8198 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 8199 } 8200 8201 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 8202} 8203 8204// Unary Operators. 'Tok' is the token for the operator. 8205ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 8206 tok::TokenKind Op, Expr *Input) { 8207 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 8208} 8209 8210/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 8211ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 8212 LabelDecl *TheDecl) { 8213 TheDecl->setUsed(); 8214 // Create the AST node. The address of a label always has type 'void*'. 8215 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 8216 Context.getPointerType(Context.VoidTy))); 8217} 8218 8219/// Given the last statement in a statement-expression, check whether 8220/// the result is a producing expression (like a call to an 8221/// ns_returns_retained function) and, if so, rebuild it to hoist the 8222/// release out of the full-expression. Otherwise, return null. 8223/// Cannot fail. 8224static Expr *maybeRebuildARCConsumingStmt(Stmt *s) { 8225 // Should always be wrapped with one of these. 8226 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(s); 8227 if (!cleanups) return 0; 8228 8229 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 8230 if (!cast || cast->getCastKind() != CK_ObjCConsumeObject) 8231 return 0; 8232 8233 // Splice out the cast. This shouldn't modify any interesting 8234 // features of the statement. 8235 Expr *producer = cast->getSubExpr(); 8236 assert(producer->getType() == cast->getType()); 8237 assert(producer->getValueKind() == cast->getValueKind()); 8238 cleanups->setSubExpr(producer); 8239 return cleanups; 8240} 8241 8242ExprResult 8243Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 8244 SourceLocation RPLoc) { // "({..})" 8245 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 8246 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 8247 8248 bool isFileScope 8249 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0); 8250 if (isFileScope) 8251 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 8252 8253 // FIXME: there are a variety of strange constraints to enforce here, for 8254 // example, it is not possible to goto into a stmt expression apparently. 8255 // More semantic analysis is needed. 8256 8257 // If there are sub stmts in the compound stmt, take the type of the last one 8258 // as the type of the stmtexpr. 8259 QualType Ty = Context.VoidTy; 8260 bool StmtExprMayBindToTemp = false; 8261 if (!Compound->body_empty()) { 8262 Stmt *LastStmt = Compound->body_back(); 8263 LabelStmt *LastLabelStmt = 0; 8264 // If LastStmt is a label, skip down through into the body. 8265 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 8266 LastLabelStmt = Label; 8267 LastStmt = Label->getSubStmt(); 8268 } 8269 8270 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 8271 // Do function/array conversion on the last expression, but not 8272 // lvalue-to-rvalue. However, initialize an unqualified type. 8273 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 8274 if (LastExpr.isInvalid()) 8275 return ExprError(); 8276 Ty = LastExpr.get()->getType().getUnqualifiedType(); 8277 8278 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 8279 // In ARC, if the final expression ends in a consume, splice 8280 // the consume out and bind it later. In the alternate case 8281 // (when dealing with a retainable type), the result 8282 // initialization will create a produce. In both cases the 8283 // result will be +1, and we'll need to balance that out with 8284 // a bind. 8285 if (Expr *rebuiltLastStmt 8286 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 8287 LastExpr = rebuiltLastStmt; 8288 } else { 8289 LastExpr = PerformCopyInitialization( 8290 InitializedEntity::InitializeResult(LPLoc, 8291 Ty, 8292 false), 8293 SourceLocation(), 8294 LastExpr); 8295 } 8296 8297 if (LastExpr.isInvalid()) 8298 return ExprError(); 8299 if (LastExpr.get() != 0) { 8300 if (!LastLabelStmt) 8301 Compound->setLastStmt(LastExpr.take()); 8302 else 8303 LastLabelStmt->setSubStmt(LastExpr.take()); 8304 StmtExprMayBindToTemp = true; 8305 } 8306 } 8307 } 8308 } 8309 8310 // FIXME: Check that expression type is complete/non-abstract; statement 8311 // expressions are not lvalues. 8312 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 8313 if (StmtExprMayBindToTemp) 8314 return MaybeBindToTemporary(ResStmtExpr); 8315 return Owned(ResStmtExpr); 8316} 8317 8318ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 8319 TypeSourceInfo *TInfo, 8320 OffsetOfComponent *CompPtr, 8321 unsigned NumComponents, 8322 SourceLocation RParenLoc) { 8323 QualType ArgTy = TInfo->getType(); 8324 bool Dependent = ArgTy->isDependentType(); 8325 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 8326 8327 // We must have at least one component that refers to the type, and the first 8328 // one is known to be a field designator. Verify that the ArgTy represents 8329 // a struct/union/class. 8330 if (!Dependent && !ArgTy->isRecordType()) 8331 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 8332 << ArgTy << TypeRange); 8333 8334 // Type must be complete per C99 7.17p3 because a declaring a variable 8335 // with an incomplete type would be ill-formed. 8336 if (!Dependent 8337 && RequireCompleteType(BuiltinLoc, ArgTy, 8338 PDiag(diag::err_offsetof_incomplete_type) 8339 << TypeRange)) 8340 return ExprError(); 8341 8342 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 8343 // GCC extension, diagnose them. 8344 // FIXME: This diagnostic isn't actually visible because the location is in 8345 // a system header! 8346 if (NumComponents != 1) 8347 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 8348 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 8349 8350 bool DidWarnAboutNonPOD = false; 8351 QualType CurrentType = ArgTy; 8352 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 8353 SmallVector<OffsetOfNode, 4> Comps; 8354 SmallVector<Expr*, 4> Exprs; 8355 for (unsigned i = 0; i != NumComponents; ++i) { 8356 const OffsetOfComponent &OC = CompPtr[i]; 8357 if (OC.isBrackets) { 8358 // Offset of an array sub-field. TODO: Should we allow vector elements? 8359 if (!CurrentType->isDependentType()) { 8360 const ArrayType *AT = Context.getAsArrayType(CurrentType); 8361 if(!AT) 8362 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 8363 << CurrentType); 8364 CurrentType = AT->getElementType(); 8365 } else 8366 CurrentType = Context.DependentTy; 8367 8368 // The expression must be an integral expression. 8369 // FIXME: An integral constant expression? 8370 Expr *Idx = static_cast<Expr*>(OC.U.E); 8371 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 8372 !Idx->getType()->isIntegerType()) 8373 return ExprError(Diag(Idx->getLocStart(), 8374 diag::err_typecheck_subscript_not_integer) 8375 << Idx->getSourceRange()); 8376 8377 // Record this array index. 8378 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 8379 Exprs.push_back(Idx); 8380 continue; 8381 } 8382 8383 // Offset of a field. 8384 if (CurrentType->isDependentType()) { 8385 // We have the offset of a field, but we can't look into the dependent 8386 // type. Just record the identifier of the field. 8387 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 8388 CurrentType = Context.DependentTy; 8389 continue; 8390 } 8391 8392 // We need to have a complete type to look into. 8393 if (RequireCompleteType(OC.LocStart, CurrentType, 8394 diag::err_offsetof_incomplete_type)) 8395 return ExprError(); 8396 8397 // Look for the designated field. 8398 const RecordType *RC = CurrentType->getAs<RecordType>(); 8399 if (!RC) 8400 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 8401 << CurrentType); 8402 RecordDecl *RD = RC->getDecl(); 8403 8404 // C++ [lib.support.types]p5: 8405 // The macro offsetof accepts a restricted set of type arguments in this 8406 // International Standard. type shall be a POD structure or a POD union 8407 // (clause 9). 8408 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 8409 if (!CRD->isPOD() && !DidWarnAboutNonPOD && 8410 DiagRuntimeBehavior(BuiltinLoc, 0, 8411 PDiag(diag::warn_offsetof_non_pod_type) 8412 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 8413 << CurrentType)) 8414 DidWarnAboutNonPOD = true; 8415 } 8416 8417 // Look for the field. 8418 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 8419 LookupQualifiedName(R, RD); 8420 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 8421 IndirectFieldDecl *IndirectMemberDecl = 0; 8422 if (!MemberDecl) { 8423 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 8424 MemberDecl = IndirectMemberDecl->getAnonField(); 8425 } 8426 8427 if (!MemberDecl) 8428 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 8429 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 8430 OC.LocEnd)); 8431 8432 // C99 7.17p3: 8433 // (If the specified member is a bit-field, the behavior is undefined.) 8434 // 8435 // We diagnose this as an error. 8436 if (MemberDecl->getBitWidth()) { 8437 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 8438 << MemberDecl->getDeclName() 8439 << SourceRange(BuiltinLoc, RParenLoc); 8440 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 8441 return ExprError(); 8442 } 8443 8444 RecordDecl *Parent = MemberDecl->getParent(); 8445 if (IndirectMemberDecl) 8446 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 8447 8448 // If the member was found in a base class, introduce OffsetOfNodes for 8449 // the base class indirections. 8450 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 8451 /*DetectVirtual=*/false); 8452 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 8453 CXXBasePath &Path = Paths.front(); 8454 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 8455 B != BEnd; ++B) 8456 Comps.push_back(OffsetOfNode(B->Base)); 8457 } 8458 8459 if (IndirectMemberDecl) { 8460 for (IndirectFieldDecl::chain_iterator FI = 8461 IndirectMemberDecl->chain_begin(), 8462 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) { 8463 assert(isa<FieldDecl>(*FI)); 8464 Comps.push_back(OffsetOfNode(OC.LocStart, 8465 cast<FieldDecl>(*FI), OC.LocEnd)); 8466 } 8467 } else 8468 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 8469 8470 CurrentType = MemberDecl->getType().getNonReferenceType(); 8471 } 8472 8473 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 8474 TInfo, Comps.data(), Comps.size(), 8475 Exprs.data(), Exprs.size(), RParenLoc)); 8476} 8477 8478ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 8479 SourceLocation BuiltinLoc, 8480 SourceLocation TypeLoc, 8481 ParsedType argty, 8482 OffsetOfComponent *CompPtr, 8483 unsigned NumComponents, 8484 SourceLocation RPLoc) { 8485 8486 TypeSourceInfo *ArgTInfo; 8487 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo); 8488 if (ArgTy.isNull()) 8489 return ExprError(); 8490 8491 if (!ArgTInfo) 8492 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 8493 8494 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 8495 RPLoc); 8496} 8497 8498 8499ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 8500 Expr *CondExpr, 8501 Expr *LHSExpr, Expr *RHSExpr, 8502 SourceLocation RPLoc) { 8503 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 8504 8505 ExprValueKind VK = VK_RValue; 8506 ExprObjectKind OK = OK_Ordinary; 8507 QualType resType; 8508 bool ValueDependent = false; 8509 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 8510 resType = Context.DependentTy; 8511 ValueDependent = true; 8512 } else { 8513 // The conditional expression is required to be a constant expression. 8514 llvm::APSInt condEval(32); 8515 SourceLocation ExpLoc; 8516 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc)) 8517 return ExprError(Diag(ExpLoc, 8518 diag::err_typecheck_choose_expr_requires_constant) 8519 << CondExpr->getSourceRange()); 8520 8521 // If the condition is > zero, then the AST type is the same as the LSHExpr. 8522 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr; 8523 8524 resType = ActiveExpr->getType(); 8525 ValueDependent = ActiveExpr->isValueDependent(); 8526 VK = ActiveExpr->getValueKind(); 8527 OK = ActiveExpr->getObjectKind(); 8528 } 8529 8530 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 8531 resType, VK, OK, RPLoc, 8532 resType->isDependentType(), 8533 ValueDependent)); 8534} 8535 8536//===----------------------------------------------------------------------===// 8537// Clang Extensions. 8538//===----------------------------------------------------------------------===// 8539 8540/// ActOnBlockStart - This callback is invoked when a block literal is started. 8541void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) { 8542 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 8543 PushBlockScope(BlockScope, Block); 8544 CurContext->addDecl(Block); 8545 if (BlockScope) 8546 PushDeclContext(BlockScope, Block); 8547 else 8548 CurContext = Block; 8549} 8550 8551void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) { 8552 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!"); 8553 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 8554 BlockScopeInfo *CurBlock = getCurBlock(); 8555 8556 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 8557 QualType T = Sig->getType(); 8558 8559 // GetTypeForDeclarator always produces a function type for a block 8560 // literal signature. Furthermore, it is always a FunctionProtoType 8561 // unless the function was written with a typedef. 8562 assert(T->isFunctionType() && 8563 "GetTypeForDeclarator made a non-function block signature"); 8564 8565 // Look for an explicit signature in that function type. 8566 FunctionProtoTypeLoc ExplicitSignature; 8567 8568 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 8569 if (isa<FunctionProtoTypeLoc>(tmp)) { 8570 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp); 8571 8572 // Check whether that explicit signature was synthesized by 8573 // GetTypeForDeclarator. If so, don't save that as part of the 8574 // written signature. 8575 if (ExplicitSignature.getLocalRangeBegin() == 8576 ExplicitSignature.getLocalRangeEnd()) { 8577 // This would be much cheaper if we stored TypeLocs instead of 8578 // TypeSourceInfos. 8579 TypeLoc Result = ExplicitSignature.getResultLoc(); 8580 unsigned Size = Result.getFullDataSize(); 8581 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 8582 Sig->getTypeLoc().initializeFullCopy(Result, Size); 8583 8584 ExplicitSignature = FunctionProtoTypeLoc(); 8585 } 8586 } 8587 8588 CurBlock->TheDecl->setSignatureAsWritten(Sig); 8589 CurBlock->FunctionType = T; 8590 8591 const FunctionType *Fn = T->getAs<FunctionType>(); 8592 QualType RetTy = Fn->getResultType(); 8593 bool isVariadic = 8594 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 8595 8596 CurBlock->TheDecl->setIsVariadic(isVariadic); 8597 8598 // Don't allow returning a objc interface by value. 8599 if (RetTy->isObjCObjectType()) { 8600 Diag(ParamInfo.getSourceRange().getBegin(), 8601 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy; 8602 return; 8603 } 8604 8605 // Context.DependentTy is used as a placeholder for a missing block 8606 // return type. TODO: what should we do with declarators like: 8607 // ^ * { ... } 8608 // If the answer is "apply template argument deduction".... 8609 if (RetTy != Context.DependentTy) 8610 CurBlock->ReturnType = RetTy; 8611 8612 // Push block parameters from the declarator if we had them. 8613 SmallVector<ParmVarDecl*, 8> Params; 8614 if (ExplicitSignature) { 8615 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) { 8616 ParmVarDecl *Param = ExplicitSignature.getArg(I); 8617 if (Param->getIdentifier() == 0 && 8618 !Param->isImplicit() && 8619 !Param->isInvalidDecl() && 8620 !getLangOptions().CPlusPlus) 8621 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 8622 Params.push_back(Param); 8623 } 8624 8625 // Fake up parameter variables if we have a typedef, like 8626 // ^ fntype { ... } 8627 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 8628 for (FunctionProtoType::arg_type_iterator 8629 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) { 8630 ParmVarDecl *Param = 8631 BuildParmVarDeclForTypedef(CurBlock->TheDecl, 8632 ParamInfo.getSourceRange().getBegin(), 8633 *I); 8634 Params.push_back(Param); 8635 } 8636 } 8637 8638 // Set the parameters on the block decl. 8639 if (!Params.empty()) { 8640 CurBlock->TheDecl->setParams(Params.data(), Params.size()); 8641 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 8642 CurBlock->TheDecl->param_end(), 8643 /*CheckParameterNames=*/false); 8644 } 8645 8646 // Finally we can process decl attributes. 8647 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 8648 8649 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) { 8650 Diag(ParamInfo.getAttributes()->getLoc(), 8651 diag::warn_attribute_sentinel_not_variadic) << 1; 8652 // FIXME: remove the attribute. 8653 } 8654 8655 // Put the parameter variables in scope. We can bail out immediately 8656 // if we don't have any. 8657 if (Params.empty()) 8658 return; 8659 8660 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 8661 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) { 8662 (*AI)->setOwningFunction(CurBlock->TheDecl); 8663 8664 // If this has an identifier, add it to the scope stack. 8665 if ((*AI)->getIdentifier()) { 8666 CheckShadow(CurBlock->TheScope, *AI); 8667 8668 PushOnScopeChains(*AI, CurBlock->TheScope); 8669 } 8670 } 8671} 8672 8673/// ActOnBlockError - If there is an error parsing a block, this callback 8674/// is invoked to pop the information about the block from the action impl. 8675void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 8676 // Pop off CurBlock, handle nested blocks. 8677 PopDeclContext(); 8678 PopFunctionOrBlockScope(); 8679} 8680 8681/// ActOnBlockStmtExpr - This is called when the body of a block statement 8682/// literal was successfully completed. ^(int x){...} 8683ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 8684 Stmt *Body, Scope *CurScope) { 8685 // If blocks are disabled, emit an error. 8686 if (!LangOpts.Blocks) 8687 Diag(CaretLoc, diag::err_blocks_disable); 8688 8689 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 8690 8691 PopDeclContext(); 8692 8693 QualType RetTy = Context.VoidTy; 8694 if (!BSI->ReturnType.isNull()) 8695 RetTy = BSI->ReturnType; 8696 8697 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>(); 8698 QualType BlockTy; 8699 8700 // Set the captured variables on the block. 8701 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(), 8702 BSI->CapturesCXXThis); 8703 8704 // If the user wrote a function type in some form, try to use that. 8705 if (!BSI->FunctionType.isNull()) { 8706 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 8707 8708 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 8709 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 8710 8711 // Turn protoless block types into nullary block types. 8712 if (isa<FunctionNoProtoType>(FTy)) { 8713 FunctionProtoType::ExtProtoInfo EPI; 8714 EPI.ExtInfo = Ext; 8715 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI); 8716 8717 // Otherwise, if we don't need to change anything about the function type, 8718 // preserve its sugar structure. 8719 } else if (FTy->getResultType() == RetTy && 8720 (!NoReturn || FTy->getNoReturnAttr())) { 8721 BlockTy = BSI->FunctionType; 8722 8723 // Otherwise, make the minimal modifications to the function type. 8724 } else { 8725 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 8726 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8727 EPI.TypeQuals = 0; // FIXME: silently? 8728 EPI.ExtInfo = Ext; 8729 BlockTy = Context.getFunctionType(RetTy, 8730 FPT->arg_type_begin(), 8731 FPT->getNumArgs(), 8732 EPI); 8733 } 8734 8735 // If we don't have a function type, just build one from nothing. 8736 } else { 8737 FunctionProtoType::ExtProtoInfo EPI; 8738 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 8739 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI); 8740 } 8741 8742 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 8743 BSI->TheDecl->param_end()); 8744 BlockTy = Context.getBlockPointerType(BlockTy); 8745 8746 // If needed, diagnose invalid gotos and switches in the block. 8747 if (getCurFunction()->NeedsScopeChecking() && 8748 !hasAnyUnrecoverableErrorsInThisFunction()) 8749 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 8750 8751 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 8752 8753 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(), 8754 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) { 8755 const VarDecl *variable = ci->getVariable(); 8756 QualType T = variable->getType(); 8757 QualType::DestructionKind destructKind = T.isDestructedType(); 8758 if (destructKind != QualType::DK_none) 8759 getCurFunction()->setHasBranchProtectedScope(); 8760 } 8761 8762 computeNRVO(Body, getCurBlock()); 8763 8764 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 8765 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy(); 8766 PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result); 8767 8768 return Owned(Result); 8769} 8770 8771ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 8772 Expr *expr, ParsedType type, 8773 SourceLocation RPLoc) { 8774 TypeSourceInfo *TInfo; 8775 GetTypeFromParser(type, &TInfo); 8776 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc); 8777} 8778 8779ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 8780 Expr *E, TypeSourceInfo *TInfo, 8781 SourceLocation RPLoc) { 8782 Expr *OrigExpr = E; 8783 8784 // Get the va_list type 8785 QualType VaListType = Context.getBuiltinVaListType(); 8786 if (VaListType->isArrayType()) { 8787 // Deal with implicit array decay; for example, on x86-64, 8788 // va_list is an array, but it's supposed to decay to 8789 // a pointer for va_arg. 8790 VaListType = Context.getArrayDecayedType(VaListType); 8791 // Make sure the input expression also decays appropriately. 8792 ExprResult Result = UsualUnaryConversions(E); 8793 if (Result.isInvalid()) 8794 return ExprError(); 8795 E = Result.take(); 8796 } else { 8797 // Otherwise, the va_list argument must be an l-value because 8798 // it is modified by va_arg. 8799 if (!E->isTypeDependent() && 8800 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 8801 return ExprError(); 8802 } 8803 8804 if (!E->isTypeDependent() && 8805 !Context.hasSameType(VaListType, E->getType())) { 8806 return ExprError(Diag(E->getLocStart(), 8807 diag::err_first_argument_to_va_arg_not_of_type_va_list) 8808 << OrigExpr->getType() << E->getSourceRange()); 8809 } 8810 8811 if (!TInfo->getType()->isDependentType()) { 8812 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 8813 PDiag(diag::err_second_parameter_to_va_arg_incomplete) 8814 << TInfo->getTypeLoc().getSourceRange())) 8815 return ExprError(); 8816 8817 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 8818 TInfo->getType(), 8819 PDiag(diag::err_second_parameter_to_va_arg_abstract) 8820 << TInfo->getTypeLoc().getSourceRange())) 8821 return ExprError(); 8822 8823 if (!TInfo->getType().isPODType(Context)) { 8824 Diag(TInfo->getTypeLoc().getBeginLoc(), 8825 TInfo->getType()->isObjCLifetimeType() 8826 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 8827 : diag::warn_second_parameter_to_va_arg_not_pod) 8828 << TInfo->getType() 8829 << TInfo->getTypeLoc().getSourceRange(); 8830 } 8831 8832 // Check for va_arg where arguments of the given type will be promoted 8833 // (i.e. this va_arg is guaranteed to have undefined behavior). 8834 QualType PromoteType; 8835 if (TInfo->getType()->isPromotableIntegerType()) { 8836 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 8837 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 8838 PromoteType = QualType(); 8839 } 8840 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 8841 PromoteType = Context.DoubleTy; 8842 if (!PromoteType.isNull()) 8843 Diag(TInfo->getTypeLoc().getBeginLoc(), 8844 diag::warn_second_parameter_to_va_arg_never_compatible) 8845 << TInfo->getType() 8846 << PromoteType 8847 << TInfo->getTypeLoc().getSourceRange(); 8848 } 8849 8850 QualType T = TInfo->getType().getNonLValueExprType(Context); 8851 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T)); 8852} 8853 8854ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 8855 // The type of __null will be int or long, depending on the size of 8856 // pointers on the target. 8857 QualType Ty; 8858 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 8859 if (pw == Context.getTargetInfo().getIntWidth()) 8860 Ty = Context.IntTy; 8861 else if (pw == Context.getTargetInfo().getLongWidth()) 8862 Ty = Context.LongTy; 8863 else if (pw == Context.getTargetInfo().getLongLongWidth()) 8864 Ty = Context.LongLongTy; 8865 else { 8866 assert(!"I don't know size of pointer!"); 8867 Ty = Context.IntTy; 8868 } 8869 8870 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); 8871} 8872 8873static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType, 8874 Expr *SrcExpr, FixItHint &Hint) { 8875 if (!SemaRef.getLangOptions().ObjC1) 8876 return; 8877 8878 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 8879 if (!PT) 8880 return; 8881 8882 // Check if the destination is of type 'id'. 8883 if (!PT->isObjCIdType()) { 8884 // Check if the destination is the 'NSString' interface. 8885 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 8886 if (!ID || !ID->getIdentifier()->isStr("NSString")) 8887 return; 8888 } 8889 8890 // Strip off any parens and casts. 8891 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts()); 8892 if (!SL || !SL->isAscii()) 8893 return; 8894 8895 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@"); 8896} 8897 8898bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 8899 SourceLocation Loc, 8900 QualType DstType, QualType SrcType, 8901 Expr *SrcExpr, AssignmentAction Action, 8902 bool *Complained) { 8903 if (Complained) 8904 *Complained = false; 8905 8906 // Decode the result (notice that AST's are still created for extensions). 8907 bool CheckInferredResultType = false; 8908 bool isInvalid = false; 8909 unsigned DiagKind; 8910 FixItHint Hint; 8911 ConversionFixItGenerator ConvHints; 8912 bool MayHaveConvFixit = false; 8913 8914 switch (ConvTy) { 8915 default: assert(0 && "Unknown conversion type"); 8916 case Compatible: return false; 8917 case PointerToInt: 8918 DiagKind = diag::ext_typecheck_convert_pointer_int; 8919 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 8920 MayHaveConvFixit = true; 8921 break; 8922 case IntToPointer: 8923 DiagKind = diag::ext_typecheck_convert_int_pointer; 8924 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 8925 MayHaveConvFixit = true; 8926 break; 8927 case IncompatiblePointer: 8928 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint); 8929 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 8930 CheckInferredResultType = DstType->isObjCObjectPointerType() && 8931 SrcType->isObjCObjectPointerType(); 8932 if (Hint.isNull() && !CheckInferredResultType) { 8933 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 8934 } 8935 MayHaveConvFixit = true; 8936 break; 8937 case IncompatiblePointerSign: 8938 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 8939 break; 8940 case FunctionVoidPointer: 8941 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 8942 break; 8943 case IncompatiblePointerDiscardsQualifiers: { 8944 // Perform array-to-pointer decay if necessary. 8945 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 8946 8947 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 8948 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 8949 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 8950 DiagKind = diag::err_typecheck_incompatible_address_space; 8951 break; 8952 8953 8954 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 8955 DiagKind = diag::err_typecheck_incompatible_ownership; 8956 break; 8957 } 8958 8959 llvm_unreachable("unknown error case for discarding qualifiers!"); 8960 // fallthrough 8961 } 8962 case CompatiblePointerDiscardsQualifiers: 8963 // If the qualifiers lost were because we were applying the 8964 // (deprecated) C++ conversion from a string literal to a char* 8965 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 8966 // Ideally, this check would be performed in 8967 // checkPointerTypesForAssignment. However, that would require a 8968 // bit of refactoring (so that the second argument is an 8969 // expression, rather than a type), which should be done as part 8970 // of a larger effort to fix checkPointerTypesForAssignment for 8971 // C++ semantics. 8972 if (getLangOptions().CPlusPlus && 8973 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 8974 return false; 8975 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 8976 break; 8977 case IncompatibleNestedPointerQualifiers: 8978 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 8979 break; 8980 case IntToBlockPointer: 8981 DiagKind = diag::err_int_to_block_pointer; 8982 break; 8983 case IncompatibleBlockPointer: 8984 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 8985 break; 8986 case IncompatibleObjCQualifiedId: 8987 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 8988 // it can give a more specific diagnostic. 8989 DiagKind = diag::warn_incompatible_qualified_id; 8990 break; 8991 case IncompatibleVectors: 8992 DiagKind = diag::warn_incompatible_vectors; 8993 break; 8994 case IncompatibleObjCWeakRef: 8995 DiagKind = diag::err_arc_weak_unavailable_assign; 8996 break; 8997 case Incompatible: 8998 DiagKind = diag::err_typecheck_convert_incompatible; 8999 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 9000 MayHaveConvFixit = true; 9001 isInvalid = true; 9002 break; 9003 } 9004 9005 QualType FirstType, SecondType; 9006 switch (Action) { 9007 case AA_Assigning: 9008 case AA_Initializing: 9009 // The destination type comes first. 9010 FirstType = DstType; 9011 SecondType = SrcType; 9012 break; 9013 9014 case AA_Returning: 9015 case AA_Passing: 9016 case AA_Converting: 9017 case AA_Sending: 9018 case AA_Casting: 9019 // The source type comes first. 9020 FirstType = SrcType; 9021 SecondType = DstType; 9022 break; 9023 } 9024 9025 PartialDiagnostic FDiag = PDiag(DiagKind); 9026 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 9027 9028 // If we can fix the conversion, suggest the FixIts. 9029 assert(ConvHints.isNull() || Hint.isNull()); 9030 if (!ConvHints.isNull()) { 9031 for (llvm::SmallVector<FixItHint, 1>::iterator 9032 HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end(); 9033 HI != HE; ++HI) 9034 FDiag << *HI; 9035 } else { 9036 FDiag << Hint; 9037 } 9038 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 9039 9040 Diag(Loc, FDiag); 9041 9042 if (CheckInferredResultType) 9043 EmitRelatedResultTypeNote(SrcExpr); 9044 9045 if (Complained) 9046 *Complained = true; 9047 return isInvalid; 9048} 9049 9050bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){ 9051 llvm::APSInt ICEResult; 9052 if (E->isIntegerConstantExpr(ICEResult, Context)) { 9053 if (Result) 9054 *Result = ICEResult; 9055 return false; 9056 } 9057 9058 Expr::EvalResult EvalResult; 9059 9060 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() || 9061 EvalResult.HasSideEffects) { 9062 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange(); 9063 9064 if (EvalResult.Diag) { 9065 // We only show the note if it's not the usual "invalid subexpression" 9066 // or if it's actually in a subexpression. 9067 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice || 9068 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens()) 9069 Diag(EvalResult.DiagLoc, EvalResult.Diag); 9070 } 9071 9072 return true; 9073 } 9074 9075 Diag(E->getExprLoc(), diag::ext_expr_not_ice) << 9076 E->getSourceRange(); 9077 9078 if (EvalResult.Diag && 9079 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc) 9080 != Diagnostic::Ignored) 9081 Diag(EvalResult.DiagLoc, EvalResult.Diag); 9082 9083 if (Result) 9084 *Result = EvalResult.Val.getInt(); 9085 return false; 9086} 9087 9088void 9089Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) { 9090 ExprEvalContexts.push_back( 9091 ExpressionEvaluationContextRecord(NewContext, 9092 ExprTemporaries.size(), 9093 ExprNeedsCleanups)); 9094 ExprNeedsCleanups = false; 9095} 9096 9097void Sema::PopExpressionEvaluationContext() { 9098 // Pop the current expression evaluation context off the stack. 9099 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back(); 9100 ExprEvalContexts.pop_back(); 9101 9102 if (Rec.Context == PotentiallyPotentiallyEvaluated) { 9103 if (Rec.PotentiallyReferenced) { 9104 // Mark any remaining declarations in the current position of the stack 9105 // as "referenced". If they were not meant to be referenced, semantic 9106 // analysis would have eliminated them (e.g., in ActOnCXXTypeId). 9107 for (PotentiallyReferencedDecls::iterator 9108 I = Rec.PotentiallyReferenced->begin(), 9109 IEnd = Rec.PotentiallyReferenced->end(); 9110 I != IEnd; ++I) 9111 MarkDeclarationReferenced(I->first, I->second); 9112 } 9113 9114 if (Rec.PotentiallyDiagnosed) { 9115 // Emit any pending diagnostics. 9116 for (PotentiallyEmittedDiagnostics::iterator 9117 I = Rec.PotentiallyDiagnosed->begin(), 9118 IEnd = Rec.PotentiallyDiagnosed->end(); 9119 I != IEnd; ++I) 9120 Diag(I->first, I->second); 9121 } 9122 } 9123 9124 // When are coming out of an unevaluated context, clear out any 9125 // temporaries that we may have created as part of the evaluation of 9126 // the expression in that context: they aren't relevant because they 9127 // will never be constructed. 9128 if (Rec.Context == Unevaluated) { 9129 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries, 9130 ExprTemporaries.end()); 9131 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 9132 9133 // Otherwise, merge the contexts together. 9134 } else { 9135 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 9136 } 9137 9138 // Destroy the popped expression evaluation record. 9139 Rec.Destroy(); 9140} 9141 9142void Sema::DiscardCleanupsInEvaluationContext() { 9143 ExprTemporaries.erase( 9144 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries, 9145 ExprTemporaries.end()); 9146 ExprNeedsCleanups = false; 9147} 9148 9149/// \brief Note that the given declaration was referenced in the source code. 9150/// 9151/// This routine should be invoke whenever a given declaration is referenced 9152/// in the source code, and where that reference occurred. If this declaration 9153/// reference means that the the declaration is used (C++ [basic.def.odr]p2, 9154/// C99 6.9p3), then the declaration will be marked as used. 9155/// 9156/// \param Loc the location where the declaration was referenced. 9157/// 9158/// \param D the declaration that has been referenced by the source code. 9159void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) { 9160 assert(D && "No declaration?"); 9161 9162 D->setReferenced(); 9163 9164 if (D->isUsed(false)) 9165 return; 9166 9167 // Mark a parameter or variable declaration "used", regardless of whether 9168 // we're in a template or not. The reason for this is that unevaluated 9169 // expressions (e.g. (void)sizeof()) constitute a use for warning purposes 9170 // (-Wunused-variables and -Wunused-parameters) 9171 if (isa<ParmVarDecl>(D) || 9172 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) { 9173 D->setUsed(); 9174 return; 9175 } 9176 9177 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D)) 9178 return; 9179 9180 // Do not mark anything as "used" within a dependent context; wait for 9181 // an instantiation. 9182 if (CurContext->isDependentContext()) 9183 return; 9184 9185 switch (ExprEvalContexts.back().Context) { 9186 case Unevaluated: 9187 // We are in an expression that is not potentially evaluated; do nothing. 9188 return; 9189 9190 case PotentiallyEvaluated: 9191 // We are in a potentially-evaluated expression, so this declaration is 9192 // "used"; handle this below. 9193 break; 9194 9195 case PotentiallyPotentiallyEvaluated: 9196 // We are in an expression that may be potentially evaluated; queue this 9197 // declaration reference until we know whether the expression is 9198 // potentially evaluated. 9199 ExprEvalContexts.back().addReferencedDecl(Loc, D); 9200 return; 9201 9202 case PotentiallyEvaluatedIfUsed: 9203 // Referenced declarations will only be used if the construct in the 9204 // containing expression is used. 9205 return; 9206 } 9207 9208 // Note that this declaration has been used. 9209 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 9210 if (Constructor->isDefaulted()) { 9211 if (Constructor->isDefaultConstructor()) { 9212 if (Constructor->isTrivial()) 9213 return; 9214 if (!Constructor->isUsed(false)) 9215 DefineImplicitDefaultConstructor(Loc, Constructor); 9216 } else if (Constructor->isCopyConstructor()) { 9217 if (!Constructor->isUsed(false)) 9218 DefineImplicitCopyConstructor(Loc, Constructor); 9219 } else if (Constructor->isMoveConstructor()) { 9220 if (!Constructor->isUsed(false)) 9221 DefineImplicitMoveConstructor(Loc, Constructor); 9222 } 9223 } 9224 9225 MarkVTableUsed(Loc, Constructor->getParent()); 9226 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 9227 if (Destructor->isDefaulted() && !Destructor->isUsed(false)) 9228 DefineImplicitDestructor(Loc, Destructor); 9229 if (Destructor->isVirtual()) 9230 MarkVTableUsed(Loc, Destructor->getParent()); 9231 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) { 9232 if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() && 9233 MethodDecl->getOverloadedOperator() == OO_Equal) { 9234 if (!MethodDecl->isUsed(false)) { 9235 if (MethodDecl->isCopyAssignmentOperator()) 9236 DefineImplicitCopyAssignment(Loc, MethodDecl); 9237 else 9238 DefineImplicitMoveAssignment(Loc, MethodDecl); 9239 } 9240 } else if (MethodDecl->isVirtual()) 9241 MarkVTableUsed(Loc, MethodDecl->getParent()); 9242 } 9243 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 9244 // Recursive functions should be marked when used from another function. 9245 if (CurContext == Function) return; 9246 9247 // Implicit instantiation of function templates and member functions of 9248 // class templates. 9249 if (Function->isImplicitlyInstantiable()) { 9250 bool AlreadyInstantiated = false; 9251 if (FunctionTemplateSpecializationInfo *SpecInfo 9252 = Function->getTemplateSpecializationInfo()) { 9253 if (SpecInfo->getPointOfInstantiation().isInvalid()) 9254 SpecInfo->setPointOfInstantiation(Loc); 9255 else if (SpecInfo->getTemplateSpecializationKind() 9256 == TSK_ImplicitInstantiation) 9257 AlreadyInstantiated = true; 9258 } else if (MemberSpecializationInfo *MSInfo 9259 = Function->getMemberSpecializationInfo()) { 9260 if (MSInfo->getPointOfInstantiation().isInvalid()) 9261 MSInfo->setPointOfInstantiation(Loc); 9262 else if (MSInfo->getTemplateSpecializationKind() 9263 == TSK_ImplicitInstantiation) 9264 AlreadyInstantiated = true; 9265 } 9266 9267 if (!AlreadyInstantiated) { 9268 if (isa<CXXRecordDecl>(Function->getDeclContext()) && 9269 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass()) 9270 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function, 9271 Loc)); 9272 else 9273 PendingInstantiations.push_back(std::make_pair(Function, Loc)); 9274 } 9275 } else { 9276 // Walk redefinitions, as some of them may be instantiable. 9277 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()), 9278 e(Function->redecls_end()); i != e; ++i) { 9279 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 9280 MarkDeclarationReferenced(Loc, *i); 9281 } 9282 } 9283 9284 // Keep track of used but undefined functions. 9285 if (!Function->isPure() && !Function->hasBody() && 9286 Function->getLinkage() != ExternalLinkage) { 9287 SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()]; 9288 if (old.isInvalid()) old = Loc; 9289 } 9290 9291 Function->setUsed(true); 9292 return; 9293 } 9294 9295 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 9296 // Implicit instantiation of static data members of class templates. 9297 if (Var->isStaticDataMember() && 9298 Var->getInstantiatedFromStaticDataMember()) { 9299 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 9300 assert(MSInfo && "Missing member specialization information?"); 9301 if (MSInfo->getPointOfInstantiation().isInvalid() && 9302 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) { 9303 MSInfo->setPointOfInstantiation(Loc); 9304 // This is a modification of an existing AST node. Notify listeners. 9305 if (ASTMutationListener *L = getASTMutationListener()) 9306 L->StaticDataMemberInstantiated(Var); 9307 PendingInstantiations.push_back(std::make_pair(Var, Loc)); 9308 } 9309 } 9310 9311 // Keep track of used but undefined variables. We make a hole in 9312 // the warning for static const data members with in-line 9313 // initializers. 9314 if (Var->hasDefinition() == VarDecl::DeclarationOnly 9315 && Var->getLinkage() != ExternalLinkage 9316 && !(Var->isStaticDataMember() && Var->hasInit())) { 9317 SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()]; 9318 if (old.isInvalid()) old = Loc; 9319 } 9320 9321 D->setUsed(true); 9322 return; 9323 } 9324} 9325 9326namespace { 9327 // Mark all of the declarations referenced 9328 // FIXME: Not fully implemented yet! We need to have a better understanding 9329 // of when we're entering 9330 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 9331 Sema &S; 9332 SourceLocation Loc; 9333 9334 public: 9335 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 9336 9337 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 9338 9339 bool TraverseTemplateArgument(const TemplateArgument &Arg); 9340 bool TraverseRecordType(RecordType *T); 9341 }; 9342} 9343 9344bool MarkReferencedDecls::TraverseTemplateArgument( 9345 const TemplateArgument &Arg) { 9346 if (Arg.getKind() == TemplateArgument::Declaration) { 9347 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl()); 9348 } 9349 9350 return Inherited::TraverseTemplateArgument(Arg); 9351} 9352 9353bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 9354 if (ClassTemplateSpecializationDecl *Spec 9355 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 9356 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 9357 return TraverseTemplateArguments(Args.data(), Args.size()); 9358 } 9359 9360 return true; 9361} 9362 9363void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 9364 MarkReferencedDecls Marker(*this, Loc); 9365 Marker.TraverseType(Context.getCanonicalType(T)); 9366} 9367 9368namespace { 9369 /// \brief Helper class that marks all of the declarations referenced by 9370 /// potentially-evaluated subexpressions as "referenced". 9371 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 9372 Sema &S; 9373 9374 public: 9375 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 9376 9377 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { } 9378 9379 void VisitDeclRefExpr(DeclRefExpr *E) { 9380 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl()); 9381 } 9382 9383 void VisitMemberExpr(MemberExpr *E) { 9384 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl()); 9385 Inherited::VisitMemberExpr(E); 9386 } 9387 9388 void VisitCXXNewExpr(CXXNewExpr *E) { 9389 if (E->getConstructor()) 9390 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor()); 9391 if (E->getOperatorNew()) 9392 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew()); 9393 if (E->getOperatorDelete()) 9394 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete()); 9395 Inherited::VisitCXXNewExpr(E); 9396 } 9397 9398 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 9399 if (E->getOperatorDelete()) 9400 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete()); 9401 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 9402 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 9403 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 9404 S.MarkDeclarationReferenced(E->getLocStart(), 9405 S.LookupDestructor(Record)); 9406 } 9407 9408 Inherited::VisitCXXDeleteExpr(E); 9409 } 9410 9411 void VisitCXXConstructExpr(CXXConstructExpr *E) { 9412 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor()); 9413 Inherited::VisitCXXConstructExpr(E); 9414 } 9415 9416 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) { 9417 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl()); 9418 } 9419 9420 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 9421 Visit(E->getExpr()); 9422 } 9423 }; 9424} 9425 9426/// \brief Mark any declarations that appear within this expression or any 9427/// potentially-evaluated subexpressions as "referenced". 9428void Sema::MarkDeclarationsReferencedInExpr(Expr *E) { 9429 EvaluatedExprMarker(*this).Visit(E); 9430} 9431 9432/// \brief Emit a diagnostic that describes an effect on the run-time behavior 9433/// of the program being compiled. 9434/// 9435/// This routine emits the given diagnostic when the code currently being 9436/// type-checked is "potentially evaluated", meaning that there is a 9437/// possibility that the code will actually be executable. Code in sizeof() 9438/// expressions, code used only during overload resolution, etc., are not 9439/// potentially evaluated. This routine will suppress such diagnostics or, 9440/// in the absolutely nutty case of potentially potentially evaluated 9441/// expressions (C++ typeid), queue the diagnostic to potentially emit it 9442/// later. 9443/// 9444/// This routine should be used for all diagnostics that describe the run-time 9445/// behavior of a program, such as passing a non-POD value through an ellipsis. 9446/// Failure to do so will likely result in spurious diagnostics or failures 9447/// during overload resolution or within sizeof/alignof/typeof/typeid. 9448bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt, 9449 const PartialDiagnostic &PD) { 9450 switch (ExprEvalContexts.back().Context) { 9451 case Unevaluated: 9452 // The argument will never be evaluated, so don't complain. 9453 break; 9454 9455 case PotentiallyEvaluated: 9456 case PotentiallyEvaluatedIfUsed: 9457 if (stmt && getCurFunctionOrMethodDecl()) { 9458 FunctionScopes.back()->PossiblyUnreachableDiags. 9459 push_back(sema::PossiblyUnreachableDiag(PD, Loc, stmt)); 9460 } 9461 else 9462 Diag(Loc, PD); 9463 9464 return true; 9465 9466 case PotentiallyPotentiallyEvaluated: 9467 ExprEvalContexts.back().addDiagnostic(Loc, PD); 9468 break; 9469 } 9470 9471 return false; 9472} 9473 9474bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 9475 CallExpr *CE, FunctionDecl *FD) { 9476 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 9477 return false; 9478 9479 PartialDiagnostic Note = 9480 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here) 9481 << FD->getDeclName() : PDiag(); 9482 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation(); 9483 9484 if (RequireCompleteType(Loc, ReturnType, 9485 FD ? 9486 PDiag(diag::err_call_function_incomplete_return) 9487 << CE->getSourceRange() << FD->getDeclName() : 9488 PDiag(diag::err_call_incomplete_return) 9489 << CE->getSourceRange(), 9490 std::make_pair(NoteLoc, Note))) 9491 return true; 9492 9493 return false; 9494} 9495 9496// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 9497// will prevent this condition from triggering, which is what we want. 9498void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 9499 SourceLocation Loc; 9500 9501 unsigned diagnostic = diag::warn_condition_is_assignment; 9502 bool IsOrAssign = false; 9503 9504 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 9505 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 9506 return; 9507 9508 IsOrAssign = Op->getOpcode() == BO_OrAssign; 9509 9510 // Greylist some idioms by putting them into a warning subcategory. 9511 if (ObjCMessageExpr *ME 9512 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 9513 Selector Sel = ME->getSelector(); 9514 9515 // self = [<foo> init...] 9516 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init")) 9517 diagnostic = diag::warn_condition_is_idiomatic_assignment; 9518 9519 // <foo> = [<bar> nextObject] 9520 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 9521 diagnostic = diag::warn_condition_is_idiomatic_assignment; 9522 } 9523 9524 Loc = Op->getOperatorLoc(); 9525 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 9526 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 9527 return; 9528 9529 IsOrAssign = Op->getOperator() == OO_PipeEqual; 9530 Loc = Op->getOperatorLoc(); 9531 } else { 9532 // Not an assignment. 9533 return; 9534 } 9535 9536 Diag(Loc, diagnostic) << E->getSourceRange(); 9537 9538 SourceLocation Open = E->getSourceRange().getBegin(); 9539 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 9540 Diag(Loc, diag::note_condition_assign_silence) 9541 << FixItHint::CreateInsertion(Open, "(") 9542 << FixItHint::CreateInsertion(Close, ")"); 9543 9544 if (IsOrAssign) 9545 Diag(Loc, diag::note_condition_or_assign_to_comparison) 9546 << FixItHint::CreateReplacement(Loc, "!="); 9547 else 9548 Diag(Loc, diag::note_condition_assign_to_comparison) 9549 << FixItHint::CreateReplacement(Loc, "=="); 9550} 9551 9552/// \brief Redundant parentheses over an equality comparison can indicate 9553/// that the user intended an assignment used as condition. 9554void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) { 9555 // Don't warn if the parens came from a macro. 9556 SourceLocation parenLoc = parenE->getLocStart(); 9557 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 9558 return; 9559 // Don't warn for dependent expressions. 9560 if (parenE->isTypeDependent()) 9561 return; 9562 9563 Expr *E = parenE->IgnoreParens(); 9564 9565 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 9566 if (opE->getOpcode() == BO_EQ && 9567 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 9568 == Expr::MLV_Valid) { 9569 SourceLocation Loc = opE->getOperatorLoc(); 9570 9571 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 9572 Diag(Loc, diag::note_equality_comparison_silence) 9573 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin()) 9574 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd()); 9575 Diag(Loc, diag::note_equality_comparison_to_assign) 9576 << FixItHint::CreateReplacement(Loc, "="); 9577 } 9578} 9579 9580ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 9581 DiagnoseAssignmentAsCondition(E); 9582 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 9583 DiagnoseEqualityWithExtraParens(parenE); 9584 9585 ExprResult result = CheckPlaceholderExpr(E); 9586 if (result.isInvalid()) return ExprError(); 9587 E = result.take(); 9588 9589 if (!E->isTypeDependent()) { 9590 if (getLangOptions().CPlusPlus) 9591 return CheckCXXBooleanCondition(E); // C++ 6.4p4 9592 9593 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 9594 if (ERes.isInvalid()) 9595 return ExprError(); 9596 E = ERes.take(); 9597 9598 QualType T = E->getType(); 9599 if (!T->isScalarType()) { // C99 6.8.4.1p1 9600 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 9601 << T << E->getSourceRange(); 9602 return ExprError(); 9603 } 9604 } 9605 9606 return Owned(E); 9607} 9608 9609ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 9610 Expr *Sub) { 9611 if (!Sub) 9612 return ExprError(); 9613 9614 return CheckBooleanCondition(Sub, Loc); 9615} 9616 9617namespace { 9618 /// A visitor for rebuilding a call to an __unknown_any expression 9619 /// to have an appropriate type. 9620 struct RebuildUnknownAnyFunction 9621 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 9622 9623 Sema &S; 9624 9625 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 9626 9627 ExprResult VisitStmt(Stmt *S) { 9628 llvm_unreachable("unexpected statement!"); 9629 return ExprError(); 9630 } 9631 9632 ExprResult VisitExpr(Expr *expr) { 9633 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_call) 9634 << expr->getSourceRange(); 9635 return ExprError(); 9636 } 9637 9638 /// Rebuild an expression which simply semantically wraps another 9639 /// expression which it shares the type and value kind of. 9640 template <class T> ExprResult rebuildSugarExpr(T *expr) { 9641 ExprResult subResult = Visit(expr->getSubExpr()); 9642 if (subResult.isInvalid()) return ExprError(); 9643 9644 Expr *subExpr = subResult.take(); 9645 expr->setSubExpr(subExpr); 9646 expr->setType(subExpr->getType()); 9647 expr->setValueKind(subExpr->getValueKind()); 9648 assert(expr->getObjectKind() == OK_Ordinary); 9649 return expr; 9650 } 9651 9652 ExprResult VisitParenExpr(ParenExpr *paren) { 9653 return rebuildSugarExpr(paren); 9654 } 9655 9656 ExprResult VisitUnaryExtension(UnaryOperator *op) { 9657 return rebuildSugarExpr(op); 9658 } 9659 9660 ExprResult VisitUnaryAddrOf(UnaryOperator *op) { 9661 ExprResult subResult = Visit(op->getSubExpr()); 9662 if (subResult.isInvalid()) return ExprError(); 9663 9664 Expr *subExpr = subResult.take(); 9665 op->setSubExpr(subExpr); 9666 op->setType(S.Context.getPointerType(subExpr->getType())); 9667 assert(op->getValueKind() == VK_RValue); 9668 assert(op->getObjectKind() == OK_Ordinary); 9669 return op; 9670 } 9671 9672 ExprResult resolveDecl(Expr *expr, ValueDecl *decl) { 9673 if (!isa<FunctionDecl>(decl)) return VisitExpr(expr); 9674 9675 expr->setType(decl->getType()); 9676 9677 assert(expr->getValueKind() == VK_RValue); 9678 if (S.getLangOptions().CPlusPlus && 9679 !(isa<CXXMethodDecl>(decl) && 9680 cast<CXXMethodDecl>(decl)->isInstance())) 9681 expr->setValueKind(VK_LValue); 9682 9683 return expr; 9684 } 9685 9686 ExprResult VisitMemberExpr(MemberExpr *mem) { 9687 return resolveDecl(mem, mem->getMemberDecl()); 9688 } 9689 9690 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) { 9691 return resolveDecl(ref, ref->getDecl()); 9692 } 9693 }; 9694} 9695 9696/// Given a function expression of unknown-any type, try to rebuild it 9697/// to have a function type. 9698static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn) { 9699 ExprResult result = RebuildUnknownAnyFunction(S).Visit(fn); 9700 if (result.isInvalid()) return ExprError(); 9701 return S.DefaultFunctionArrayConversion(result.take()); 9702} 9703 9704namespace { 9705 /// A visitor for rebuilding an expression of type __unknown_anytype 9706 /// into one which resolves the type directly on the referring 9707 /// expression. Strict preservation of the original source 9708 /// structure is not a goal. 9709 struct RebuildUnknownAnyExpr 9710 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 9711 9712 Sema &S; 9713 9714 /// The current destination type. 9715 QualType DestType; 9716 9717 RebuildUnknownAnyExpr(Sema &S, QualType castType) 9718 : S(S), DestType(castType) {} 9719 9720 ExprResult VisitStmt(Stmt *S) { 9721 llvm_unreachable("unexpected statement!"); 9722 return ExprError(); 9723 } 9724 9725 ExprResult VisitExpr(Expr *expr) { 9726 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_expr) 9727 << expr->getSourceRange(); 9728 return ExprError(); 9729 } 9730 9731 ExprResult VisitCallExpr(CallExpr *call); 9732 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *message); 9733 9734 /// Rebuild an expression which simply semantically wraps another 9735 /// expression which it shares the type and value kind of. 9736 template <class T> ExprResult rebuildSugarExpr(T *expr) { 9737 ExprResult subResult = Visit(expr->getSubExpr()); 9738 if (subResult.isInvalid()) return ExprError(); 9739 Expr *subExpr = subResult.take(); 9740 expr->setSubExpr(subExpr); 9741 expr->setType(subExpr->getType()); 9742 expr->setValueKind(subExpr->getValueKind()); 9743 assert(expr->getObjectKind() == OK_Ordinary); 9744 return expr; 9745 } 9746 9747 ExprResult VisitParenExpr(ParenExpr *paren) { 9748 return rebuildSugarExpr(paren); 9749 } 9750 9751 ExprResult VisitUnaryExtension(UnaryOperator *op) { 9752 return rebuildSugarExpr(op); 9753 } 9754 9755 ExprResult VisitUnaryAddrOf(UnaryOperator *op) { 9756 const PointerType *ptr = DestType->getAs<PointerType>(); 9757 if (!ptr) { 9758 S.Diag(op->getOperatorLoc(), diag::err_unknown_any_addrof) 9759 << op->getSourceRange(); 9760 return ExprError(); 9761 } 9762 assert(op->getValueKind() == VK_RValue); 9763 assert(op->getObjectKind() == OK_Ordinary); 9764 op->setType(DestType); 9765 9766 // Build the sub-expression as if it were an object of the pointee type. 9767 DestType = ptr->getPointeeType(); 9768 ExprResult subResult = Visit(op->getSubExpr()); 9769 if (subResult.isInvalid()) return ExprError(); 9770 op->setSubExpr(subResult.take()); 9771 return op; 9772 } 9773 9774 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *ice); 9775 9776 ExprResult resolveDecl(Expr *expr, ValueDecl *decl); 9777 9778 ExprResult VisitMemberExpr(MemberExpr *mem) { 9779 return resolveDecl(mem, mem->getMemberDecl()); 9780 } 9781 9782 ExprResult VisitDeclRefExpr(DeclRefExpr *ref) { 9783 return resolveDecl(ref, ref->getDecl()); 9784 } 9785 }; 9786} 9787 9788/// Rebuilds a call expression which yielded __unknown_anytype. 9789ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *call) { 9790 Expr *callee = call->getCallee(); 9791 9792 enum FnKind { 9793 FK_MemberFunction, 9794 FK_FunctionPointer, 9795 FK_BlockPointer 9796 }; 9797 9798 FnKind kind; 9799 QualType type = callee->getType(); 9800 if (type == S.Context.BoundMemberTy) { 9801 assert(isa<CXXMemberCallExpr>(call) || isa<CXXOperatorCallExpr>(call)); 9802 kind = FK_MemberFunction; 9803 type = Expr::findBoundMemberType(callee); 9804 } else if (const PointerType *ptr = type->getAs<PointerType>()) { 9805 type = ptr->getPointeeType(); 9806 kind = FK_FunctionPointer; 9807 } else { 9808 type = type->castAs<BlockPointerType>()->getPointeeType(); 9809 kind = FK_BlockPointer; 9810 } 9811 const FunctionType *fnType = type->castAs<FunctionType>(); 9812 9813 // Verify that this is a legal result type of a function. 9814 if (DestType->isArrayType() || DestType->isFunctionType()) { 9815 unsigned diagID = diag::err_func_returning_array_function; 9816 if (kind == FK_BlockPointer) 9817 diagID = diag::err_block_returning_array_function; 9818 9819 S.Diag(call->getExprLoc(), diagID) 9820 << DestType->isFunctionType() << DestType; 9821 return ExprError(); 9822 } 9823 9824 // Otherwise, go ahead and set DestType as the call's result. 9825 call->setType(DestType.getNonLValueExprType(S.Context)); 9826 call->setValueKind(Expr::getValueKindForType(DestType)); 9827 assert(call->getObjectKind() == OK_Ordinary); 9828 9829 // Rebuild the function type, replacing the result type with DestType. 9830 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) 9831 DestType = S.Context.getFunctionType(DestType, 9832 proto->arg_type_begin(), 9833 proto->getNumArgs(), 9834 proto->getExtProtoInfo()); 9835 else 9836 DestType = S.Context.getFunctionNoProtoType(DestType, 9837 fnType->getExtInfo()); 9838 9839 // Rebuild the appropriate pointer-to-function type. 9840 switch (kind) { 9841 case FK_MemberFunction: 9842 // Nothing to do. 9843 break; 9844 9845 case FK_FunctionPointer: 9846 DestType = S.Context.getPointerType(DestType); 9847 break; 9848 9849 case FK_BlockPointer: 9850 DestType = S.Context.getBlockPointerType(DestType); 9851 break; 9852 } 9853 9854 // Finally, we can recurse. 9855 ExprResult calleeResult = Visit(callee); 9856 if (!calleeResult.isUsable()) return ExprError(); 9857 call->setCallee(calleeResult.take()); 9858 9859 // Bind a temporary if necessary. 9860 return S.MaybeBindToTemporary(call); 9861} 9862 9863ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *msg) { 9864 // Verify that this is a legal result type of a call. 9865 if (DestType->isArrayType() || DestType->isFunctionType()) { 9866 S.Diag(msg->getExprLoc(), diag::err_func_returning_array_function) 9867 << DestType->isFunctionType() << DestType; 9868 return ExprError(); 9869 } 9870 9871 // Rewrite the method result type if available. 9872 if (ObjCMethodDecl *method = msg->getMethodDecl()) { 9873 assert(method->getResultType() == S.Context.UnknownAnyTy); 9874 method->setResultType(DestType); 9875 } 9876 9877 // Change the type of the message. 9878 msg->setType(DestType.getNonReferenceType()); 9879 msg->setValueKind(Expr::getValueKindForType(DestType)); 9880 9881 return S.MaybeBindToTemporary(msg); 9882} 9883 9884ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *ice) { 9885 // The only case we should ever see here is a function-to-pointer decay. 9886 assert(ice->getCastKind() == CK_FunctionToPointerDecay); 9887 assert(ice->getValueKind() == VK_RValue); 9888 assert(ice->getObjectKind() == OK_Ordinary); 9889 9890 ice->setType(DestType); 9891 9892 // Rebuild the sub-expression as the pointee (function) type. 9893 DestType = DestType->castAs<PointerType>()->getPointeeType(); 9894 9895 ExprResult result = Visit(ice->getSubExpr()); 9896 if (!result.isUsable()) return ExprError(); 9897 9898 ice->setSubExpr(result.take()); 9899 return S.Owned(ice); 9900} 9901 9902ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *expr, ValueDecl *decl) { 9903 ExprValueKind valueKind = VK_LValue; 9904 QualType type = DestType; 9905 9906 // We know how to make this work for certain kinds of decls: 9907 9908 // - functions 9909 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) { 9910 if (const PointerType *ptr = type->getAs<PointerType>()) { 9911 DestType = ptr->getPointeeType(); 9912 ExprResult result = resolveDecl(expr, decl); 9913 if (result.isInvalid()) return ExprError(); 9914 return S.ImpCastExprToType(result.take(), type, 9915 CK_FunctionToPointerDecay, VK_RValue); 9916 } 9917 9918 if (!type->isFunctionType()) { 9919 S.Diag(expr->getExprLoc(), diag::err_unknown_any_function) 9920 << decl << expr->getSourceRange(); 9921 return ExprError(); 9922 } 9923 9924 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(fn)) 9925 if (method->isInstance()) { 9926 valueKind = VK_RValue; 9927 type = S.Context.BoundMemberTy; 9928 } 9929 9930 // Function references aren't l-values in C. 9931 if (!S.getLangOptions().CPlusPlus) 9932 valueKind = VK_RValue; 9933 9934 // - variables 9935 } else if (isa<VarDecl>(decl)) { 9936 if (const ReferenceType *refTy = type->getAs<ReferenceType>()) { 9937 type = refTy->getPointeeType(); 9938 } else if (type->isFunctionType()) { 9939 S.Diag(expr->getExprLoc(), diag::err_unknown_any_var_function_type) 9940 << decl << expr->getSourceRange(); 9941 return ExprError(); 9942 } 9943 9944 // - nothing else 9945 } else { 9946 S.Diag(expr->getExprLoc(), diag::err_unsupported_unknown_any_decl) 9947 << decl << expr->getSourceRange(); 9948 return ExprError(); 9949 } 9950 9951 decl->setType(DestType); 9952 expr->setType(type); 9953 expr->setValueKind(valueKind); 9954 return S.Owned(expr); 9955} 9956 9957/// Check a cast of an unknown-any type. We intentionally only 9958/// trigger this for C-style casts. 9959ExprResult Sema::checkUnknownAnyCast(SourceRange typeRange, QualType castType, 9960 Expr *castExpr, CastKind &castKind, 9961 ExprValueKind &VK, CXXCastPath &path) { 9962 // Rewrite the casted expression from scratch. 9963 ExprResult result = RebuildUnknownAnyExpr(*this, castType).Visit(castExpr); 9964 if (!result.isUsable()) return ExprError(); 9965 9966 castExpr = result.take(); 9967 VK = castExpr->getValueKind(); 9968 castKind = CK_NoOp; 9969 9970 return castExpr; 9971} 9972 9973static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *e) { 9974 Expr *orig = e; 9975 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 9976 while (true) { 9977 e = e->IgnoreParenImpCasts(); 9978 if (CallExpr *call = dyn_cast<CallExpr>(e)) { 9979 e = call->getCallee(); 9980 diagID = diag::err_uncasted_call_of_unknown_any; 9981 } else { 9982 break; 9983 } 9984 } 9985 9986 SourceLocation loc; 9987 NamedDecl *d; 9988 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 9989 loc = ref->getLocation(); 9990 d = ref->getDecl(); 9991 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(e)) { 9992 loc = mem->getMemberLoc(); 9993 d = mem->getMemberDecl(); 9994 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(e)) { 9995 diagID = diag::err_uncasted_call_of_unknown_any; 9996 loc = msg->getSelectorLoc(); 9997 d = msg->getMethodDecl(); 9998 if (!d) { 9999 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 10000 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 10001 << orig->getSourceRange(); 10002 return ExprError(); 10003 } 10004 } else { 10005 S.Diag(e->getExprLoc(), diag::err_unsupported_unknown_any_expr) 10006 << e->getSourceRange(); 10007 return ExprError(); 10008 } 10009 10010 S.Diag(loc, diagID) << d << orig->getSourceRange(); 10011 10012 // Never recoverable. 10013 return ExprError(); 10014} 10015 10016/// Check for operands with placeholder types and complain if found. 10017/// Returns true if there was an error and no recovery was possible. 10018ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 10019 // Placeholder types are always *exactly* the appropriate builtin type. 10020 QualType type = E->getType(); 10021 10022 // Overloaded expressions. 10023 if (type == Context.OverloadTy) 10024 return ResolveAndFixSingleFunctionTemplateSpecialization(E, false, true, 10025 E->getSourceRange(), 10026 QualType(), 10027 diag::err_ovl_unresolvable); 10028 10029 // Bound member functions. 10030 if (type == Context.BoundMemberTy) { 10031 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func) 10032 << E->getSourceRange(); 10033 return ExprError(); 10034 } 10035 10036 // Expressions of unknown type. 10037 if (type == Context.UnknownAnyTy) 10038 return diagnoseUnknownAnyExpr(*this, E); 10039 10040 assert(!type->isPlaceholderType()); 10041 return Owned(E); 10042} 10043 10044bool Sema::CheckCaseExpression(Expr *expr) { 10045 if (expr->isTypeDependent()) 10046 return true; 10047 if (expr->isValueDependent() || expr->isIntegerConstantExpr(Context)) 10048 return expr->getType()->isIntegralOrEnumerationType(); 10049 return false; 10050} 10051