SemaExpr.cpp revision 84268904947ada7e251932a6f5b0f4364df7a2c7
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/DelayedDiagnostic.h" 16#include "clang/Sema/Initialization.h" 17#include "clang/Sema/Lookup.h" 18#include "clang/Sema/ScopeInfo.h" 19#include "clang/Sema/AnalysisBasedWarnings.h" 20#include "clang/AST/ASTContext.h" 21#include "clang/AST/ASTConsumer.h" 22#include "clang/AST/ASTMutationListener.h" 23#include "clang/AST/CXXInheritance.h" 24#include "clang/AST/DeclObjC.h" 25#include "clang/AST/DeclTemplate.h" 26#include "clang/AST/EvaluatedExprVisitor.h" 27#include "clang/AST/Expr.h" 28#include "clang/AST/ExprCXX.h" 29#include "clang/AST/ExprObjC.h" 30#include "clang/AST/RecursiveASTVisitor.h" 31#include "clang/AST/TypeLoc.h" 32#include "clang/Basic/PartialDiagnostic.h" 33#include "clang/Basic/SourceManager.h" 34#include "clang/Basic/TargetInfo.h" 35#include "clang/Lex/LiteralSupport.h" 36#include "clang/Lex/Preprocessor.h" 37#include "clang/Sema/DeclSpec.h" 38#include "clang/Sema/Designator.h" 39#include "clang/Sema/Scope.h" 40#include "clang/Sema/ScopeInfo.h" 41#include "clang/Sema/ParsedTemplate.h" 42#include "clang/Sema/SemaFixItUtils.h" 43#include "clang/Sema/Template.h" 44#include "TreeTransform.h" 45using namespace clang; 46using namespace sema; 47 48/// \brief Determine whether the use of this declaration is valid, without 49/// emitting diagnostics. 50bool Sema::CanUseDecl(NamedDecl *D) { 51 // See if this is an auto-typed variable whose initializer we are parsing. 52 if (ParsingInitForAutoVars.count(D)) 53 return false; 54 55 // See if this is a deleted function. 56 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 57 if (FD->isDeleted()) 58 return false; 59 } 60 61 // See if this function is unavailable. 62 if (D->getAvailability() == AR_Unavailable && 63 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 64 return false; 65 66 return true; 67} 68 69static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 70 // Warn if this is used but marked unused. 71 if (D->hasAttr<UnusedAttr>()) { 72 const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext()); 73 if (!DC->hasAttr<UnusedAttr>()) 74 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 75 } 76} 77 78static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S, 79 NamedDecl *D, SourceLocation Loc, 80 const ObjCInterfaceDecl *UnknownObjCClass) { 81 // See if this declaration is unavailable or deprecated. 82 std::string Message; 83 AvailabilityResult Result = D->getAvailability(&Message); 84 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 85 if (Result == AR_Available) { 86 const DeclContext *DC = ECD->getDeclContext(); 87 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 88 Result = TheEnumDecl->getAvailability(&Message); 89 } 90 91 const ObjCPropertyDecl *ObjCPDecl = 0; 92 if (Result == AR_Deprecated || Result == AR_Unavailable) { 93 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 94 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 95 AvailabilityResult PDeclResult = PD->getAvailability(0); 96 if (PDeclResult == Result) 97 ObjCPDecl = PD; 98 } 99 } 100 } 101 102 switch (Result) { 103 case AR_Available: 104 case AR_NotYetIntroduced: 105 break; 106 107 case AR_Deprecated: 108 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl); 109 break; 110 111 case AR_Unavailable: 112 if (S.getCurContextAvailability() != AR_Unavailable) { 113 if (Message.empty()) { 114 if (!UnknownObjCClass) { 115 S.Diag(Loc, diag::err_unavailable) << D->getDeclName(); 116 if (ObjCPDecl) 117 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute) 118 << ObjCPDecl->getDeclName() << 1; 119 } 120 else 121 S.Diag(Loc, diag::warn_unavailable_fwdclass_message) 122 << D->getDeclName(); 123 } 124 else 125 S.Diag(Loc, diag::err_unavailable_message) 126 << D->getDeclName() << Message; 127 S.Diag(D->getLocation(), diag::note_unavailable_here) 128 << isa<FunctionDecl>(D) << false; 129 if (ObjCPDecl) 130 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute) 131 << ObjCPDecl->getDeclName() << 1; 132 } 133 break; 134 } 135 return Result; 136} 137 138/// \brief Emit a note explaining that this function is deleted or unavailable. 139void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 140 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 141 142 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) { 143 // If the method was explicitly defaulted, point at that declaration. 144 if (!Method->isImplicit()) 145 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 146 147 // Try to diagnose why this special member function was implicitly 148 // deleted. This might fail, if that reason no longer applies. 149 CXXSpecialMember CSM = getSpecialMember(Method); 150 if (CSM != CXXInvalid) 151 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true); 152 153 return; 154 } 155 156 Diag(Decl->getLocation(), diag::note_unavailable_here) 157 << 1 << Decl->isDeleted(); 158} 159 160/// \brief Determine whether a FunctionDecl was ever declared with an 161/// explicit storage class. 162static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 163 for (FunctionDecl::redecl_iterator I = D->redecls_begin(), 164 E = D->redecls_end(); 165 I != E; ++I) { 166 if (I->getStorageClassAsWritten() != SC_None) 167 return true; 168 } 169 return false; 170} 171 172/// \brief Check whether we're in an extern inline function and referring to a 173/// variable or function with internal linkage (C11 6.7.4p3). 174/// 175/// This is only a warning because we used to silently accept this code, but 176/// in many cases it will not behave correctly. This is not enabled in C++ mode 177/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 178/// and so while there may still be user mistakes, most of the time we can't 179/// prove that there are errors. 180static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 181 const NamedDecl *D, 182 SourceLocation Loc) { 183 // This is disabled under C++; there are too many ways for this to fire in 184 // contexts where the warning is a false positive, or where it is technically 185 // correct but benign. 186 if (S.getLangOpts().CPlusPlus) 187 return; 188 189 // Check if this is an inlined function or method. 190 FunctionDecl *Current = S.getCurFunctionDecl(); 191 if (!Current) 192 return; 193 if (!Current->isInlined()) 194 return; 195 if (Current->getLinkage() != ExternalLinkage) 196 return; 197 198 // Check if the decl has internal linkage. 199 if (D->getLinkage() != InternalLinkage) 200 return; 201 202 // Downgrade from ExtWarn to Extension if 203 // (1) the supposedly external inline function is in the main file, 204 // and probably won't be included anywhere else. 205 // (2) the thing we're referencing is a pure function. 206 // (3) the thing we're referencing is another inline function. 207 // This last can give us false negatives, but it's better than warning on 208 // wrappers for simple C library functions. 209 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 210 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc); 211 if (!DowngradeWarning && UsedFn) 212 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 213 214 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline 215 : diag::warn_internal_in_extern_inline) 216 << /*IsVar=*/!UsedFn << D; 217 218 // Suggest "static" on the inline function, if possible. 219 if (!hasAnyExplicitStorageClass(Current)) { 220 const FunctionDecl *FirstDecl = Current->getCanonicalDecl(); 221 SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin(); 222 S.Diag(DeclBegin, diag::note_convert_inline_to_static) 223 << Current << FixItHint::CreateInsertion(DeclBegin, "static "); 224 } 225 226 S.Diag(D->getCanonicalDecl()->getLocation(), 227 diag::note_internal_decl_declared_here) 228 << D; 229} 230 231/// \brief Determine whether the use of this declaration is valid, and 232/// emit any corresponding diagnostics. 233/// 234/// This routine diagnoses various problems with referencing 235/// declarations that can occur when using a declaration. For example, 236/// it might warn if a deprecated or unavailable declaration is being 237/// used, or produce an error (and return true) if a C++0x deleted 238/// function is being used. 239/// 240/// \returns true if there was an error (this declaration cannot be 241/// referenced), false otherwise. 242/// 243bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 244 const ObjCInterfaceDecl *UnknownObjCClass) { 245 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 246 // If there were any diagnostics suppressed by template argument deduction, 247 // emit them now. 248 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator 249 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 250 if (Pos != SuppressedDiagnostics.end()) { 251 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second; 252 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I) 253 Diag(Suppressed[I].first, Suppressed[I].second); 254 255 // Clear out the list of suppressed diagnostics, so that we don't emit 256 // them again for this specialization. However, we don't obsolete this 257 // entry from the table, because we want to avoid ever emitting these 258 // diagnostics again. 259 Suppressed.clear(); 260 } 261 } 262 263 // See if this is an auto-typed variable whose initializer we are parsing. 264 if (ParsingInitForAutoVars.count(D)) { 265 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 266 << D->getDeclName(); 267 return true; 268 } 269 270 // See if this is a deleted function. 271 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 272 if (FD->isDeleted()) { 273 Diag(Loc, diag::err_deleted_function_use); 274 NoteDeletedFunction(FD); 275 return true; 276 } 277 } 278 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass); 279 280 DiagnoseUnusedOfDecl(*this, D, Loc); 281 282 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 283 284 return false; 285} 286 287/// \brief Retrieve the message suffix that should be added to a 288/// diagnostic complaining about the given function being deleted or 289/// unavailable. 290std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 291 // FIXME: C++0x implicitly-deleted special member functions could be 292 // detected here so that we could improve diagnostics to say, e.g., 293 // "base class 'A' had a deleted copy constructor". 294 if (FD->isDeleted()) 295 return std::string(); 296 297 std::string Message; 298 if (FD->getAvailability(&Message)) 299 return ": " + Message; 300 301 return std::string(); 302} 303 304/// DiagnoseSentinelCalls - This routine checks whether a call or 305/// message-send is to a declaration with the sentinel attribute, and 306/// if so, it checks that the requirements of the sentinel are 307/// satisfied. 308void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 309 Expr **args, unsigned numArgs) { 310 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 311 if (!attr) 312 return; 313 314 // The number of formal parameters of the declaration. 315 unsigned numFormalParams; 316 317 // The kind of declaration. This is also an index into a %select in 318 // the diagnostic. 319 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 320 321 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 322 numFormalParams = MD->param_size(); 323 calleeType = CT_Method; 324 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 325 numFormalParams = FD->param_size(); 326 calleeType = CT_Function; 327 } else if (isa<VarDecl>(D)) { 328 QualType type = cast<ValueDecl>(D)->getType(); 329 const FunctionType *fn = 0; 330 if (const PointerType *ptr = type->getAs<PointerType>()) { 331 fn = ptr->getPointeeType()->getAs<FunctionType>(); 332 if (!fn) return; 333 calleeType = CT_Function; 334 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 335 fn = ptr->getPointeeType()->castAs<FunctionType>(); 336 calleeType = CT_Block; 337 } else { 338 return; 339 } 340 341 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 342 numFormalParams = proto->getNumArgs(); 343 } else { 344 numFormalParams = 0; 345 } 346 } else { 347 return; 348 } 349 350 // "nullPos" is the number of formal parameters at the end which 351 // effectively count as part of the variadic arguments. This is 352 // useful if you would prefer to not have *any* formal parameters, 353 // but the language forces you to have at least one. 354 unsigned nullPos = attr->getNullPos(); 355 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 356 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 357 358 // The number of arguments which should follow the sentinel. 359 unsigned numArgsAfterSentinel = attr->getSentinel(); 360 361 // If there aren't enough arguments for all the formal parameters, 362 // the sentinel, and the args after the sentinel, complain. 363 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) { 364 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 365 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType; 366 return; 367 } 368 369 // Otherwise, find the sentinel expression. 370 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1]; 371 if (!sentinelExpr) return; 372 if (sentinelExpr->isValueDependent()) return; 373 if (Context.isSentinelNullExpr(sentinelExpr)) return; 374 375 // Pick a reasonable string to insert. Optimistically use 'nil' or 376 // 'NULL' if those are actually defined in the context. Only use 377 // 'nil' for ObjC methods, where it's much more likely that the 378 // variadic arguments form a list of object pointers. 379 SourceLocation MissingNilLoc 380 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd()); 381 std::string NullValue; 382 if (calleeType == CT_Method && 383 PP.getIdentifierInfo("nil")->hasMacroDefinition()) 384 NullValue = "nil"; 385 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition()) 386 NullValue = "NULL"; 387 else 388 NullValue = "(void*) 0"; 389 390 if (MissingNilLoc.isInvalid()) 391 Diag(Loc, diag::warn_missing_sentinel) << calleeType; 392 else 393 Diag(MissingNilLoc, diag::warn_missing_sentinel) 394 << calleeType 395 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 396 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType; 397} 398 399SourceRange Sema::getExprRange(Expr *E) const { 400 return E ? E->getSourceRange() : SourceRange(); 401} 402 403//===----------------------------------------------------------------------===// 404// Standard Promotions and Conversions 405//===----------------------------------------------------------------------===// 406 407/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 408ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) { 409 // Handle any placeholder expressions which made it here. 410 if (E->getType()->isPlaceholderType()) { 411 ExprResult result = CheckPlaceholderExpr(E); 412 if (result.isInvalid()) return ExprError(); 413 E = result.take(); 414 } 415 416 QualType Ty = E->getType(); 417 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 418 419 if (Ty->isFunctionType()) 420 E = ImpCastExprToType(E, Context.getPointerType(Ty), 421 CK_FunctionToPointerDecay).take(); 422 else if (Ty->isArrayType()) { 423 // In C90 mode, arrays only promote to pointers if the array expression is 424 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 425 // type 'array of type' is converted to an expression that has type 'pointer 426 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 427 // that has type 'array of type' ...". The relevant change is "an lvalue" 428 // (C90) to "an expression" (C99). 429 // 430 // C++ 4.2p1: 431 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 432 // T" can be converted to an rvalue of type "pointer to T". 433 // 434 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 435 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 436 CK_ArrayToPointerDecay).take(); 437 } 438 return Owned(E); 439} 440 441static void CheckForNullPointerDereference(Sema &S, Expr *E) { 442 // Check to see if we are dereferencing a null pointer. If so, 443 // and if not volatile-qualified, this is undefined behavior that the 444 // optimizer will delete, so warn about it. People sometimes try to use this 445 // to get a deterministic trap and are surprised by clang's behavior. This 446 // only handles the pattern "*null", which is a very syntactic check. 447 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 448 if (UO->getOpcode() == UO_Deref && 449 UO->getSubExpr()->IgnoreParenCasts()-> 450 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 451 !UO->getType().isVolatileQualified()) { 452 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 453 S.PDiag(diag::warn_indirection_through_null) 454 << UO->getSubExpr()->getSourceRange()); 455 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 456 S.PDiag(diag::note_indirection_through_null)); 457 } 458} 459 460ExprResult Sema::DefaultLvalueConversion(Expr *E) { 461 // Handle any placeholder expressions which made it here. 462 if (E->getType()->isPlaceholderType()) { 463 ExprResult result = CheckPlaceholderExpr(E); 464 if (result.isInvalid()) return ExprError(); 465 E = result.take(); 466 } 467 468 // C++ [conv.lval]p1: 469 // A glvalue of a non-function, non-array type T can be 470 // converted to a prvalue. 471 if (!E->isGLValue()) return Owned(E); 472 473 QualType T = E->getType(); 474 assert(!T.isNull() && "r-value conversion on typeless expression?"); 475 476 // We don't want to throw lvalue-to-rvalue casts on top of 477 // expressions of certain types in C++. 478 if (getLangOpts().CPlusPlus && 479 (E->getType() == Context.OverloadTy || 480 T->isDependentType() || 481 T->isRecordType())) 482 return Owned(E); 483 484 // The C standard is actually really unclear on this point, and 485 // DR106 tells us what the result should be but not why. It's 486 // generally best to say that void types just doesn't undergo 487 // lvalue-to-rvalue at all. Note that expressions of unqualified 488 // 'void' type are never l-values, but qualified void can be. 489 if (T->isVoidType()) 490 return Owned(E); 491 492 CheckForNullPointerDereference(*this, E); 493 494 // C++ [conv.lval]p1: 495 // [...] If T is a non-class type, the type of the prvalue is the 496 // cv-unqualified version of T. Otherwise, the type of the 497 // rvalue is T. 498 // 499 // C99 6.3.2.1p2: 500 // If the lvalue has qualified type, the value has the unqualified 501 // version of the type of the lvalue; otherwise, the value has the 502 // type of the lvalue. 503 if (T.hasQualifiers()) 504 T = T.getUnqualifiedType(); 505 506 UpdateMarkingForLValueToRValue(E); 507 508 // Loading a __weak object implicitly retains the value, so we need a cleanup to 509 // balance that. 510 if (getLangOpts().ObjCAutoRefCount && 511 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 512 ExprNeedsCleanups = true; 513 514 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, 515 E, 0, VK_RValue)); 516 517 // C11 6.3.2.1p2: 518 // ... if the lvalue has atomic type, the value has the non-atomic version 519 // of the type of the lvalue ... 520 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 521 T = Atomic->getValueType().getUnqualifiedType(); 522 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, 523 Res.get(), 0, VK_RValue)); 524 } 525 526 return Res; 527} 528 529ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 530 ExprResult Res = DefaultFunctionArrayConversion(E); 531 if (Res.isInvalid()) 532 return ExprError(); 533 Res = DefaultLvalueConversion(Res.take()); 534 if (Res.isInvalid()) 535 return ExprError(); 536 return Res; 537} 538 539 540/// UsualUnaryConversions - Performs various conversions that are common to most 541/// operators (C99 6.3). The conversions of array and function types are 542/// sometimes suppressed. For example, the array->pointer conversion doesn't 543/// apply if the array is an argument to the sizeof or address (&) operators. 544/// In these instances, this routine should *not* be called. 545ExprResult Sema::UsualUnaryConversions(Expr *E) { 546 // First, convert to an r-value. 547 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 548 if (Res.isInvalid()) 549 return Owned(E); 550 E = Res.take(); 551 552 QualType Ty = E->getType(); 553 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 554 555 // Half FP is a bit different: it's a storage-only type, meaning that any 556 // "use" of it should be promoted to float. 557 if (Ty->isHalfType()) 558 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast); 559 560 // Try to perform integral promotions if the object has a theoretically 561 // promotable type. 562 if (Ty->isIntegralOrUnscopedEnumerationType()) { 563 // C99 6.3.1.1p2: 564 // 565 // The following may be used in an expression wherever an int or 566 // unsigned int may be used: 567 // - an object or expression with an integer type whose integer 568 // conversion rank is less than or equal to the rank of int 569 // and unsigned int. 570 // - A bit-field of type _Bool, int, signed int, or unsigned int. 571 // 572 // If an int can represent all values of the original type, the 573 // value is converted to an int; otherwise, it is converted to an 574 // unsigned int. These are called the integer promotions. All 575 // other types are unchanged by the integer promotions. 576 577 QualType PTy = Context.isPromotableBitField(E); 578 if (!PTy.isNull()) { 579 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take(); 580 return Owned(E); 581 } 582 if (Ty->isPromotableIntegerType()) { 583 QualType PT = Context.getPromotedIntegerType(Ty); 584 E = ImpCastExprToType(E, PT, CK_IntegralCast).take(); 585 return Owned(E); 586 } 587 } 588 return Owned(E); 589} 590 591/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 592/// do not have a prototype. Arguments that have type float are promoted to 593/// double. All other argument types are converted by UsualUnaryConversions(). 594ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 595 QualType Ty = E->getType(); 596 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 597 598 ExprResult Res = UsualUnaryConversions(E); 599 if (Res.isInvalid()) 600 return Owned(E); 601 E = Res.take(); 602 603 // If this is a 'float' (CVR qualified or typedef) promote to double. 604 if (Ty->isSpecificBuiltinType(BuiltinType::Float)) 605 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take(); 606 607 // C++ performs lvalue-to-rvalue conversion as a default argument 608 // promotion, even on class types, but note: 609 // C++11 [conv.lval]p2: 610 // When an lvalue-to-rvalue conversion occurs in an unevaluated 611 // operand or a subexpression thereof the value contained in the 612 // referenced object is not accessed. Otherwise, if the glvalue 613 // has a class type, the conversion copy-initializes a temporary 614 // of type T from the glvalue and the result of the conversion 615 // is a prvalue for the temporary. 616 // FIXME: add some way to gate this entire thing for correctness in 617 // potentially potentially evaluated contexts. 618 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 619 ExprResult Temp = PerformCopyInitialization( 620 InitializedEntity::InitializeTemporary(E->getType()), 621 E->getExprLoc(), 622 Owned(E)); 623 if (Temp.isInvalid()) 624 return ExprError(); 625 E = Temp.get(); 626 } 627 628 return Owned(E); 629} 630 631/// Determine the degree of POD-ness for an expression. 632/// Incomplete types are considered POD, since this check can be performed 633/// when we're in an unevaluated context. 634Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 635 if (Ty->isIncompleteType()) { 636 if (Ty->isObjCObjectType()) 637 return VAK_Invalid; 638 return VAK_Valid; 639 } 640 641 if (Ty.isCXX98PODType(Context)) 642 return VAK_Valid; 643 644 // C++11 [expr.call]p7: 645 // Passing a potentially-evaluated argument of class type (Clause 9) 646 // having a non-trivial copy constructor, a non-trivial move constructor, 647 // or a non-trivial destructor, with no corresponding parameter, 648 // is conditionally-supported with implementation-defined semantics. 649 if (getLangOpts().CPlusPlus0x && !Ty->isDependentType()) 650 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 651 if (!Record->hasNonTrivialCopyConstructor() && 652 !Record->hasNonTrivialMoveConstructor() && 653 !Record->hasNonTrivialDestructor()) 654 return VAK_ValidInCXX11; 655 656 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 657 return VAK_Valid; 658 return VAK_Invalid; 659} 660 661bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) { 662 // Don't allow one to pass an Objective-C interface to a vararg. 663 const QualType & Ty = E->getType(); 664 665 // Complain about passing non-POD types through varargs. 666 switch (isValidVarArgType(Ty)) { 667 case VAK_Valid: 668 break; 669 case VAK_ValidInCXX11: 670 DiagRuntimeBehavior(E->getLocStart(), 0, 671 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 672 << E->getType() << CT); 673 break; 674 case VAK_Invalid: { 675 if (Ty->isObjCObjectType()) 676 return DiagRuntimeBehavior(E->getLocStart(), 0, 677 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 678 << Ty << CT); 679 680 return DiagRuntimeBehavior(E->getLocStart(), 0, 681 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 682 << getLangOpts().CPlusPlus0x << Ty << CT); 683 } 684 } 685 // c++ rules are enforced elsewhere. 686 return false; 687} 688 689/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 690/// will create a trap if the resulting type is not a POD type. 691ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 692 FunctionDecl *FDecl) { 693 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 694 // Strip the unbridged-cast placeholder expression off, if applicable. 695 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 696 (CT == VariadicMethod || 697 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 698 E = stripARCUnbridgedCast(E); 699 700 // Otherwise, do normal placeholder checking. 701 } else { 702 ExprResult ExprRes = CheckPlaceholderExpr(E); 703 if (ExprRes.isInvalid()) 704 return ExprError(); 705 E = ExprRes.take(); 706 } 707 } 708 709 ExprResult ExprRes = DefaultArgumentPromotion(E); 710 if (ExprRes.isInvalid()) 711 return ExprError(); 712 E = ExprRes.take(); 713 714 // Diagnostics regarding non-POD argument types are 715 // emitted along with format string checking in Sema::CheckFunctionCall(). 716 if (isValidVarArgType(E->getType()) == VAK_Invalid) { 717 // Turn this into a trap. 718 CXXScopeSpec SS; 719 SourceLocation TemplateKWLoc; 720 UnqualifiedId Name; 721 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 722 E->getLocStart()); 723 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 724 Name, true, false); 725 if (TrapFn.isInvalid()) 726 return ExprError(); 727 728 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 729 E->getLocStart(), MultiExprArg(), 730 E->getLocEnd()); 731 if (Call.isInvalid()) 732 return ExprError(); 733 734 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 735 Call.get(), E); 736 if (Comma.isInvalid()) 737 return ExprError(); 738 return Comma.get(); 739 } 740 741 if (!getLangOpts().CPlusPlus && 742 RequireCompleteType(E->getExprLoc(), E->getType(), 743 diag::err_call_incomplete_argument)) 744 return ExprError(); 745 746 return Owned(E); 747} 748 749/// \brief Converts an integer to complex float type. Helper function of 750/// UsualArithmeticConversions() 751/// 752/// \return false if the integer expression is an integer type and is 753/// successfully converted to the complex type. 754static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 755 ExprResult &ComplexExpr, 756 QualType IntTy, 757 QualType ComplexTy, 758 bool SkipCast) { 759 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 760 if (SkipCast) return false; 761 if (IntTy->isIntegerType()) { 762 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 763 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating); 764 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 765 CK_FloatingRealToComplex); 766 } else { 767 assert(IntTy->isComplexIntegerType()); 768 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 769 CK_IntegralComplexToFloatingComplex); 770 } 771 return false; 772} 773 774/// \brief Takes two complex float types and converts them to the same type. 775/// Helper function of UsualArithmeticConversions() 776static QualType 777handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS, 778 ExprResult &RHS, QualType LHSType, 779 QualType RHSType, 780 bool IsCompAssign) { 781 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 782 783 if (order < 0) { 784 // _Complex float -> _Complex double 785 if (!IsCompAssign) 786 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast); 787 return RHSType; 788 } 789 if (order > 0) 790 // _Complex float -> _Complex double 791 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast); 792 return LHSType; 793} 794 795/// \brief Converts otherExpr to complex float and promotes complexExpr if 796/// necessary. Helper function of UsualArithmeticConversions() 797static QualType handleOtherComplexFloatConversion(Sema &S, 798 ExprResult &ComplexExpr, 799 ExprResult &OtherExpr, 800 QualType ComplexTy, 801 QualType OtherTy, 802 bool ConvertComplexExpr, 803 bool ConvertOtherExpr) { 804 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy); 805 806 // If just the complexExpr is complex, the otherExpr needs to be converted, 807 // and the complexExpr might need to be promoted. 808 if (order > 0) { // complexExpr is wider 809 // float -> _Complex double 810 if (ConvertOtherExpr) { 811 QualType fp = cast<ComplexType>(ComplexTy)->getElementType(); 812 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast); 813 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy, 814 CK_FloatingRealToComplex); 815 } 816 return ComplexTy; 817 } 818 819 // otherTy is at least as wide. Find its corresponding complex type. 820 QualType result = (order == 0 ? ComplexTy : 821 S.Context.getComplexType(OtherTy)); 822 823 // double -> _Complex double 824 if (ConvertOtherExpr) 825 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result, 826 CK_FloatingRealToComplex); 827 828 // _Complex float -> _Complex double 829 if (ConvertComplexExpr && order < 0) 830 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result, 831 CK_FloatingComplexCast); 832 833 return result; 834} 835 836/// \brief Handle arithmetic conversion with complex types. Helper function of 837/// UsualArithmeticConversions() 838static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 839 ExprResult &RHS, QualType LHSType, 840 QualType RHSType, 841 bool IsCompAssign) { 842 // if we have an integer operand, the result is the complex type. 843 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 844 /*skipCast*/false)) 845 return LHSType; 846 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 847 /*skipCast*/IsCompAssign)) 848 return RHSType; 849 850 // This handles complex/complex, complex/float, or float/complex. 851 // When both operands are complex, the shorter operand is converted to the 852 // type of the longer, and that is the type of the result. This corresponds 853 // to what is done when combining two real floating-point operands. 854 // The fun begins when size promotion occur across type domains. 855 // From H&S 6.3.4: When one operand is complex and the other is a real 856 // floating-point type, the less precise type is converted, within it's 857 // real or complex domain, to the precision of the other type. For example, 858 // when combining a "long double" with a "double _Complex", the 859 // "double _Complex" is promoted to "long double _Complex". 860 861 bool LHSComplexFloat = LHSType->isComplexType(); 862 bool RHSComplexFloat = RHSType->isComplexType(); 863 864 // If both are complex, just cast to the more precise type. 865 if (LHSComplexFloat && RHSComplexFloat) 866 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS, 867 LHSType, RHSType, 868 IsCompAssign); 869 870 // If only one operand is complex, promote it if necessary and convert the 871 // other operand to complex. 872 if (LHSComplexFloat) 873 return handleOtherComplexFloatConversion( 874 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign, 875 /*convertOtherExpr*/ true); 876 877 assert(RHSComplexFloat); 878 return handleOtherComplexFloatConversion( 879 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true, 880 /*convertOtherExpr*/ !IsCompAssign); 881} 882 883/// \brief Hande arithmetic conversion from integer to float. Helper function 884/// of UsualArithmeticConversions() 885static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 886 ExprResult &IntExpr, 887 QualType FloatTy, QualType IntTy, 888 bool ConvertFloat, bool ConvertInt) { 889 if (IntTy->isIntegerType()) { 890 if (ConvertInt) 891 // Convert intExpr to the lhs floating point type. 892 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy, 893 CK_IntegralToFloating); 894 return FloatTy; 895 } 896 897 // Convert both sides to the appropriate complex float. 898 assert(IntTy->isComplexIntegerType()); 899 QualType result = S.Context.getComplexType(FloatTy); 900 901 // _Complex int -> _Complex float 902 if (ConvertInt) 903 IntExpr = S.ImpCastExprToType(IntExpr.take(), result, 904 CK_IntegralComplexToFloatingComplex); 905 906 // float -> _Complex float 907 if (ConvertFloat) 908 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result, 909 CK_FloatingRealToComplex); 910 911 return result; 912} 913 914/// \brief Handle arithmethic conversion with floating point types. Helper 915/// function of UsualArithmeticConversions() 916static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 917 ExprResult &RHS, QualType LHSType, 918 QualType RHSType, bool IsCompAssign) { 919 bool LHSFloat = LHSType->isRealFloatingType(); 920 bool RHSFloat = RHSType->isRealFloatingType(); 921 922 // If we have two real floating types, convert the smaller operand 923 // to the bigger result. 924 if (LHSFloat && RHSFloat) { 925 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 926 if (order > 0) { 927 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast); 928 return LHSType; 929 } 930 931 assert(order < 0 && "illegal float comparison"); 932 if (!IsCompAssign) 933 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast); 934 return RHSType; 935 } 936 937 if (LHSFloat) 938 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 939 /*convertFloat=*/!IsCompAssign, 940 /*convertInt=*/ true); 941 assert(RHSFloat); 942 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 943 /*convertInt=*/ true, 944 /*convertFloat=*/!IsCompAssign); 945} 946 947/// \brief Handle conversions with GCC complex int extension. Helper function 948/// of UsualArithmeticConversions() 949// FIXME: if the operands are (int, _Complex long), we currently 950// don't promote the complex. Also, signedness? 951static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 952 ExprResult &RHS, QualType LHSType, 953 QualType RHSType, 954 bool IsCompAssign) { 955 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 956 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 957 958 if (LHSComplexInt && RHSComplexInt) { 959 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(), 960 RHSComplexInt->getElementType()); 961 assert(order && "inequal types with equal element ordering"); 962 if (order > 0) { 963 // _Complex int -> _Complex long 964 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast); 965 return LHSType; 966 } 967 968 if (!IsCompAssign) 969 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast); 970 return RHSType; 971 } 972 973 if (LHSComplexInt) { 974 // int -> _Complex int 975 // FIXME: This needs to take integer ranks into account 976 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(), 977 CK_IntegralCast); 978 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex); 979 return LHSType; 980 } 981 982 assert(RHSComplexInt); 983 // int -> _Complex int 984 // FIXME: This needs to take integer ranks into account 985 if (!IsCompAssign) { 986 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(), 987 CK_IntegralCast); 988 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex); 989 } 990 return RHSType; 991} 992 993/// \brief Handle integer arithmetic conversions. Helper function of 994/// UsualArithmeticConversions() 995static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 996 ExprResult &RHS, QualType LHSType, 997 QualType RHSType, bool IsCompAssign) { 998 // The rules for this case are in C99 6.3.1.8 999 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1000 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1001 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1002 if (LHSSigned == RHSSigned) { 1003 // Same signedness; use the higher-ranked type 1004 if (order >= 0) { 1005 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast); 1006 return LHSType; 1007 } else if (!IsCompAssign) 1008 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast); 1009 return RHSType; 1010 } else if (order != (LHSSigned ? 1 : -1)) { 1011 // The unsigned type has greater than or equal rank to the 1012 // signed type, so use the unsigned type 1013 if (RHSSigned) { 1014 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast); 1015 return LHSType; 1016 } else if (!IsCompAssign) 1017 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast); 1018 return RHSType; 1019 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1020 // The two types are different widths; if we are here, that 1021 // means the signed type is larger than the unsigned type, so 1022 // use the signed type. 1023 if (LHSSigned) { 1024 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast); 1025 return LHSType; 1026 } else if (!IsCompAssign) 1027 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast); 1028 return RHSType; 1029 } else { 1030 // The signed type is higher-ranked than the unsigned type, 1031 // but isn't actually any bigger (like unsigned int and long 1032 // on most 32-bit systems). Use the unsigned type corresponding 1033 // to the signed type. 1034 QualType result = 1035 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1036 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast); 1037 if (!IsCompAssign) 1038 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast); 1039 return result; 1040 } 1041} 1042 1043/// UsualArithmeticConversions - Performs various conversions that are common to 1044/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1045/// routine returns the first non-arithmetic type found. The client is 1046/// responsible for emitting appropriate error diagnostics. 1047/// FIXME: verify the conversion rules for "complex int" are consistent with 1048/// GCC. 1049QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1050 bool IsCompAssign) { 1051 if (!IsCompAssign) { 1052 LHS = UsualUnaryConversions(LHS.take()); 1053 if (LHS.isInvalid()) 1054 return QualType(); 1055 } 1056 1057 RHS = UsualUnaryConversions(RHS.take()); 1058 if (RHS.isInvalid()) 1059 return QualType(); 1060 1061 // For conversion purposes, we ignore any qualifiers. 1062 // For example, "const float" and "float" are equivalent. 1063 QualType LHSType = 1064 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1065 QualType RHSType = 1066 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1067 1068 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1069 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1070 LHSType = AtomicLHS->getValueType(); 1071 1072 // If both types are identical, no conversion is needed. 1073 if (LHSType == RHSType) 1074 return LHSType; 1075 1076 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1077 // The caller can deal with this (e.g. pointer + int). 1078 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1079 return QualType(); 1080 1081 // Apply unary and bitfield promotions to the LHS's type. 1082 QualType LHSUnpromotedType = LHSType; 1083 if (LHSType->isPromotableIntegerType()) 1084 LHSType = Context.getPromotedIntegerType(LHSType); 1085 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1086 if (!LHSBitfieldPromoteTy.isNull()) 1087 LHSType = LHSBitfieldPromoteTy; 1088 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1089 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast); 1090 1091 // If both types are identical, no conversion is needed. 1092 if (LHSType == RHSType) 1093 return LHSType; 1094 1095 // At this point, we have two different arithmetic types. 1096 1097 // Handle complex types first (C99 6.3.1.8p1). 1098 if (LHSType->isComplexType() || RHSType->isComplexType()) 1099 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1100 IsCompAssign); 1101 1102 // Now handle "real" floating types (i.e. float, double, long double). 1103 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1104 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1105 IsCompAssign); 1106 1107 // Handle GCC complex int extension. 1108 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1109 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1110 IsCompAssign); 1111 1112 // Finally, we have two differing integer types. 1113 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType, 1114 IsCompAssign); 1115} 1116 1117//===----------------------------------------------------------------------===// 1118// Semantic Analysis for various Expression Types 1119//===----------------------------------------------------------------------===// 1120 1121 1122ExprResult 1123Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1124 SourceLocation DefaultLoc, 1125 SourceLocation RParenLoc, 1126 Expr *ControllingExpr, 1127 MultiTypeArg ArgTypes, 1128 MultiExprArg ArgExprs) { 1129 unsigned NumAssocs = ArgTypes.size(); 1130 assert(NumAssocs == ArgExprs.size()); 1131 1132 ParsedType *ParsedTypes = ArgTypes.data(); 1133 Expr **Exprs = ArgExprs.data(); 1134 1135 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1136 for (unsigned i = 0; i < NumAssocs; ++i) { 1137 if (ParsedTypes[i]) 1138 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]); 1139 else 1140 Types[i] = 0; 1141 } 1142 1143 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1144 ControllingExpr, Types, Exprs, 1145 NumAssocs); 1146 delete [] Types; 1147 return ER; 1148} 1149 1150ExprResult 1151Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1152 SourceLocation DefaultLoc, 1153 SourceLocation RParenLoc, 1154 Expr *ControllingExpr, 1155 TypeSourceInfo **Types, 1156 Expr **Exprs, 1157 unsigned NumAssocs) { 1158 bool TypeErrorFound = false, 1159 IsResultDependent = ControllingExpr->isTypeDependent(), 1160 ContainsUnexpandedParameterPack 1161 = ControllingExpr->containsUnexpandedParameterPack(); 1162 1163 for (unsigned i = 0; i < NumAssocs; ++i) { 1164 if (Exprs[i]->containsUnexpandedParameterPack()) 1165 ContainsUnexpandedParameterPack = true; 1166 1167 if (Types[i]) { 1168 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1169 ContainsUnexpandedParameterPack = true; 1170 1171 if (Types[i]->getType()->isDependentType()) { 1172 IsResultDependent = true; 1173 } else { 1174 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1175 // complete object type other than a variably modified type." 1176 unsigned D = 0; 1177 if (Types[i]->getType()->isIncompleteType()) 1178 D = diag::err_assoc_type_incomplete; 1179 else if (!Types[i]->getType()->isObjectType()) 1180 D = diag::err_assoc_type_nonobject; 1181 else if (Types[i]->getType()->isVariablyModifiedType()) 1182 D = diag::err_assoc_type_variably_modified; 1183 1184 if (D != 0) { 1185 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1186 << Types[i]->getTypeLoc().getSourceRange() 1187 << Types[i]->getType(); 1188 TypeErrorFound = true; 1189 } 1190 1191 // C11 6.5.1.1p2 "No two generic associations in the same generic 1192 // selection shall specify compatible types." 1193 for (unsigned j = i+1; j < NumAssocs; ++j) 1194 if (Types[j] && !Types[j]->getType()->isDependentType() && 1195 Context.typesAreCompatible(Types[i]->getType(), 1196 Types[j]->getType())) { 1197 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1198 diag::err_assoc_compatible_types) 1199 << Types[j]->getTypeLoc().getSourceRange() 1200 << Types[j]->getType() 1201 << Types[i]->getType(); 1202 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1203 diag::note_compat_assoc) 1204 << Types[i]->getTypeLoc().getSourceRange() 1205 << Types[i]->getType(); 1206 TypeErrorFound = true; 1207 } 1208 } 1209 } 1210 } 1211 if (TypeErrorFound) 1212 return ExprError(); 1213 1214 // If we determined that the generic selection is result-dependent, don't 1215 // try to compute the result expression. 1216 if (IsResultDependent) 1217 return Owned(new (Context) GenericSelectionExpr( 1218 Context, KeyLoc, ControllingExpr, 1219 llvm::makeArrayRef(Types, NumAssocs), 1220 llvm::makeArrayRef(Exprs, NumAssocs), 1221 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack)); 1222 1223 SmallVector<unsigned, 1> CompatIndices; 1224 unsigned DefaultIndex = -1U; 1225 for (unsigned i = 0; i < NumAssocs; ++i) { 1226 if (!Types[i]) 1227 DefaultIndex = i; 1228 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1229 Types[i]->getType())) 1230 CompatIndices.push_back(i); 1231 } 1232 1233 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1234 // type compatible with at most one of the types named in its generic 1235 // association list." 1236 if (CompatIndices.size() > 1) { 1237 // We strip parens here because the controlling expression is typically 1238 // parenthesized in macro definitions. 1239 ControllingExpr = ControllingExpr->IgnoreParens(); 1240 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1241 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1242 << (unsigned) CompatIndices.size(); 1243 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(), 1244 E = CompatIndices.end(); I != E; ++I) { 1245 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1246 diag::note_compat_assoc) 1247 << Types[*I]->getTypeLoc().getSourceRange() 1248 << Types[*I]->getType(); 1249 } 1250 return ExprError(); 1251 } 1252 1253 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1254 // its controlling expression shall have type compatible with exactly one of 1255 // the types named in its generic association list." 1256 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1257 // We strip parens here because the controlling expression is typically 1258 // parenthesized in macro definitions. 1259 ControllingExpr = ControllingExpr->IgnoreParens(); 1260 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1261 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1262 return ExprError(); 1263 } 1264 1265 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1266 // type name that is compatible with the type of the controlling expression, 1267 // then the result expression of the generic selection is the expression 1268 // in that generic association. Otherwise, the result expression of the 1269 // generic selection is the expression in the default generic association." 1270 unsigned ResultIndex = 1271 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1272 1273 return Owned(new (Context) GenericSelectionExpr( 1274 Context, KeyLoc, ControllingExpr, 1275 llvm::makeArrayRef(Types, NumAssocs), 1276 llvm::makeArrayRef(Exprs, NumAssocs), 1277 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack, 1278 ResultIndex)); 1279} 1280 1281/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1282/// location of the token and the offset of the ud-suffix within it. 1283static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1284 unsigned Offset) { 1285 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1286 S.getLangOpts()); 1287} 1288 1289/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1290/// the corresponding cooked (non-raw) literal operator, and build a call to it. 1291static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1292 IdentifierInfo *UDSuffix, 1293 SourceLocation UDSuffixLoc, 1294 ArrayRef<Expr*> Args, 1295 SourceLocation LitEndLoc) { 1296 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1297 1298 QualType ArgTy[2]; 1299 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1300 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1301 if (ArgTy[ArgIdx]->isArrayType()) 1302 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1303 } 1304 1305 DeclarationName OpName = 1306 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1307 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1308 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1309 1310 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1311 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1312 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error) 1313 return ExprError(); 1314 1315 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1316} 1317 1318/// ActOnStringLiteral - The specified tokens were lexed as pasted string 1319/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1320/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1321/// multiple tokens. However, the common case is that StringToks points to one 1322/// string. 1323/// 1324ExprResult 1325Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks, 1326 Scope *UDLScope) { 1327 assert(NumStringToks && "Must have at least one string!"); 1328 1329 StringLiteralParser Literal(StringToks, NumStringToks, PP); 1330 if (Literal.hadError) 1331 return ExprError(); 1332 1333 SmallVector<SourceLocation, 4> StringTokLocs; 1334 for (unsigned i = 0; i != NumStringToks; ++i) 1335 StringTokLocs.push_back(StringToks[i].getLocation()); 1336 1337 QualType StrTy = Context.CharTy; 1338 if (Literal.isWide()) 1339 StrTy = Context.getWCharType(); 1340 else if (Literal.isUTF16()) 1341 StrTy = Context.Char16Ty; 1342 else if (Literal.isUTF32()) 1343 StrTy = Context.Char32Ty; 1344 else if (Literal.isPascal()) 1345 StrTy = Context.UnsignedCharTy; 1346 1347 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1348 if (Literal.isWide()) 1349 Kind = StringLiteral::Wide; 1350 else if (Literal.isUTF8()) 1351 Kind = StringLiteral::UTF8; 1352 else if (Literal.isUTF16()) 1353 Kind = StringLiteral::UTF16; 1354 else if (Literal.isUTF32()) 1355 Kind = StringLiteral::UTF32; 1356 1357 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1358 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1359 StrTy.addConst(); 1360 1361 // Get an array type for the string, according to C99 6.4.5. This includes 1362 // the nul terminator character as well as the string length for pascal 1363 // strings. 1364 StrTy = Context.getConstantArrayType(StrTy, 1365 llvm::APInt(32, Literal.GetNumStringChars()+1), 1366 ArrayType::Normal, 0); 1367 1368 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1369 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1370 Kind, Literal.Pascal, StrTy, 1371 &StringTokLocs[0], 1372 StringTokLocs.size()); 1373 if (Literal.getUDSuffix().empty()) 1374 return Owned(Lit); 1375 1376 // We're building a user-defined literal. 1377 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1378 SourceLocation UDSuffixLoc = 1379 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1380 Literal.getUDSuffixOffset()); 1381 1382 // Make sure we're allowed user-defined literals here. 1383 if (!UDLScope) 1384 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1385 1386 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1387 // operator "" X (str, len) 1388 QualType SizeType = Context.getSizeType(); 1389 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1390 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1391 StringTokLocs[0]); 1392 Expr *Args[] = { Lit, LenArg }; 1393 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 1394 Args, StringTokLocs.back()); 1395} 1396 1397ExprResult 1398Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1399 SourceLocation Loc, 1400 const CXXScopeSpec *SS) { 1401 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1402 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1403} 1404 1405/// BuildDeclRefExpr - Build an expression that references a 1406/// declaration that does not require a closure capture. 1407ExprResult 1408Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1409 const DeclarationNameInfo &NameInfo, 1410 const CXXScopeSpec *SS) { 1411 if (getLangOpts().CUDA) 1412 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1413 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1414 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller), 1415 CalleeTarget = IdentifyCUDATarget(Callee); 1416 if (CheckCUDATarget(CallerTarget, CalleeTarget)) { 1417 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1418 << CalleeTarget << D->getIdentifier() << CallerTarget; 1419 Diag(D->getLocation(), diag::note_previous_decl) 1420 << D->getIdentifier(); 1421 return ExprError(); 1422 } 1423 } 1424 1425 bool refersToEnclosingScope = 1426 (CurContext != D->getDeclContext() && 1427 D->getDeclContext()->isFunctionOrMethod()); 1428 1429 DeclRefExpr *E = DeclRefExpr::Create(Context, 1430 SS ? SS->getWithLocInContext(Context) 1431 : NestedNameSpecifierLoc(), 1432 SourceLocation(), 1433 D, refersToEnclosingScope, 1434 NameInfo, Ty, VK); 1435 1436 MarkDeclRefReferenced(E); 1437 1438 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) && 1439 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) { 1440 DiagnosticsEngine::Level Level = 1441 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 1442 E->getLocStart()); 1443 if (Level != DiagnosticsEngine::Ignored) 1444 getCurFunction()->recordUseOfWeak(E); 1445 } 1446 1447 // Just in case we're building an illegal pointer-to-member. 1448 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1449 if (FD && FD->isBitField()) 1450 E->setObjectKind(OK_BitField); 1451 1452 return Owned(E); 1453} 1454 1455/// Decomposes the given name into a DeclarationNameInfo, its location, and 1456/// possibly a list of template arguments. 1457/// 1458/// If this produces template arguments, it is permitted to call 1459/// DecomposeTemplateName. 1460/// 1461/// This actually loses a lot of source location information for 1462/// non-standard name kinds; we should consider preserving that in 1463/// some way. 1464void 1465Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1466 TemplateArgumentListInfo &Buffer, 1467 DeclarationNameInfo &NameInfo, 1468 const TemplateArgumentListInfo *&TemplateArgs) { 1469 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1470 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1471 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1472 1473 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1474 Id.TemplateId->NumArgs); 1475 translateTemplateArguments(TemplateArgsPtr, Buffer); 1476 1477 TemplateName TName = Id.TemplateId->Template.get(); 1478 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1479 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1480 TemplateArgs = &Buffer; 1481 } else { 1482 NameInfo = GetNameFromUnqualifiedId(Id); 1483 TemplateArgs = 0; 1484 } 1485} 1486 1487/// Diagnose an empty lookup. 1488/// 1489/// \return false if new lookup candidates were found 1490bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1491 CorrectionCandidateCallback &CCC, 1492 TemplateArgumentListInfo *ExplicitTemplateArgs, 1493 llvm::ArrayRef<Expr *> Args) { 1494 DeclarationName Name = R.getLookupName(); 1495 1496 unsigned diagnostic = diag::err_undeclared_var_use; 1497 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1498 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1499 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1500 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1501 diagnostic = diag::err_undeclared_use; 1502 diagnostic_suggest = diag::err_undeclared_use_suggest; 1503 } 1504 1505 // If the original lookup was an unqualified lookup, fake an 1506 // unqualified lookup. This is useful when (for example) the 1507 // original lookup would not have found something because it was a 1508 // dependent name. 1509 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty()) 1510 ? CurContext : 0; 1511 while (DC) { 1512 if (isa<CXXRecordDecl>(DC)) { 1513 LookupQualifiedName(R, DC); 1514 1515 if (!R.empty()) { 1516 // Don't give errors about ambiguities in this lookup. 1517 R.suppressDiagnostics(); 1518 1519 // During a default argument instantiation the CurContext points 1520 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1521 // function parameter list, hence add an explicit check. 1522 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1523 ActiveTemplateInstantiations.back().Kind == 1524 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1525 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1526 bool isInstance = CurMethod && 1527 CurMethod->isInstance() && 1528 DC == CurMethod->getParent() && !isDefaultArgument; 1529 1530 1531 // Give a code modification hint to insert 'this->'. 1532 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1533 // Actually quite difficult! 1534 if (getLangOpts().MicrosoftMode) 1535 diagnostic = diag::warn_found_via_dependent_bases_lookup; 1536 if (isInstance) { 1537 Diag(R.getNameLoc(), diagnostic) << Name 1538 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1539 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 1540 CallsUndergoingInstantiation.back()->getCallee()); 1541 1542 1543 CXXMethodDecl *DepMethod; 1544 if (CurMethod->getTemplatedKind() == 1545 FunctionDecl::TK_FunctionTemplateSpecialization) 1546 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()-> 1547 getInstantiatedFromMemberTemplate()->getTemplatedDecl()); 1548 else 1549 DepMethod = cast<CXXMethodDecl>( 1550 CurMethod->getInstantiatedFromMemberFunction()); 1551 assert(DepMethod && "No template pattern found"); 1552 1553 QualType DepThisType = DepMethod->getThisType(Context); 1554 CheckCXXThisCapture(R.getNameLoc()); 1555 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 1556 R.getNameLoc(), DepThisType, false); 1557 TemplateArgumentListInfo TList; 1558 if (ULE->hasExplicitTemplateArgs()) 1559 ULE->copyTemplateArgumentsInto(TList); 1560 1561 CXXScopeSpec SS; 1562 SS.Adopt(ULE->getQualifierLoc()); 1563 CXXDependentScopeMemberExpr *DepExpr = 1564 CXXDependentScopeMemberExpr::Create( 1565 Context, DepThis, DepThisType, true, SourceLocation(), 1566 SS.getWithLocInContext(Context), 1567 ULE->getTemplateKeywordLoc(), 0, 1568 R.getLookupNameInfo(), 1569 ULE->hasExplicitTemplateArgs() ? &TList : 0); 1570 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 1571 } else { 1572 Diag(R.getNameLoc(), diagnostic) << Name; 1573 } 1574 1575 // Do we really want to note all of these? 1576 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1577 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1578 1579 // Return true if we are inside a default argument instantiation 1580 // and the found name refers to an instance member function, otherwise 1581 // the function calling DiagnoseEmptyLookup will try to create an 1582 // implicit member call and this is wrong for default argument. 1583 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1584 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1585 return true; 1586 } 1587 1588 // Tell the callee to try to recover. 1589 return false; 1590 } 1591 1592 R.clear(); 1593 } 1594 1595 // In Microsoft mode, if we are performing lookup from within a friend 1596 // function definition declared at class scope then we must set 1597 // DC to the lexical parent to be able to search into the parent 1598 // class. 1599 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) && 1600 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1601 DC->getLexicalParent()->isRecord()) 1602 DC = DC->getLexicalParent(); 1603 else 1604 DC = DC->getParent(); 1605 } 1606 1607 // We didn't find anything, so try to correct for a typo. 1608 TypoCorrection Corrected; 1609 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 1610 S, &SS, CCC))) { 1611 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1612 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts())); 1613 R.setLookupName(Corrected.getCorrection()); 1614 1615 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 1616 if (Corrected.isOverloaded()) { 1617 OverloadCandidateSet OCS(R.getNameLoc()); 1618 OverloadCandidateSet::iterator Best; 1619 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1620 CDEnd = Corrected.end(); 1621 CD != CDEnd; ++CD) { 1622 if (FunctionTemplateDecl *FTD = 1623 dyn_cast<FunctionTemplateDecl>(*CD)) 1624 AddTemplateOverloadCandidate( 1625 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1626 Args, OCS); 1627 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1628 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1629 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1630 Args, OCS); 1631 } 1632 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1633 case OR_Success: 1634 ND = Best->Function; 1635 break; 1636 default: 1637 break; 1638 } 1639 } 1640 R.addDecl(ND); 1641 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 1642 if (SS.isEmpty()) 1643 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr 1644 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1645 else 1646 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1647 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1648 << SS.getRange() 1649 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(), 1650 CorrectedStr); 1651 if (ND) 1652 Diag(ND->getLocation(), diag::note_previous_decl) 1653 << CorrectedQuotedStr; 1654 1655 // Tell the callee to try to recover. 1656 return false; 1657 } 1658 1659 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) { 1660 // FIXME: If we ended up with a typo for a type name or 1661 // Objective-C class name, we're in trouble because the parser 1662 // is in the wrong place to recover. Suggest the typo 1663 // correction, but don't make it a fix-it since we're not going 1664 // to recover well anyway. 1665 if (SS.isEmpty()) 1666 Diag(R.getNameLoc(), diagnostic_suggest) 1667 << Name << CorrectedQuotedStr; 1668 else 1669 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1670 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1671 << SS.getRange(); 1672 1673 // Don't try to recover; it won't work. 1674 return true; 1675 } 1676 } else { 1677 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1678 // because we aren't able to recover. 1679 if (SS.isEmpty()) 1680 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr; 1681 else 1682 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1683 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 1684 << SS.getRange(); 1685 return true; 1686 } 1687 } 1688 R.clear(); 1689 1690 // Emit a special diagnostic for failed member lookups. 1691 // FIXME: computing the declaration context might fail here (?) 1692 if (!SS.isEmpty()) { 1693 Diag(R.getNameLoc(), diag::err_no_member) 1694 << Name << computeDeclContext(SS, false) 1695 << SS.getRange(); 1696 return true; 1697 } 1698 1699 // Give up, we can't recover. 1700 Diag(R.getNameLoc(), diagnostic) << Name; 1701 return true; 1702} 1703 1704ExprResult Sema::ActOnIdExpression(Scope *S, 1705 CXXScopeSpec &SS, 1706 SourceLocation TemplateKWLoc, 1707 UnqualifiedId &Id, 1708 bool HasTrailingLParen, 1709 bool IsAddressOfOperand, 1710 CorrectionCandidateCallback *CCC) { 1711 assert(!(IsAddressOfOperand && HasTrailingLParen) && 1712 "cannot be direct & operand and have a trailing lparen"); 1713 1714 if (SS.isInvalid()) 1715 return ExprError(); 1716 1717 TemplateArgumentListInfo TemplateArgsBuffer; 1718 1719 // Decompose the UnqualifiedId into the following data. 1720 DeclarationNameInfo NameInfo; 1721 const TemplateArgumentListInfo *TemplateArgs; 1722 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 1723 1724 DeclarationName Name = NameInfo.getName(); 1725 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1726 SourceLocation NameLoc = NameInfo.getLoc(); 1727 1728 // C++ [temp.dep.expr]p3: 1729 // An id-expression is type-dependent if it contains: 1730 // -- an identifier that was declared with a dependent type, 1731 // (note: handled after lookup) 1732 // -- a template-id that is dependent, 1733 // (note: handled in BuildTemplateIdExpr) 1734 // -- a conversion-function-id that specifies a dependent type, 1735 // -- a nested-name-specifier that contains a class-name that 1736 // names a dependent type. 1737 // Determine whether this is a member of an unknown specialization; 1738 // we need to handle these differently. 1739 bool DependentID = false; 1740 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 1741 Name.getCXXNameType()->isDependentType()) { 1742 DependentID = true; 1743 } else if (SS.isSet()) { 1744 if (DeclContext *DC = computeDeclContext(SS, false)) { 1745 if (RequireCompleteDeclContext(SS, DC)) 1746 return ExprError(); 1747 } else { 1748 DependentID = true; 1749 } 1750 } 1751 1752 if (DependentID) 1753 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1754 IsAddressOfOperand, TemplateArgs); 1755 1756 // Perform the required lookup. 1757 LookupResult R(*this, NameInfo, 1758 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 1759 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 1760 if (TemplateArgs) { 1761 // Lookup the template name again to correctly establish the context in 1762 // which it was found. This is really unfortunate as we already did the 1763 // lookup to determine that it was a template name in the first place. If 1764 // this becomes a performance hit, we can work harder to preserve those 1765 // results until we get here but it's likely not worth it. 1766 bool MemberOfUnknownSpecialization; 1767 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 1768 MemberOfUnknownSpecialization); 1769 1770 if (MemberOfUnknownSpecialization || 1771 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 1772 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1773 IsAddressOfOperand, TemplateArgs); 1774 } else { 1775 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 1776 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 1777 1778 // If the result might be in a dependent base class, this is a dependent 1779 // id-expression. 1780 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 1781 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1782 IsAddressOfOperand, TemplateArgs); 1783 1784 // If this reference is in an Objective-C method, then we need to do 1785 // some special Objective-C lookup, too. 1786 if (IvarLookupFollowUp) { 1787 ExprResult E(LookupInObjCMethod(R, S, II, true)); 1788 if (E.isInvalid()) 1789 return ExprError(); 1790 1791 if (Expr *Ex = E.takeAs<Expr>()) 1792 return Owned(Ex); 1793 } 1794 } 1795 1796 if (R.isAmbiguous()) 1797 return ExprError(); 1798 1799 // Determine whether this name might be a candidate for 1800 // argument-dependent lookup. 1801 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 1802 1803 if (R.empty() && !ADL) { 1804 // Otherwise, this could be an implicitly declared function reference (legal 1805 // in C90, extension in C99, forbidden in C++). 1806 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 1807 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 1808 if (D) R.addDecl(D); 1809 } 1810 1811 // If this name wasn't predeclared and if this is not a function 1812 // call, diagnose the problem. 1813 if (R.empty()) { 1814 1815 // In Microsoft mode, if we are inside a template class member function 1816 // and we can't resolve an identifier then assume the identifier is type 1817 // dependent. The goal is to postpone name lookup to instantiation time 1818 // to be able to search into type dependent base classes. 1819 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() && 1820 isa<CXXMethodDecl>(CurContext)) 1821 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1822 IsAddressOfOperand, TemplateArgs); 1823 1824 CorrectionCandidateCallback DefaultValidator; 1825 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator)) 1826 return ExprError(); 1827 1828 assert(!R.empty() && 1829 "DiagnoseEmptyLookup returned false but added no results"); 1830 1831 // If we found an Objective-C instance variable, let 1832 // LookupInObjCMethod build the appropriate expression to 1833 // reference the ivar. 1834 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 1835 R.clear(); 1836 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 1837 // In a hopelessly buggy code, Objective-C instance variable 1838 // lookup fails and no expression will be built to reference it. 1839 if (!E.isInvalid() && !E.get()) 1840 return ExprError(); 1841 return E; 1842 } 1843 } 1844 } 1845 1846 // This is guaranteed from this point on. 1847 assert(!R.empty() || ADL); 1848 1849 // Check whether this might be a C++ implicit instance member access. 1850 // C++ [class.mfct.non-static]p3: 1851 // When an id-expression that is not part of a class member access 1852 // syntax and not used to form a pointer to member is used in the 1853 // body of a non-static member function of class X, if name lookup 1854 // resolves the name in the id-expression to a non-static non-type 1855 // member of some class C, the id-expression is transformed into a 1856 // class member access expression using (*this) as the 1857 // postfix-expression to the left of the . operator. 1858 // 1859 // But we don't actually need to do this for '&' operands if R 1860 // resolved to a function or overloaded function set, because the 1861 // expression is ill-formed if it actually works out to be a 1862 // non-static member function: 1863 // 1864 // C++ [expr.ref]p4: 1865 // Otherwise, if E1.E2 refers to a non-static member function. . . 1866 // [t]he expression can be used only as the left-hand operand of a 1867 // member function call. 1868 // 1869 // There are other safeguards against such uses, but it's important 1870 // to get this right here so that we don't end up making a 1871 // spuriously dependent expression if we're inside a dependent 1872 // instance method. 1873 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 1874 bool MightBeImplicitMember; 1875 if (!IsAddressOfOperand) 1876 MightBeImplicitMember = true; 1877 else if (!SS.isEmpty()) 1878 MightBeImplicitMember = false; 1879 else if (R.isOverloadedResult()) 1880 MightBeImplicitMember = false; 1881 else if (R.isUnresolvableResult()) 1882 MightBeImplicitMember = true; 1883 else 1884 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 1885 isa<IndirectFieldDecl>(R.getFoundDecl()); 1886 1887 if (MightBeImplicitMember) 1888 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 1889 R, TemplateArgs); 1890 } 1891 1892 if (TemplateArgs || TemplateKWLoc.isValid()) 1893 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 1894 1895 return BuildDeclarationNameExpr(SS, R, ADL); 1896} 1897 1898/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 1899/// declaration name, generally during template instantiation. 1900/// There's a large number of things which don't need to be done along 1901/// this path. 1902ExprResult 1903Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 1904 const DeclarationNameInfo &NameInfo, 1905 bool IsAddressOfOperand) { 1906 DeclContext *DC = computeDeclContext(SS, false); 1907 if (!DC) 1908 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 1909 NameInfo, /*TemplateArgs=*/0); 1910 1911 if (RequireCompleteDeclContext(SS, DC)) 1912 return ExprError(); 1913 1914 LookupResult R(*this, NameInfo, LookupOrdinaryName); 1915 LookupQualifiedName(R, DC); 1916 1917 if (R.isAmbiguous()) 1918 return ExprError(); 1919 1920 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 1921 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 1922 NameInfo, /*TemplateArgs=*/0); 1923 1924 if (R.empty()) { 1925 Diag(NameInfo.getLoc(), diag::err_no_member) 1926 << NameInfo.getName() << DC << SS.getRange(); 1927 return ExprError(); 1928 } 1929 1930 // Defend against this resolving to an implicit member access. We usually 1931 // won't get here if this might be a legitimate a class member (we end up in 1932 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 1933 // a pointer-to-member or in an unevaluated context in C++11. 1934 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 1935 return BuildPossibleImplicitMemberExpr(SS, 1936 /*TemplateKWLoc=*/SourceLocation(), 1937 R, /*TemplateArgs=*/0); 1938 1939 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 1940} 1941 1942/// LookupInObjCMethod - The parser has read a name in, and Sema has 1943/// detected that we're currently inside an ObjC method. Perform some 1944/// additional lookup. 1945/// 1946/// Ideally, most of this would be done by lookup, but there's 1947/// actually quite a lot of extra work involved. 1948/// 1949/// Returns a null sentinel to indicate trivial success. 1950ExprResult 1951Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 1952 IdentifierInfo *II, bool AllowBuiltinCreation) { 1953 SourceLocation Loc = Lookup.getNameLoc(); 1954 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 1955 1956 // There are two cases to handle here. 1) scoped lookup could have failed, 1957 // in which case we should look for an ivar. 2) scoped lookup could have 1958 // found a decl, but that decl is outside the current instance method (i.e. 1959 // a global variable). In these two cases, we do a lookup for an ivar with 1960 // this name, if the lookup sucedes, we replace it our current decl. 1961 1962 // If we're in a class method, we don't normally want to look for 1963 // ivars. But if we don't find anything else, and there's an 1964 // ivar, that's an error. 1965 bool IsClassMethod = CurMethod->isClassMethod(); 1966 1967 bool LookForIvars; 1968 if (Lookup.empty()) 1969 LookForIvars = true; 1970 else if (IsClassMethod) 1971 LookForIvars = false; 1972 else 1973 LookForIvars = (Lookup.isSingleResult() && 1974 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 1975 ObjCInterfaceDecl *IFace = 0; 1976 if (LookForIvars) { 1977 IFace = CurMethod->getClassInterface(); 1978 ObjCInterfaceDecl *ClassDeclared; 1979 ObjCIvarDecl *IV = 0; 1980 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 1981 // Diagnose using an ivar in a class method. 1982 if (IsClassMethod) 1983 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 1984 << IV->getDeclName()); 1985 1986 // If we're referencing an invalid decl, just return this as a silent 1987 // error node. The error diagnostic was already emitted on the decl. 1988 if (IV->isInvalidDecl()) 1989 return ExprError(); 1990 1991 // Check if referencing a field with __attribute__((deprecated)). 1992 if (DiagnoseUseOfDecl(IV, Loc)) 1993 return ExprError(); 1994 1995 // Diagnose the use of an ivar outside of the declaring class. 1996 if (IV->getAccessControl() == ObjCIvarDecl::Private && 1997 !declaresSameEntity(ClassDeclared, IFace) && 1998 !getLangOpts().DebuggerSupport) 1999 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2000 2001 // FIXME: This should use a new expr for a direct reference, don't 2002 // turn this into Self->ivar, just return a BareIVarExpr or something. 2003 IdentifierInfo &II = Context.Idents.get("self"); 2004 UnqualifiedId SelfName; 2005 SelfName.setIdentifier(&II, SourceLocation()); 2006 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2007 CXXScopeSpec SelfScopeSpec; 2008 SourceLocation TemplateKWLoc; 2009 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2010 SelfName, false, false); 2011 if (SelfExpr.isInvalid()) 2012 return ExprError(); 2013 2014 SelfExpr = DefaultLvalueConversion(SelfExpr.take()); 2015 if (SelfExpr.isInvalid()) 2016 return ExprError(); 2017 2018 MarkAnyDeclReferenced(Loc, IV); 2019 2020 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2021 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize) 2022 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2023 2024 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(), 2025 Loc, 2026 SelfExpr.take(), 2027 true, true); 2028 2029 if (getLangOpts().ObjCAutoRefCount) { 2030 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2031 DiagnosticsEngine::Level Level = 2032 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc); 2033 if (Level != DiagnosticsEngine::Ignored) 2034 getCurFunction()->recordUseOfWeak(Result); 2035 } 2036 if (CurContext->isClosure()) 2037 Diag(Loc, diag::warn_implicitly_retains_self) 2038 << FixItHint::CreateInsertion(Loc, "self->"); 2039 } 2040 2041 return Owned(Result); 2042 } 2043 } else if (CurMethod->isInstanceMethod()) { 2044 // We should warn if a local variable hides an ivar. 2045 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2046 ObjCInterfaceDecl *ClassDeclared; 2047 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2048 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2049 declaresSameEntity(IFace, ClassDeclared)) 2050 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2051 } 2052 } 2053 } else if (Lookup.isSingleResult() && 2054 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2055 // If accessing a stand-alone ivar in a class method, this is an error. 2056 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2057 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2058 << IV->getDeclName()); 2059 } 2060 2061 if (Lookup.empty() && II && AllowBuiltinCreation) { 2062 // FIXME. Consolidate this with similar code in LookupName. 2063 if (unsigned BuiltinID = II->getBuiltinID()) { 2064 if (!(getLangOpts().CPlusPlus && 2065 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2066 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2067 S, Lookup.isForRedeclaration(), 2068 Lookup.getNameLoc()); 2069 if (D) Lookup.addDecl(D); 2070 } 2071 } 2072 } 2073 // Sentinel value saying that we didn't do anything special. 2074 return Owned((Expr*) 0); 2075} 2076 2077/// \brief Cast a base object to a member's actual type. 2078/// 2079/// Logically this happens in three phases: 2080/// 2081/// * First we cast from the base type to the naming class. 2082/// The naming class is the class into which we were looking 2083/// when we found the member; it's the qualifier type if a 2084/// qualifier was provided, and otherwise it's the base type. 2085/// 2086/// * Next we cast from the naming class to the declaring class. 2087/// If the member we found was brought into a class's scope by 2088/// a using declaration, this is that class; otherwise it's 2089/// the class declaring the member. 2090/// 2091/// * Finally we cast from the declaring class to the "true" 2092/// declaring class of the member. This conversion does not 2093/// obey access control. 2094ExprResult 2095Sema::PerformObjectMemberConversion(Expr *From, 2096 NestedNameSpecifier *Qualifier, 2097 NamedDecl *FoundDecl, 2098 NamedDecl *Member) { 2099 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2100 if (!RD) 2101 return Owned(From); 2102 2103 QualType DestRecordType; 2104 QualType DestType; 2105 QualType FromRecordType; 2106 QualType FromType = From->getType(); 2107 bool PointerConversions = false; 2108 if (isa<FieldDecl>(Member)) { 2109 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2110 2111 if (FromType->getAs<PointerType>()) { 2112 DestType = Context.getPointerType(DestRecordType); 2113 FromRecordType = FromType->getPointeeType(); 2114 PointerConversions = true; 2115 } else { 2116 DestType = DestRecordType; 2117 FromRecordType = FromType; 2118 } 2119 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2120 if (Method->isStatic()) 2121 return Owned(From); 2122 2123 DestType = Method->getThisType(Context); 2124 DestRecordType = DestType->getPointeeType(); 2125 2126 if (FromType->getAs<PointerType>()) { 2127 FromRecordType = FromType->getPointeeType(); 2128 PointerConversions = true; 2129 } else { 2130 FromRecordType = FromType; 2131 DestType = DestRecordType; 2132 } 2133 } else { 2134 // No conversion necessary. 2135 return Owned(From); 2136 } 2137 2138 if (DestType->isDependentType() || FromType->isDependentType()) 2139 return Owned(From); 2140 2141 // If the unqualified types are the same, no conversion is necessary. 2142 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2143 return Owned(From); 2144 2145 SourceRange FromRange = From->getSourceRange(); 2146 SourceLocation FromLoc = FromRange.getBegin(); 2147 2148 ExprValueKind VK = From->getValueKind(); 2149 2150 // C++ [class.member.lookup]p8: 2151 // [...] Ambiguities can often be resolved by qualifying a name with its 2152 // class name. 2153 // 2154 // If the member was a qualified name and the qualified referred to a 2155 // specific base subobject type, we'll cast to that intermediate type 2156 // first and then to the object in which the member is declared. That allows 2157 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2158 // 2159 // class Base { public: int x; }; 2160 // class Derived1 : public Base { }; 2161 // class Derived2 : public Base { }; 2162 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2163 // 2164 // void VeryDerived::f() { 2165 // x = 17; // error: ambiguous base subobjects 2166 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2167 // } 2168 if (Qualifier) { 2169 QualType QType = QualType(Qualifier->getAsType(), 0); 2170 assert(!QType.isNull() && "lookup done with dependent qualifier?"); 2171 assert(QType->isRecordType() && "lookup done with non-record type"); 2172 2173 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2174 2175 // In C++98, the qualifier type doesn't actually have to be a base 2176 // type of the object type, in which case we just ignore it. 2177 // Otherwise build the appropriate casts. 2178 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2179 CXXCastPath BasePath; 2180 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2181 FromLoc, FromRange, &BasePath)) 2182 return ExprError(); 2183 2184 if (PointerConversions) 2185 QType = Context.getPointerType(QType); 2186 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2187 VK, &BasePath).take(); 2188 2189 FromType = QType; 2190 FromRecordType = QRecordType; 2191 2192 // If the qualifier type was the same as the destination type, 2193 // we're done. 2194 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2195 return Owned(From); 2196 } 2197 } 2198 2199 bool IgnoreAccess = false; 2200 2201 // If we actually found the member through a using declaration, cast 2202 // down to the using declaration's type. 2203 // 2204 // Pointer equality is fine here because only one declaration of a 2205 // class ever has member declarations. 2206 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2207 assert(isa<UsingShadowDecl>(FoundDecl)); 2208 QualType URecordType = Context.getTypeDeclType( 2209 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2210 2211 // We only need to do this if the naming-class to declaring-class 2212 // conversion is non-trivial. 2213 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2214 assert(IsDerivedFrom(FromRecordType, URecordType)); 2215 CXXCastPath BasePath; 2216 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2217 FromLoc, FromRange, &BasePath)) 2218 return ExprError(); 2219 2220 QualType UType = URecordType; 2221 if (PointerConversions) 2222 UType = Context.getPointerType(UType); 2223 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2224 VK, &BasePath).take(); 2225 FromType = UType; 2226 FromRecordType = URecordType; 2227 } 2228 2229 // We don't do access control for the conversion from the 2230 // declaring class to the true declaring class. 2231 IgnoreAccess = true; 2232 } 2233 2234 CXXCastPath BasePath; 2235 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2236 FromLoc, FromRange, &BasePath, 2237 IgnoreAccess)) 2238 return ExprError(); 2239 2240 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2241 VK, &BasePath); 2242} 2243 2244bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2245 const LookupResult &R, 2246 bool HasTrailingLParen) { 2247 // Only when used directly as the postfix-expression of a call. 2248 if (!HasTrailingLParen) 2249 return false; 2250 2251 // Never if a scope specifier was provided. 2252 if (SS.isSet()) 2253 return false; 2254 2255 // Only in C++ or ObjC++. 2256 if (!getLangOpts().CPlusPlus) 2257 return false; 2258 2259 // Turn off ADL when we find certain kinds of declarations during 2260 // normal lookup: 2261 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2262 NamedDecl *D = *I; 2263 2264 // C++0x [basic.lookup.argdep]p3: 2265 // -- a declaration of a class member 2266 // Since using decls preserve this property, we check this on the 2267 // original decl. 2268 if (D->isCXXClassMember()) 2269 return false; 2270 2271 // C++0x [basic.lookup.argdep]p3: 2272 // -- a block-scope function declaration that is not a 2273 // using-declaration 2274 // NOTE: we also trigger this for function templates (in fact, we 2275 // don't check the decl type at all, since all other decl types 2276 // turn off ADL anyway). 2277 if (isa<UsingShadowDecl>(D)) 2278 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2279 else if (D->getDeclContext()->isFunctionOrMethod()) 2280 return false; 2281 2282 // C++0x [basic.lookup.argdep]p3: 2283 // -- a declaration that is neither a function or a function 2284 // template 2285 // And also for builtin functions. 2286 if (isa<FunctionDecl>(D)) { 2287 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2288 2289 // But also builtin functions. 2290 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2291 return false; 2292 } else if (!isa<FunctionTemplateDecl>(D)) 2293 return false; 2294 } 2295 2296 return true; 2297} 2298 2299 2300/// Diagnoses obvious problems with the use of the given declaration 2301/// as an expression. This is only actually called for lookups that 2302/// were not overloaded, and it doesn't promise that the declaration 2303/// will in fact be used. 2304static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2305 if (isa<TypedefNameDecl>(D)) { 2306 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2307 return true; 2308 } 2309 2310 if (isa<ObjCInterfaceDecl>(D)) { 2311 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2312 return true; 2313 } 2314 2315 if (isa<NamespaceDecl>(D)) { 2316 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2317 return true; 2318 } 2319 2320 return false; 2321} 2322 2323ExprResult 2324Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2325 LookupResult &R, 2326 bool NeedsADL) { 2327 // If this is a single, fully-resolved result and we don't need ADL, 2328 // just build an ordinary singleton decl ref. 2329 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2330 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), 2331 R.getFoundDecl()); 2332 2333 // We only need to check the declaration if there's exactly one 2334 // result, because in the overloaded case the results can only be 2335 // functions and function templates. 2336 if (R.isSingleResult() && 2337 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2338 return ExprError(); 2339 2340 // Otherwise, just build an unresolved lookup expression. Suppress 2341 // any lookup-related diagnostics; we'll hash these out later, when 2342 // we've picked a target. 2343 R.suppressDiagnostics(); 2344 2345 UnresolvedLookupExpr *ULE 2346 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2347 SS.getWithLocInContext(Context), 2348 R.getLookupNameInfo(), 2349 NeedsADL, R.isOverloadedResult(), 2350 R.begin(), R.end()); 2351 2352 return Owned(ULE); 2353} 2354 2355/// \brief Complete semantic analysis for a reference to the given declaration. 2356ExprResult 2357Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2358 const DeclarationNameInfo &NameInfo, 2359 NamedDecl *D) { 2360 assert(D && "Cannot refer to a NULL declaration"); 2361 assert(!isa<FunctionTemplateDecl>(D) && 2362 "Cannot refer unambiguously to a function template"); 2363 2364 SourceLocation Loc = NameInfo.getLoc(); 2365 if (CheckDeclInExpr(*this, Loc, D)) 2366 return ExprError(); 2367 2368 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2369 // Specifically diagnose references to class templates that are missing 2370 // a template argument list. 2371 Diag(Loc, diag::err_template_decl_ref) 2372 << Template << SS.getRange(); 2373 Diag(Template->getLocation(), diag::note_template_decl_here); 2374 return ExprError(); 2375 } 2376 2377 // Make sure that we're referring to a value. 2378 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2379 if (!VD) { 2380 Diag(Loc, diag::err_ref_non_value) 2381 << D << SS.getRange(); 2382 Diag(D->getLocation(), diag::note_declared_at); 2383 return ExprError(); 2384 } 2385 2386 // Check whether this declaration can be used. Note that we suppress 2387 // this check when we're going to perform argument-dependent lookup 2388 // on this function name, because this might not be the function 2389 // that overload resolution actually selects. 2390 if (DiagnoseUseOfDecl(VD, Loc)) 2391 return ExprError(); 2392 2393 // Only create DeclRefExpr's for valid Decl's. 2394 if (VD->isInvalidDecl()) 2395 return ExprError(); 2396 2397 // Handle members of anonymous structs and unions. If we got here, 2398 // and the reference is to a class member indirect field, then this 2399 // must be the subject of a pointer-to-member expression. 2400 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2401 if (!indirectField->isCXXClassMember()) 2402 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2403 indirectField); 2404 2405 { 2406 QualType type = VD->getType(); 2407 ExprValueKind valueKind = VK_RValue; 2408 2409 switch (D->getKind()) { 2410 // Ignore all the non-ValueDecl kinds. 2411#define ABSTRACT_DECL(kind) 2412#define VALUE(type, base) 2413#define DECL(type, base) \ 2414 case Decl::type: 2415#include "clang/AST/DeclNodes.inc" 2416 llvm_unreachable("invalid value decl kind"); 2417 2418 // These shouldn't make it here. 2419 case Decl::ObjCAtDefsField: 2420 case Decl::ObjCIvar: 2421 llvm_unreachable("forming non-member reference to ivar?"); 2422 2423 // Enum constants are always r-values and never references. 2424 // Unresolved using declarations are dependent. 2425 case Decl::EnumConstant: 2426 case Decl::UnresolvedUsingValue: 2427 valueKind = VK_RValue; 2428 break; 2429 2430 // Fields and indirect fields that got here must be for 2431 // pointer-to-member expressions; we just call them l-values for 2432 // internal consistency, because this subexpression doesn't really 2433 // exist in the high-level semantics. 2434 case Decl::Field: 2435 case Decl::IndirectField: 2436 assert(getLangOpts().CPlusPlus && 2437 "building reference to field in C?"); 2438 2439 // These can't have reference type in well-formed programs, but 2440 // for internal consistency we do this anyway. 2441 type = type.getNonReferenceType(); 2442 valueKind = VK_LValue; 2443 break; 2444 2445 // Non-type template parameters are either l-values or r-values 2446 // depending on the type. 2447 case Decl::NonTypeTemplateParm: { 2448 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2449 type = reftype->getPointeeType(); 2450 valueKind = VK_LValue; // even if the parameter is an r-value reference 2451 break; 2452 } 2453 2454 // For non-references, we need to strip qualifiers just in case 2455 // the template parameter was declared as 'const int' or whatever. 2456 valueKind = VK_RValue; 2457 type = type.getUnqualifiedType(); 2458 break; 2459 } 2460 2461 case Decl::Var: 2462 // In C, "extern void blah;" is valid and is an r-value. 2463 if (!getLangOpts().CPlusPlus && 2464 !type.hasQualifiers() && 2465 type->isVoidType()) { 2466 valueKind = VK_RValue; 2467 break; 2468 } 2469 // fallthrough 2470 2471 case Decl::ImplicitParam: 2472 case Decl::ParmVar: { 2473 // These are always l-values. 2474 valueKind = VK_LValue; 2475 type = type.getNonReferenceType(); 2476 2477 // FIXME: Does the addition of const really only apply in 2478 // potentially-evaluated contexts? Since the variable isn't actually 2479 // captured in an unevaluated context, it seems that the answer is no. 2480 if (!isUnevaluatedContext()) { 2481 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2482 if (!CapturedType.isNull()) 2483 type = CapturedType; 2484 } 2485 2486 break; 2487 } 2488 2489 case Decl::Function: { 2490 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2491 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2492 type = Context.BuiltinFnTy; 2493 valueKind = VK_RValue; 2494 break; 2495 } 2496 } 2497 2498 const FunctionType *fty = type->castAs<FunctionType>(); 2499 2500 // If we're referring to a function with an __unknown_anytype 2501 // result type, make the entire expression __unknown_anytype. 2502 if (fty->getResultType() == Context.UnknownAnyTy) { 2503 type = Context.UnknownAnyTy; 2504 valueKind = VK_RValue; 2505 break; 2506 } 2507 2508 // Functions are l-values in C++. 2509 if (getLangOpts().CPlusPlus) { 2510 valueKind = VK_LValue; 2511 break; 2512 } 2513 2514 // C99 DR 316 says that, if a function type comes from a 2515 // function definition (without a prototype), that type is only 2516 // used for checking compatibility. Therefore, when referencing 2517 // the function, we pretend that we don't have the full function 2518 // type. 2519 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2520 isa<FunctionProtoType>(fty)) 2521 type = Context.getFunctionNoProtoType(fty->getResultType(), 2522 fty->getExtInfo()); 2523 2524 // Functions are r-values in C. 2525 valueKind = VK_RValue; 2526 break; 2527 } 2528 2529 case Decl::CXXMethod: 2530 // If we're referring to a method with an __unknown_anytype 2531 // result type, make the entire expression __unknown_anytype. 2532 // This should only be possible with a type written directly. 2533 if (const FunctionProtoType *proto 2534 = dyn_cast<FunctionProtoType>(VD->getType())) 2535 if (proto->getResultType() == Context.UnknownAnyTy) { 2536 type = Context.UnknownAnyTy; 2537 valueKind = VK_RValue; 2538 break; 2539 } 2540 2541 // C++ methods are l-values if static, r-values if non-static. 2542 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2543 valueKind = VK_LValue; 2544 break; 2545 } 2546 // fallthrough 2547 2548 case Decl::CXXConversion: 2549 case Decl::CXXDestructor: 2550 case Decl::CXXConstructor: 2551 valueKind = VK_RValue; 2552 break; 2553 } 2554 2555 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS); 2556 } 2557} 2558 2559ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 2560 PredefinedExpr::IdentType IT; 2561 2562 switch (Kind) { 2563 default: llvm_unreachable("Unknown simple primary expr!"); 2564 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 2565 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 2566 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 2567 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 2568 } 2569 2570 // Pre-defined identifiers are of type char[x], where x is the length of the 2571 // string. 2572 2573 Decl *currentDecl = getCurFunctionOrMethodDecl(); 2574 if (!currentDecl && getCurBlock()) 2575 currentDecl = getCurBlock()->TheDecl; 2576 if (!currentDecl) { 2577 Diag(Loc, diag::ext_predef_outside_function); 2578 currentDecl = Context.getTranslationUnitDecl(); 2579 } 2580 2581 QualType ResTy; 2582 if (cast<DeclContext>(currentDecl)->isDependentContext()) { 2583 ResTy = Context.DependentTy; 2584 } else { 2585 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 2586 2587 llvm::APInt LengthI(32, Length + 1); 2588 if (IT == PredefinedExpr::LFunction) 2589 ResTy = Context.WCharTy.withConst(); 2590 else 2591 ResTy = Context.CharTy.withConst(); 2592 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 2593 } 2594 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 2595} 2596 2597ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 2598 SmallString<16> CharBuffer; 2599 bool Invalid = false; 2600 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 2601 if (Invalid) 2602 return ExprError(); 2603 2604 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 2605 PP, Tok.getKind()); 2606 if (Literal.hadError()) 2607 return ExprError(); 2608 2609 QualType Ty; 2610 if (Literal.isWide()) 2611 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++. 2612 else if (Literal.isUTF16()) 2613 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 2614 else if (Literal.isUTF32()) 2615 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 2616 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 2617 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 2618 else 2619 Ty = Context.CharTy; // 'x' -> char in C++ 2620 2621 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 2622 if (Literal.isWide()) 2623 Kind = CharacterLiteral::Wide; 2624 else if (Literal.isUTF16()) 2625 Kind = CharacterLiteral::UTF16; 2626 else if (Literal.isUTF32()) 2627 Kind = CharacterLiteral::UTF32; 2628 2629 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 2630 Tok.getLocation()); 2631 2632 if (Literal.getUDSuffix().empty()) 2633 return Owned(Lit); 2634 2635 // We're building a user-defined literal. 2636 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2637 SourceLocation UDSuffixLoc = 2638 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2639 2640 // Make sure we're allowed user-defined literals here. 2641 if (!UDLScope) 2642 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 2643 2644 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 2645 // operator "" X (ch) 2646 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 2647 llvm::makeArrayRef(&Lit, 1), 2648 Tok.getLocation()); 2649} 2650 2651ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 2652 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2653 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 2654 Context.IntTy, Loc)); 2655} 2656 2657static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 2658 QualType Ty, SourceLocation Loc) { 2659 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 2660 2661 using llvm::APFloat; 2662 APFloat Val(Format); 2663 2664 APFloat::opStatus result = Literal.GetFloatValue(Val); 2665 2666 // Overflow is always an error, but underflow is only an error if 2667 // we underflowed to zero (APFloat reports denormals as underflow). 2668 if ((result & APFloat::opOverflow) || 2669 ((result & APFloat::opUnderflow) && Val.isZero())) { 2670 unsigned diagnostic; 2671 SmallString<20> buffer; 2672 if (result & APFloat::opOverflow) { 2673 diagnostic = diag::warn_float_overflow; 2674 APFloat::getLargest(Format).toString(buffer); 2675 } else { 2676 diagnostic = diag::warn_float_underflow; 2677 APFloat::getSmallest(Format).toString(buffer); 2678 } 2679 2680 S.Diag(Loc, diagnostic) 2681 << Ty 2682 << StringRef(buffer.data(), buffer.size()); 2683 } 2684 2685 bool isExact = (result == APFloat::opOK); 2686 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 2687} 2688 2689ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 2690 // Fast path for a single digit (which is quite common). A single digit 2691 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 2692 if (Tok.getLength() == 1) { 2693 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 2694 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 2695 } 2696 2697 SmallString<128> SpellingBuffer; 2698 // NumericLiteralParser wants to overread by one character. Add padding to 2699 // the buffer in case the token is copied to the buffer. If getSpelling() 2700 // returns a StringRef to the memory buffer, it should have a null char at 2701 // the EOF, so it is also safe. 2702 SpellingBuffer.resize(Tok.getLength() + 1); 2703 2704 // Get the spelling of the token, which eliminates trigraphs, etc. 2705 bool Invalid = false; 2706 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 2707 if (Invalid) 2708 return ExprError(); 2709 2710 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 2711 if (Literal.hadError) 2712 return ExprError(); 2713 2714 if (Literal.hasUDSuffix()) { 2715 // We're building a user-defined literal. 2716 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2717 SourceLocation UDSuffixLoc = 2718 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2719 2720 // Make sure we're allowed user-defined literals here. 2721 if (!UDLScope) 2722 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 2723 2724 QualType CookedTy; 2725 if (Literal.isFloatingLiteral()) { 2726 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 2727 // long double, the literal is treated as a call of the form 2728 // operator "" X (f L) 2729 CookedTy = Context.LongDoubleTy; 2730 } else { 2731 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 2732 // unsigned long long, the literal is treated as a call of the form 2733 // operator "" X (n ULL) 2734 CookedTy = Context.UnsignedLongLongTy; 2735 } 2736 2737 DeclarationName OpName = 2738 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 2739 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 2740 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 2741 2742 // Perform literal operator lookup to determine if we're building a raw 2743 // literal or a cooked one. 2744 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 2745 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1), 2746 /*AllowRawAndTemplate*/true)) { 2747 case LOLR_Error: 2748 return ExprError(); 2749 2750 case LOLR_Cooked: { 2751 Expr *Lit; 2752 if (Literal.isFloatingLiteral()) { 2753 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 2754 } else { 2755 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 2756 if (Literal.GetIntegerValue(ResultVal)) 2757 Diag(Tok.getLocation(), diag::warn_integer_too_large); 2758 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 2759 Tok.getLocation()); 2760 } 2761 return BuildLiteralOperatorCall(R, OpNameInfo, 2762 llvm::makeArrayRef(&Lit, 1), 2763 Tok.getLocation()); 2764 } 2765 2766 case LOLR_Raw: { 2767 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 2768 // literal is treated as a call of the form 2769 // operator "" X ("n") 2770 SourceLocation TokLoc = Tok.getLocation(); 2771 unsigned Length = Literal.getUDSuffixOffset(); 2772 QualType StrTy = Context.getConstantArrayType( 2773 Context.CharTy, llvm::APInt(32, Length + 1), 2774 ArrayType::Normal, 0); 2775 Expr *Lit = StringLiteral::Create( 2776 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 2777 /*Pascal*/false, StrTy, &TokLoc, 1); 2778 return BuildLiteralOperatorCall(R, OpNameInfo, 2779 llvm::makeArrayRef(&Lit, 1), TokLoc); 2780 } 2781 2782 case LOLR_Template: 2783 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 2784 // template), L is treated as a call fo the form 2785 // operator "" X <'c1', 'c2', ... 'ck'>() 2786 // where n is the source character sequence c1 c2 ... ck. 2787 TemplateArgumentListInfo ExplicitArgs; 2788 unsigned CharBits = Context.getIntWidth(Context.CharTy); 2789 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 2790 llvm::APSInt Value(CharBits, CharIsUnsigned); 2791 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 2792 Value = TokSpelling[I]; 2793 TemplateArgument Arg(Context, Value, Context.CharTy); 2794 TemplateArgumentLocInfo ArgInfo; 2795 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 2796 } 2797 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(), 2798 Tok.getLocation(), &ExplicitArgs); 2799 } 2800 2801 llvm_unreachable("unexpected literal operator lookup result"); 2802 } 2803 2804 Expr *Res; 2805 2806 if (Literal.isFloatingLiteral()) { 2807 QualType Ty; 2808 if (Literal.isFloat) 2809 Ty = Context.FloatTy; 2810 else if (!Literal.isLong) 2811 Ty = Context.DoubleTy; 2812 else 2813 Ty = Context.LongDoubleTy; 2814 2815 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 2816 2817 if (Ty == Context.DoubleTy) { 2818 if (getLangOpts().SinglePrecisionConstants) { 2819 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 2820 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) { 2821 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 2822 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 2823 } 2824 } 2825 } else if (!Literal.isIntegerLiteral()) { 2826 return ExprError(); 2827 } else { 2828 QualType Ty; 2829 2830 // 'long long' is a C99 or C++11 feature. 2831 if (!getLangOpts().C99 && Literal.isLongLong) { 2832 if (getLangOpts().CPlusPlus) 2833 Diag(Tok.getLocation(), 2834 getLangOpts().CPlusPlus0x ? 2835 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 2836 else 2837 Diag(Tok.getLocation(), diag::ext_c99_longlong); 2838 } 2839 2840 // Get the value in the widest-possible width. 2841 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 2842 // The microsoft literal suffix extensions support 128-bit literals, which 2843 // may be wider than [u]intmax_t. 2844 // FIXME: Actually, they don't. We seem to have accidentally invented the 2845 // i128 suffix. 2846 if (Literal.isMicrosoftInteger && MaxWidth < 128 && 2847 PP.getTargetInfo().hasInt128Type()) 2848 MaxWidth = 128; 2849 llvm::APInt ResultVal(MaxWidth, 0); 2850 2851 if (Literal.GetIntegerValue(ResultVal)) { 2852 // If this value didn't fit into uintmax_t, warn and force to ull. 2853 Diag(Tok.getLocation(), diag::warn_integer_too_large); 2854 Ty = Context.UnsignedLongLongTy; 2855 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 2856 "long long is not intmax_t?"); 2857 } else { 2858 // If this value fits into a ULL, try to figure out what else it fits into 2859 // according to the rules of C99 6.4.4.1p5. 2860 2861 // Octal, Hexadecimal, and integers with a U suffix are allowed to 2862 // be an unsigned int. 2863 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 2864 2865 // Check from smallest to largest, picking the smallest type we can. 2866 unsigned Width = 0; 2867 if (!Literal.isLong && !Literal.isLongLong) { 2868 // Are int/unsigned possibilities? 2869 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2870 2871 // Does it fit in a unsigned int? 2872 if (ResultVal.isIntN(IntSize)) { 2873 // Does it fit in a signed int? 2874 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 2875 Ty = Context.IntTy; 2876 else if (AllowUnsigned) 2877 Ty = Context.UnsignedIntTy; 2878 Width = IntSize; 2879 } 2880 } 2881 2882 // Are long/unsigned long possibilities? 2883 if (Ty.isNull() && !Literal.isLongLong) { 2884 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 2885 2886 // Does it fit in a unsigned long? 2887 if (ResultVal.isIntN(LongSize)) { 2888 // Does it fit in a signed long? 2889 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 2890 Ty = Context.LongTy; 2891 else if (AllowUnsigned) 2892 Ty = Context.UnsignedLongTy; 2893 Width = LongSize; 2894 } 2895 } 2896 2897 // Check long long if needed. 2898 if (Ty.isNull()) { 2899 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 2900 2901 // Does it fit in a unsigned long long? 2902 if (ResultVal.isIntN(LongLongSize)) { 2903 // Does it fit in a signed long long? 2904 // To be compatible with MSVC, hex integer literals ending with the 2905 // LL or i64 suffix are always signed in Microsoft mode. 2906 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 2907 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 2908 Ty = Context.LongLongTy; 2909 else if (AllowUnsigned) 2910 Ty = Context.UnsignedLongLongTy; 2911 Width = LongLongSize; 2912 } 2913 } 2914 2915 // If it doesn't fit in unsigned long long, and we're using Microsoft 2916 // extensions, then its a 128-bit integer literal. 2917 if (Ty.isNull() && Literal.isMicrosoftInteger && 2918 PP.getTargetInfo().hasInt128Type()) { 2919 if (Literal.isUnsigned) 2920 Ty = Context.UnsignedInt128Ty; 2921 else 2922 Ty = Context.Int128Ty; 2923 Width = 128; 2924 } 2925 2926 // If we still couldn't decide a type, we probably have something that 2927 // does not fit in a signed long long, but has no U suffix. 2928 if (Ty.isNull()) { 2929 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 2930 Ty = Context.UnsignedLongLongTy; 2931 Width = Context.getTargetInfo().getLongLongWidth(); 2932 } 2933 2934 if (ResultVal.getBitWidth() != Width) 2935 ResultVal = ResultVal.trunc(Width); 2936 } 2937 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 2938 } 2939 2940 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 2941 if (Literal.isImaginary) 2942 Res = new (Context) ImaginaryLiteral(Res, 2943 Context.getComplexType(Res->getType())); 2944 2945 return Owned(Res); 2946} 2947 2948ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 2949 assert((E != 0) && "ActOnParenExpr() missing expr"); 2950 return Owned(new (Context) ParenExpr(L, R, E)); 2951} 2952 2953static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 2954 SourceLocation Loc, 2955 SourceRange ArgRange) { 2956 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 2957 // scalar or vector data type argument..." 2958 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 2959 // type (C99 6.2.5p18) or void. 2960 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 2961 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 2962 << T << ArgRange; 2963 return true; 2964 } 2965 2966 assert((T->isVoidType() || !T->isIncompleteType()) && 2967 "Scalar types should always be complete"); 2968 return false; 2969} 2970 2971static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 2972 SourceLocation Loc, 2973 SourceRange ArgRange, 2974 UnaryExprOrTypeTrait TraitKind) { 2975 // C99 6.5.3.4p1: 2976 if (T->isFunctionType()) { 2977 // alignof(function) is allowed as an extension. 2978 if (TraitKind == UETT_SizeOf) 2979 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange; 2980 return false; 2981 } 2982 2983 // Allow sizeof(void)/alignof(void) as an extension. 2984 if (T->isVoidType()) { 2985 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange; 2986 return false; 2987 } 2988 2989 return true; 2990} 2991 2992static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 2993 SourceLocation Loc, 2994 SourceRange ArgRange, 2995 UnaryExprOrTypeTrait TraitKind) { 2996 // Reject sizeof(interface) and sizeof(interface<proto>) if the 2997 // runtime doesn't allow it. 2998 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 2999 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3000 << T << (TraitKind == UETT_SizeOf) 3001 << ArgRange; 3002 return true; 3003 } 3004 3005 return false; 3006} 3007 3008/// \brief Check the constrains on expression operands to unary type expression 3009/// and type traits. 3010/// 3011/// Completes any types necessary and validates the constraints on the operand 3012/// expression. The logic mostly mirrors the type-based overload, but may modify 3013/// the expression as it completes the type for that expression through template 3014/// instantiation, etc. 3015bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3016 UnaryExprOrTypeTrait ExprKind) { 3017 QualType ExprTy = E->getType(); 3018 3019 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 3020 // the result is the size of the referenced type." 3021 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 3022 // result shall be the alignment of the referenced type." 3023 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>()) 3024 ExprTy = Ref->getPointeeType(); 3025 3026 if (ExprKind == UETT_VecStep) 3027 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3028 E->getSourceRange()); 3029 3030 // Whitelist some types as extensions 3031 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3032 E->getSourceRange(), ExprKind)) 3033 return false; 3034 3035 if (RequireCompleteExprType(E, 3036 diag::err_sizeof_alignof_incomplete_type, 3037 ExprKind, E->getSourceRange())) 3038 return true; 3039 3040 // Completeing the expression's type may have changed it. 3041 ExprTy = E->getType(); 3042 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>()) 3043 ExprTy = Ref->getPointeeType(); 3044 3045 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3046 E->getSourceRange(), ExprKind)) 3047 return true; 3048 3049 if (ExprKind == UETT_SizeOf) { 3050 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3051 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3052 QualType OType = PVD->getOriginalType(); 3053 QualType Type = PVD->getType(); 3054 if (Type->isPointerType() && OType->isArrayType()) { 3055 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3056 << Type << OType; 3057 Diag(PVD->getLocation(), diag::note_declared_at); 3058 } 3059 } 3060 } 3061 } 3062 3063 return false; 3064} 3065 3066/// \brief Check the constraints on operands to unary expression and type 3067/// traits. 3068/// 3069/// This will complete any types necessary, and validate the various constraints 3070/// on those operands. 3071/// 3072/// The UsualUnaryConversions() function is *not* called by this routine. 3073/// C99 6.3.2.1p[2-4] all state: 3074/// Except when it is the operand of the sizeof operator ... 3075/// 3076/// C++ [expr.sizeof]p4 3077/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3078/// standard conversions are not applied to the operand of sizeof. 3079/// 3080/// This policy is followed for all of the unary trait expressions. 3081bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3082 SourceLocation OpLoc, 3083 SourceRange ExprRange, 3084 UnaryExprOrTypeTrait ExprKind) { 3085 if (ExprType->isDependentType()) 3086 return false; 3087 3088 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 3089 // the result is the size of the referenced type." 3090 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 3091 // result shall be the alignment of the referenced type." 3092 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3093 ExprType = Ref->getPointeeType(); 3094 3095 if (ExprKind == UETT_VecStep) 3096 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3097 3098 // Whitelist some types as extensions 3099 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3100 ExprKind)) 3101 return false; 3102 3103 if (RequireCompleteType(OpLoc, ExprType, 3104 diag::err_sizeof_alignof_incomplete_type, 3105 ExprKind, ExprRange)) 3106 return true; 3107 3108 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3109 ExprKind)) 3110 return true; 3111 3112 return false; 3113} 3114 3115static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3116 E = E->IgnoreParens(); 3117 3118 // alignof decl is always ok. 3119 if (isa<DeclRefExpr>(E)) 3120 return false; 3121 3122 // Cannot know anything else if the expression is dependent. 3123 if (E->isTypeDependent()) 3124 return false; 3125 3126 if (E->getBitField()) { 3127 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) 3128 << 1 << E->getSourceRange(); 3129 return true; 3130 } 3131 3132 // Alignment of a field access is always okay, so long as it isn't a 3133 // bit-field. 3134 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) 3135 if (isa<FieldDecl>(ME->getMemberDecl())) 3136 return false; 3137 3138 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3139} 3140 3141bool Sema::CheckVecStepExpr(Expr *E) { 3142 E = E->IgnoreParens(); 3143 3144 // Cannot know anything else if the expression is dependent. 3145 if (E->isTypeDependent()) 3146 return false; 3147 3148 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3149} 3150 3151/// \brief Build a sizeof or alignof expression given a type operand. 3152ExprResult 3153Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3154 SourceLocation OpLoc, 3155 UnaryExprOrTypeTrait ExprKind, 3156 SourceRange R) { 3157 if (!TInfo) 3158 return ExprError(); 3159 3160 QualType T = TInfo->getType(); 3161 3162 if (!T->isDependentType() && 3163 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3164 return ExprError(); 3165 3166 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3167 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo, 3168 Context.getSizeType(), 3169 OpLoc, R.getEnd())); 3170} 3171 3172/// \brief Build a sizeof or alignof expression given an expression 3173/// operand. 3174ExprResult 3175Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3176 UnaryExprOrTypeTrait ExprKind) { 3177 ExprResult PE = CheckPlaceholderExpr(E); 3178 if (PE.isInvalid()) 3179 return ExprError(); 3180 3181 E = PE.get(); 3182 3183 // Verify that the operand is valid. 3184 bool isInvalid = false; 3185 if (E->isTypeDependent()) { 3186 // Delay type-checking for type-dependent expressions. 3187 } else if (ExprKind == UETT_AlignOf) { 3188 isInvalid = CheckAlignOfExpr(*this, E); 3189 } else if (ExprKind == UETT_VecStep) { 3190 isInvalid = CheckVecStepExpr(E); 3191 } else if (E->getBitField()) { // C99 6.5.3.4p1. 3192 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0; 3193 isInvalid = true; 3194 } else { 3195 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3196 } 3197 3198 if (isInvalid) 3199 return ExprError(); 3200 3201 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3202 PE = TransformToPotentiallyEvaluated(E); 3203 if (PE.isInvalid()) return ExprError(); 3204 E = PE.take(); 3205 } 3206 3207 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3208 return Owned(new (Context) UnaryExprOrTypeTraitExpr( 3209 ExprKind, E, Context.getSizeType(), OpLoc, 3210 E->getSourceRange().getEnd())); 3211} 3212 3213/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3214/// expr and the same for @c alignof and @c __alignof 3215/// Note that the ArgRange is invalid if isType is false. 3216ExprResult 3217Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3218 UnaryExprOrTypeTrait ExprKind, bool IsType, 3219 void *TyOrEx, const SourceRange &ArgRange) { 3220 // If error parsing type, ignore. 3221 if (TyOrEx == 0) return ExprError(); 3222 3223 if (IsType) { 3224 TypeSourceInfo *TInfo; 3225 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3226 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3227 } 3228 3229 Expr *ArgEx = (Expr *)TyOrEx; 3230 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3231 return Result; 3232} 3233 3234static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3235 bool IsReal) { 3236 if (V.get()->isTypeDependent()) 3237 return S.Context.DependentTy; 3238 3239 // _Real and _Imag are only l-values for normal l-values. 3240 if (V.get()->getObjectKind() != OK_Ordinary) { 3241 V = S.DefaultLvalueConversion(V.take()); 3242 if (V.isInvalid()) 3243 return QualType(); 3244 } 3245 3246 // These operators return the element type of a complex type. 3247 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3248 return CT->getElementType(); 3249 3250 // Otherwise they pass through real integer and floating point types here. 3251 if (V.get()->getType()->isArithmeticType()) 3252 return V.get()->getType(); 3253 3254 // Test for placeholders. 3255 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3256 if (PR.isInvalid()) return QualType(); 3257 if (PR.get() != V.get()) { 3258 V = PR; 3259 return CheckRealImagOperand(S, V, Loc, IsReal); 3260 } 3261 3262 // Reject anything else. 3263 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3264 << (IsReal ? "__real" : "__imag"); 3265 return QualType(); 3266} 3267 3268 3269 3270ExprResult 3271Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3272 tok::TokenKind Kind, Expr *Input) { 3273 UnaryOperatorKind Opc; 3274 switch (Kind) { 3275 default: llvm_unreachable("Unknown unary op!"); 3276 case tok::plusplus: Opc = UO_PostInc; break; 3277 case tok::minusminus: Opc = UO_PostDec; break; 3278 } 3279 3280 // Since this might is a postfix expression, get rid of ParenListExprs. 3281 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3282 if (Result.isInvalid()) return ExprError(); 3283 Input = Result.take(); 3284 3285 return BuildUnaryOp(S, OpLoc, Opc, Input); 3286} 3287 3288/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 3289/// 3290/// \return true on error 3291static bool checkArithmeticOnObjCPointer(Sema &S, 3292 SourceLocation opLoc, 3293 Expr *op) { 3294 assert(op->getType()->isObjCObjectPointerType()); 3295 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic()) 3296 return false; 3297 3298 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 3299 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 3300 << op->getSourceRange(); 3301 return true; 3302} 3303 3304ExprResult 3305Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, 3306 Expr *Idx, SourceLocation RLoc) { 3307 // Since this might be a postfix expression, get rid of ParenListExprs. 3308 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 3309 if (Result.isInvalid()) return ExprError(); 3310 Base = Result.take(); 3311 3312 Expr *LHSExp = Base, *RHSExp = Idx; 3313 3314 if (getLangOpts().CPlusPlus && 3315 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) { 3316 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 3317 Context.DependentTy, 3318 VK_LValue, OK_Ordinary, 3319 RLoc)); 3320 } 3321 3322 if (getLangOpts().CPlusPlus && 3323 (LHSExp->getType()->isRecordType() || 3324 LHSExp->getType()->isEnumeralType() || 3325 RHSExp->getType()->isRecordType() || 3326 RHSExp->getType()->isEnumeralType()) && 3327 !LHSExp->getType()->isObjCObjectPointerType()) { 3328 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx); 3329 } 3330 3331 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc); 3332} 3333 3334ExprResult 3335Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 3336 Expr *Idx, SourceLocation RLoc) { 3337 Expr *LHSExp = Base; 3338 Expr *RHSExp = Idx; 3339 3340 // Perform default conversions. 3341 if (!LHSExp->getType()->getAs<VectorType>()) { 3342 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 3343 if (Result.isInvalid()) 3344 return ExprError(); 3345 LHSExp = Result.take(); 3346 } 3347 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 3348 if (Result.isInvalid()) 3349 return ExprError(); 3350 RHSExp = Result.take(); 3351 3352 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 3353 ExprValueKind VK = VK_LValue; 3354 ExprObjectKind OK = OK_Ordinary; 3355 3356 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 3357 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 3358 // in the subscript position. As a result, we need to derive the array base 3359 // and index from the expression types. 3360 Expr *BaseExpr, *IndexExpr; 3361 QualType ResultType; 3362 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 3363 BaseExpr = LHSExp; 3364 IndexExpr = RHSExp; 3365 ResultType = Context.DependentTy; 3366 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 3367 BaseExpr = LHSExp; 3368 IndexExpr = RHSExp; 3369 ResultType = PTy->getPointeeType(); 3370 } else if (const ObjCObjectPointerType *PTy = 3371 LHSTy->getAs<ObjCObjectPointerType>()) { 3372 BaseExpr = LHSExp; 3373 IndexExpr = RHSExp; 3374 3375 // Use custom logic if this should be the pseudo-object subscript 3376 // expression. 3377 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic()) 3378 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0); 3379 3380 ResultType = PTy->getPointeeType(); 3381 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) { 3382 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3383 << ResultType << BaseExpr->getSourceRange(); 3384 return ExprError(); 3385 } 3386 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 3387 // Handle the uncommon case of "123[Ptr]". 3388 BaseExpr = RHSExp; 3389 IndexExpr = LHSExp; 3390 ResultType = PTy->getPointeeType(); 3391 } else if (const ObjCObjectPointerType *PTy = 3392 RHSTy->getAs<ObjCObjectPointerType>()) { 3393 // Handle the uncommon case of "123[Ptr]". 3394 BaseExpr = RHSExp; 3395 IndexExpr = LHSExp; 3396 ResultType = PTy->getPointeeType(); 3397 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) { 3398 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3399 << ResultType << BaseExpr->getSourceRange(); 3400 return ExprError(); 3401 } 3402 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 3403 BaseExpr = LHSExp; // vectors: V[123] 3404 IndexExpr = RHSExp; 3405 VK = LHSExp->getValueKind(); 3406 if (VK != VK_RValue) 3407 OK = OK_VectorComponent; 3408 3409 // FIXME: need to deal with const... 3410 ResultType = VTy->getElementType(); 3411 } else if (LHSTy->isArrayType()) { 3412 // If we see an array that wasn't promoted by 3413 // DefaultFunctionArrayLvalueConversion, it must be an array that 3414 // wasn't promoted because of the C90 rule that doesn't 3415 // allow promoting non-lvalue arrays. Warn, then 3416 // force the promotion here. 3417 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3418 LHSExp->getSourceRange(); 3419 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 3420 CK_ArrayToPointerDecay).take(); 3421 LHSTy = LHSExp->getType(); 3422 3423 BaseExpr = LHSExp; 3424 IndexExpr = RHSExp; 3425 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 3426 } else if (RHSTy->isArrayType()) { 3427 // Same as previous, except for 123[f().a] case 3428 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3429 RHSExp->getSourceRange(); 3430 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 3431 CK_ArrayToPointerDecay).take(); 3432 RHSTy = RHSExp->getType(); 3433 3434 BaseExpr = RHSExp; 3435 IndexExpr = LHSExp; 3436 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 3437 } else { 3438 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 3439 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 3440 } 3441 // C99 6.5.2.1p1 3442 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 3443 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 3444 << IndexExpr->getSourceRange()); 3445 3446 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 3447 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 3448 && !IndexExpr->isTypeDependent()) 3449 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 3450 3451 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 3452 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 3453 // type. Note that Functions are not objects, and that (in C99 parlance) 3454 // incomplete types are not object types. 3455 if (ResultType->isFunctionType()) { 3456 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 3457 << ResultType << BaseExpr->getSourceRange(); 3458 return ExprError(); 3459 } 3460 3461 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 3462 // GNU extension: subscripting on pointer to void 3463 Diag(LLoc, diag::ext_gnu_subscript_void_type) 3464 << BaseExpr->getSourceRange(); 3465 3466 // C forbids expressions of unqualified void type from being l-values. 3467 // See IsCForbiddenLValueType. 3468 if (!ResultType.hasQualifiers()) VK = VK_RValue; 3469 } else if (!ResultType->isDependentType() && 3470 RequireCompleteType(LLoc, ResultType, 3471 diag::err_subscript_incomplete_type, BaseExpr)) 3472 return ExprError(); 3473 3474 assert(VK == VK_RValue || LangOpts.CPlusPlus || 3475 !ResultType.isCForbiddenLValueType()); 3476 3477 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 3478 ResultType, VK, OK, RLoc)); 3479} 3480 3481ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3482 FunctionDecl *FD, 3483 ParmVarDecl *Param) { 3484 if (Param->hasUnparsedDefaultArg()) { 3485 Diag(CallLoc, 3486 diag::err_use_of_default_argument_to_function_declared_later) << 3487 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 3488 Diag(UnparsedDefaultArgLocs[Param], 3489 diag::note_default_argument_declared_here); 3490 return ExprError(); 3491 } 3492 3493 if (Param->hasUninstantiatedDefaultArg()) { 3494 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 3495 3496 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 3497 Param); 3498 3499 // Instantiate the expression. 3500 MultiLevelTemplateArgumentList ArgList 3501 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true); 3502 3503 std::pair<const TemplateArgument *, unsigned> Innermost 3504 = ArgList.getInnermost(); 3505 InstantiatingTemplate Inst(*this, CallLoc, Param, 3506 ArrayRef<TemplateArgument>(Innermost.first, 3507 Innermost.second)); 3508 if (Inst) 3509 return ExprError(); 3510 3511 ExprResult Result; 3512 { 3513 // C++ [dcl.fct.default]p5: 3514 // The names in the [default argument] expression are bound, and 3515 // the semantic constraints are checked, at the point where the 3516 // default argument expression appears. 3517 ContextRAII SavedContext(*this, FD); 3518 LocalInstantiationScope Local(*this); 3519 Result = SubstExpr(UninstExpr, ArgList); 3520 } 3521 if (Result.isInvalid()) 3522 return ExprError(); 3523 3524 // Check the expression as an initializer for the parameter. 3525 InitializedEntity Entity 3526 = InitializedEntity::InitializeParameter(Context, Param); 3527 InitializationKind Kind 3528 = InitializationKind::CreateCopy(Param->getLocation(), 3529 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 3530 Expr *ResultE = Result.takeAs<Expr>(); 3531 3532 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1); 3533 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 3534 if (Result.isInvalid()) 3535 return ExprError(); 3536 3537 Expr *Arg = Result.takeAs<Expr>(); 3538 CheckImplicitConversions(Arg, Param->getOuterLocStart()); 3539 // Build the default argument expression. 3540 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg)); 3541 } 3542 3543 // If the default expression creates temporaries, we need to 3544 // push them to the current stack of expression temporaries so they'll 3545 // be properly destroyed. 3546 // FIXME: We should really be rebuilding the default argument with new 3547 // bound temporaries; see the comment in PR5810. 3548 // We don't need to do that with block decls, though, because 3549 // blocks in default argument expression can never capture anything. 3550 if (isa<ExprWithCleanups>(Param->getInit())) { 3551 // Set the "needs cleanups" bit regardless of whether there are 3552 // any explicit objects. 3553 ExprNeedsCleanups = true; 3554 3555 // Append all the objects to the cleanup list. Right now, this 3556 // should always be a no-op, because blocks in default argument 3557 // expressions should never be able to capture anything. 3558 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 3559 "default argument expression has capturing blocks?"); 3560 } 3561 3562 // We already type-checked the argument, so we know it works. 3563 // Just mark all of the declarations in this potentially-evaluated expression 3564 // as being "referenced". 3565 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 3566 /*SkipLocalVariables=*/true); 3567 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param)); 3568} 3569 3570 3571Sema::VariadicCallType 3572Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 3573 Expr *Fn) { 3574 if (Proto && Proto->isVariadic()) { 3575 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 3576 return VariadicConstructor; 3577 else if (Fn && Fn->getType()->isBlockPointerType()) 3578 return VariadicBlock; 3579 else if (FDecl) { 3580 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 3581 if (Method->isInstance()) 3582 return VariadicMethod; 3583 } 3584 return VariadicFunction; 3585 } 3586 return VariadicDoesNotApply; 3587} 3588 3589/// ConvertArgumentsForCall - Converts the arguments specified in 3590/// Args/NumArgs to the parameter types of the function FDecl with 3591/// function prototype Proto. Call is the call expression itself, and 3592/// Fn is the function expression. For a C++ member function, this 3593/// routine does not attempt to convert the object argument. Returns 3594/// true if the call is ill-formed. 3595bool 3596Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 3597 FunctionDecl *FDecl, 3598 const FunctionProtoType *Proto, 3599 Expr **Args, unsigned NumArgs, 3600 SourceLocation RParenLoc, 3601 bool IsExecConfig) { 3602 // Bail out early if calling a builtin with custom typechecking. 3603 // We don't need to do this in the 3604 if (FDecl) 3605 if (unsigned ID = FDecl->getBuiltinID()) 3606 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 3607 return false; 3608 3609 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 3610 // assignment, to the types of the corresponding parameter, ... 3611 unsigned NumArgsInProto = Proto->getNumArgs(); 3612 bool Invalid = false; 3613 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto; 3614 unsigned FnKind = Fn->getType()->isBlockPointerType() 3615 ? 1 /* block */ 3616 : (IsExecConfig ? 3 /* kernel function (exec config) */ 3617 : 0 /* function */); 3618 3619 // If too few arguments are available (and we don't have default 3620 // arguments for the remaining parameters), don't make the call. 3621 if (NumArgs < NumArgsInProto) { 3622 if (NumArgs < MinArgs) { 3623 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 3624 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic() 3625 ? diag::err_typecheck_call_too_few_args_one 3626 : diag::err_typecheck_call_too_few_args_at_least_one) 3627 << FnKind 3628 << FDecl->getParamDecl(0) << Fn->getSourceRange(); 3629 else 3630 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic() 3631 ? diag::err_typecheck_call_too_few_args 3632 : diag::err_typecheck_call_too_few_args_at_least) 3633 << FnKind 3634 << MinArgs << NumArgs << Fn->getSourceRange(); 3635 3636 // Emit the location of the prototype. 3637 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 3638 Diag(FDecl->getLocStart(), diag::note_callee_decl) 3639 << FDecl; 3640 3641 return true; 3642 } 3643 Call->setNumArgs(Context, NumArgsInProto); 3644 } 3645 3646 // If too many are passed and not variadic, error on the extras and drop 3647 // them. 3648 if (NumArgs > NumArgsInProto) { 3649 if (!Proto->isVariadic()) { 3650 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 3651 Diag(Args[NumArgsInProto]->getLocStart(), 3652 MinArgs == NumArgsInProto 3653 ? diag::err_typecheck_call_too_many_args_one 3654 : diag::err_typecheck_call_too_many_args_at_most_one) 3655 << FnKind 3656 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange() 3657 << SourceRange(Args[NumArgsInProto]->getLocStart(), 3658 Args[NumArgs-1]->getLocEnd()); 3659 else 3660 Diag(Args[NumArgsInProto]->getLocStart(), 3661 MinArgs == NumArgsInProto 3662 ? diag::err_typecheck_call_too_many_args 3663 : diag::err_typecheck_call_too_many_args_at_most) 3664 << FnKind 3665 << NumArgsInProto << NumArgs << Fn->getSourceRange() 3666 << SourceRange(Args[NumArgsInProto]->getLocStart(), 3667 Args[NumArgs-1]->getLocEnd()); 3668 3669 // Emit the location of the prototype. 3670 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 3671 Diag(FDecl->getLocStart(), diag::note_callee_decl) 3672 << FDecl; 3673 3674 // This deletes the extra arguments. 3675 Call->setNumArgs(Context, NumArgsInProto); 3676 return true; 3677 } 3678 } 3679 SmallVector<Expr *, 8> AllArgs; 3680 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 3681 3682 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 3683 Proto, 0, Args, NumArgs, AllArgs, CallType); 3684 if (Invalid) 3685 return true; 3686 unsigned TotalNumArgs = AllArgs.size(); 3687 for (unsigned i = 0; i < TotalNumArgs; ++i) 3688 Call->setArg(i, AllArgs[i]); 3689 3690 return false; 3691} 3692 3693bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, 3694 FunctionDecl *FDecl, 3695 const FunctionProtoType *Proto, 3696 unsigned FirstProtoArg, 3697 Expr **Args, unsigned NumArgs, 3698 SmallVector<Expr *, 8> &AllArgs, 3699 VariadicCallType CallType, 3700 bool AllowExplicit) { 3701 unsigned NumArgsInProto = Proto->getNumArgs(); 3702 unsigned NumArgsToCheck = NumArgs; 3703 bool Invalid = false; 3704 if (NumArgs != NumArgsInProto) 3705 // Use default arguments for missing arguments 3706 NumArgsToCheck = NumArgsInProto; 3707 unsigned ArgIx = 0; 3708 // Continue to check argument types (even if we have too few/many args). 3709 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) { 3710 QualType ProtoArgType = Proto->getArgType(i); 3711 3712 Expr *Arg; 3713 ParmVarDecl *Param; 3714 if (ArgIx < NumArgs) { 3715 Arg = Args[ArgIx++]; 3716 3717 if (RequireCompleteType(Arg->getLocStart(), 3718 ProtoArgType, 3719 diag::err_call_incomplete_argument, Arg)) 3720 return true; 3721 3722 // Pass the argument 3723 Param = 0; 3724 if (FDecl && i < FDecl->getNumParams()) 3725 Param = FDecl->getParamDecl(i); 3726 3727 // Strip the unbridged-cast placeholder expression off, if applicable. 3728 if (Arg->getType() == Context.ARCUnbridgedCastTy && 3729 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 3730 (!Param || !Param->hasAttr<CFConsumedAttr>())) 3731 Arg = stripARCUnbridgedCast(Arg); 3732 3733 InitializedEntity Entity = 3734 Param? InitializedEntity::InitializeParameter(Context, Param) 3735 : InitializedEntity::InitializeParameter(Context, ProtoArgType, 3736 Proto->isArgConsumed(i)); 3737 ExprResult ArgE = PerformCopyInitialization(Entity, 3738 SourceLocation(), 3739 Owned(Arg), 3740 /*TopLevelOfInitList=*/false, 3741 AllowExplicit); 3742 if (ArgE.isInvalid()) 3743 return true; 3744 3745 Arg = ArgE.takeAs<Expr>(); 3746 } else { 3747 Param = FDecl->getParamDecl(i); 3748 3749 ExprResult ArgExpr = 3750 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 3751 if (ArgExpr.isInvalid()) 3752 return true; 3753 3754 Arg = ArgExpr.takeAs<Expr>(); 3755 } 3756 3757 // Check for array bounds violations for each argument to the call. This 3758 // check only triggers warnings when the argument isn't a more complex Expr 3759 // with its own checking, such as a BinaryOperator. 3760 CheckArrayAccess(Arg); 3761 3762 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 3763 CheckStaticArrayArgument(CallLoc, Param, Arg); 3764 3765 AllArgs.push_back(Arg); 3766 } 3767 3768 // If this is a variadic call, handle args passed through "...". 3769 if (CallType != VariadicDoesNotApply) { 3770 // Assume that extern "C" functions with variadic arguments that 3771 // return __unknown_anytype aren't *really* variadic. 3772 if (Proto->getResultType() == Context.UnknownAnyTy && 3773 FDecl && FDecl->isExternC()) { 3774 for (unsigned i = ArgIx; i != NumArgs; ++i) { 3775 ExprResult arg; 3776 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens())) 3777 arg = DefaultFunctionArrayLvalueConversion(Args[i]); 3778 else 3779 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl); 3780 Invalid |= arg.isInvalid(); 3781 AllArgs.push_back(arg.take()); 3782 } 3783 3784 // Otherwise do argument promotion, (C99 6.5.2.2p7). 3785 } else { 3786 for (unsigned i = ArgIx; i != NumArgs; ++i) { 3787 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 3788 FDecl); 3789 Invalid |= Arg.isInvalid(); 3790 AllArgs.push_back(Arg.take()); 3791 } 3792 } 3793 3794 // Check for array bounds violations. 3795 for (unsigned i = ArgIx; i != NumArgs; ++i) 3796 CheckArrayAccess(Args[i]); 3797 } 3798 return Invalid; 3799} 3800 3801static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 3802 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 3803 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL)) 3804 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 3805 << ATL->getLocalSourceRange(); 3806} 3807 3808/// CheckStaticArrayArgument - If the given argument corresponds to a static 3809/// array parameter, check that it is non-null, and that if it is formed by 3810/// array-to-pointer decay, the underlying array is sufficiently large. 3811/// 3812/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 3813/// array type derivation, then for each call to the function, the value of the 3814/// corresponding actual argument shall provide access to the first element of 3815/// an array with at least as many elements as specified by the size expression. 3816void 3817Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 3818 ParmVarDecl *Param, 3819 const Expr *ArgExpr) { 3820 // Static array parameters are not supported in C++. 3821 if (!Param || getLangOpts().CPlusPlus) 3822 return; 3823 3824 QualType OrigTy = Param->getOriginalType(); 3825 3826 const ArrayType *AT = Context.getAsArrayType(OrigTy); 3827 if (!AT || AT->getSizeModifier() != ArrayType::Static) 3828 return; 3829 3830 if (ArgExpr->isNullPointerConstant(Context, 3831 Expr::NPC_NeverValueDependent)) { 3832 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 3833 DiagnoseCalleeStaticArrayParam(*this, Param); 3834 return; 3835 } 3836 3837 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 3838 if (!CAT) 3839 return; 3840 3841 const ConstantArrayType *ArgCAT = 3842 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 3843 if (!ArgCAT) 3844 return; 3845 3846 if (ArgCAT->getSize().ult(CAT->getSize())) { 3847 Diag(CallLoc, diag::warn_static_array_too_small) 3848 << ArgExpr->getSourceRange() 3849 << (unsigned) ArgCAT->getSize().getZExtValue() 3850 << (unsigned) CAT->getSize().getZExtValue(); 3851 DiagnoseCalleeStaticArrayParam(*this, Param); 3852 } 3853} 3854 3855/// Given a function expression of unknown-any type, try to rebuild it 3856/// to have a function type. 3857static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 3858 3859/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 3860/// This provides the location of the left/right parens and a list of comma 3861/// locations. 3862ExprResult 3863Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 3864 MultiExprArg ArgExprs, SourceLocation RParenLoc, 3865 Expr *ExecConfig, bool IsExecConfig) { 3866 // Since this might be a postfix expression, get rid of ParenListExprs. 3867 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 3868 if (Result.isInvalid()) return ExprError(); 3869 Fn = Result.take(); 3870 3871 if (getLangOpts().CPlusPlus) { 3872 // If this is a pseudo-destructor expression, build the call immediately. 3873 if (isa<CXXPseudoDestructorExpr>(Fn)) { 3874 if (!ArgExprs.empty()) { 3875 // Pseudo-destructor calls should not have any arguments. 3876 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 3877 << FixItHint::CreateRemoval( 3878 SourceRange(ArgExprs[0]->getLocStart(), 3879 ArgExprs.back()->getLocEnd())); 3880 } 3881 3882 return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(), 3883 Context.VoidTy, VK_RValue, 3884 RParenLoc)); 3885 } 3886 3887 // Determine whether this is a dependent call inside a C++ template, 3888 // in which case we won't do any semantic analysis now. 3889 // FIXME: Will need to cache the results of name lookup (including ADL) in 3890 // Fn. 3891 bool Dependent = false; 3892 if (Fn->isTypeDependent()) 3893 Dependent = true; 3894 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 3895 Dependent = true; 3896 3897 if (Dependent) { 3898 if (ExecConfig) { 3899 return Owned(new (Context) CUDAKernelCallExpr( 3900 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 3901 Context.DependentTy, VK_RValue, RParenLoc)); 3902 } else { 3903 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs, 3904 Context.DependentTy, VK_RValue, 3905 RParenLoc)); 3906 } 3907 } 3908 3909 // Determine whether this is a call to an object (C++ [over.call.object]). 3910 if (Fn->getType()->isRecordType()) 3911 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, 3912 ArgExprs.data(), 3913 ArgExprs.size(), RParenLoc)); 3914 3915 if (Fn->getType() == Context.UnknownAnyTy) { 3916 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 3917 if (result.isInvalid()) return ExprError(); 3918 Fn = result.take(); 3919 } 3920 3921 if (Fn->getType() == Context.BoundMemberTy) { 3922 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(), 3923 ArgExprs.size(), RParenLoc); 3924 } 3925 } 3926 3927 // Check for overloaded calls. This can happen even in C due to extensions. 3928 if (Fn->getType() == Context.OverloadTy) { 3929 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 3930 3931 // We aren't supposed to apply this logic for if there's an '&' involved. 3932 if (!find.HasFormOfMemberPointer) { 3933 OverloadExpr *ovl = find.Expression; 3934 if (isa<UnresolvedLookupExpr>(ovl)) { 3935 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 3936 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(), 3937 ArgExprs.size(), RParenLoc, ExecConfig); 3938 } else { 3939 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(), 3940 ArgExprs.size(), RParenLoc); 3941 } 3942 } 3943 } 3944 3945 // If we're directly calling a function, get the appropriate declaration. 3946 if (Fn->getType() == Context.UnknownAnyTy) { 3947 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 3948 if (result.isInvalid()) return ExprError(); 3949 Fn = result.take(); 3950 } 3951 3952 Expr *NakedFn = Fn->IgnoreParens(); 3953 3954 NamedDecl *NDecl = 0; 3955 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 3956 if (UnOp->getOpcode() == UO_AddrOf) 3957 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 3958 3959 if (isa<DeclRefExpr>(NakedFn)) 3960 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 3961 else if (isa<MemberExpr>(NakedFn)) 3962 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 3963 3964 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(), 3965 ArgExprs.size(), RParenLoc, ExecConfig, 3966 IsExecConfig); 3967} 3968 3969ExprResult 3970Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 3971 MultiExprArg ExecConfig, SourceLocation GGGLoc) { 3972 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl(); 3973 if (!ConfigDecl) 3974 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use) 3975 << "cudaConfigureCall"); 3976 QualType ConfigQTy = ConfigDecl->getType(); 3977 3978 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr( 3979 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc); 3980 MarkFunctionReferenced(LLLLoc, ConfigDecl); 3981 3982 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0, 3983 /*IsExecConfig=*/true); 3984} 3985 3986/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 3987/// 3988/// __builtin_astype( value, dst type ) 3989/// 3990ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 3991 SourceLocation BuiltinLoc, 3992 SourceLocation RParenLoc) { 3993 ExprValueKind VK = VK_RValue; 3994 ExprObjectKind OK = OK_Ordinary; 3995 QualType DstTy = GetTypeFromParser(ParsedDestTy); 3996 QualType SrcTy = E->getType(); 3997 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 3998 return ExprError(Diag(BuiltinLoc, 3999 diag::err_invalid_astype_of_different_size) 4000 << DstTy 4001 << SrcTy 4002 << E->getSourceRange()); 4003 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, 4004 RParenLoc)); 4005} 4006 4007/// BuildResolvedCallExpr - Build a call to a resolved expression, 4008/// i.e. an expression not of \p OverloadTy. The expression should 4009/// unary-convert to an expression of function-pointer or 4010/// block-pointer type. 4011/// 4012/// \param NDecl the declaration being called, if available 4013ExprResult 4014Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 4015 SourceLocation LParenLoc, 4016 Expr **Args, unsigned NumArgs, 4017 SourceLocation RParenLoc, 4018 Expr *Config, bool IsExecConfig) { 4019 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 4020 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 4021 4022 // Promote the function operand. 4023 // We special-case function promotion here because we only allow promoting 4024 // builtin functions to function pointers in the callee of a call. 4025 ExprResult Result; 4026 if (BuiltinID && 4027 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 4028 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 4029 CK_BuiltinFnToFnPtr).take(); 4030 } else { 4031 Result = UsualUnaryConversions(Fn); 4032 } 4033 if (Result.isInvalid()) 4034 return ExprError(); 4035 Fn = Result.take(); 4036 4037 // Make the call expr early, before semantic checks. This guarantees cleanup 4038 // of arguments and function on error. 4039 CallExpr *TheCall; 4040 if (Config) 4041 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 4042 cast<CallExpr>(Config), 4043 llvm::makeArrayRef(Args,NumArgs), 4044 Context.BoolTy, 4045 VK_RValue, 4046 RParenLoc); 4047 else 4048 TheCall = new (Context) CallExpr(Context, Fn, 4049 llvm::makeArrayRef(Args, NumArgs), 4050 Context.BoolTy, 4051 VK_RValue, 4052 RParenLoc); 4053 4054 // Bail out early if calling a builtin with custom typechecking. 4055 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 4056 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4057 4058 retry: 4059 const FunctionType *FuncT; 4060 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 4061 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 4062 // have type pointer to function". 4063 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 4064 if (FuncT == 0) 4065 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4066 << Fn->getType() << Fn->getSourceRange()); 4067 } else if (const BlockPointerType *BPT = 4068 Fn->getType()->getAs<BlockPointerType>()) { 4069 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 4070 } else { 4071 // Handle calls to expressions of unknown-any type. 4072 if (Fn->getType() == Context.UnknownAnyTy) { 4073 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 4074 if (rewrite.isInvalid()) return ExprError(); 4075 Fn = rewrite.take(); 4076 TheCall->setCallee(Fn); 4077 goto retry; 4078 } 4079 4080 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4081 << Fn->getType() << Fn->getSourceRange()); 4082 } 4083 4084 if (getLangOpts().CUDA) { 4085 if (Config) { 4086 // CUDA: Kernel calls must be to global functions 4087 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 4088 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 4089 << FDecl->getName() << Fn->getSourceRange()); 4090 4091 // CUDA: Kernel function must have 'void' return type 4092 if (!FuncT->getResultType()->isVoidType()) 4093 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 4094 << Fn->getType() << Fn->getSourceRange()); 4095 } else { 4096 // CUDA: Calls to global functions must be configured 4097 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 4098 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 4099 << FDecl->getName() << Fn->getSourceRange()); 4100 } 4101 } 4102 4103 // Check for a valid return type 4104 if (CheckCallReturnType(FuncT->getResultType(), 4105 Fn->getLocStart(), TheCall, 4106 FDecl)) 4107 return ExprError(); 4108 4109 // We know the result type of the call, set it. 4110 TheCall->setType(FuncT->getCallResultType(Context)); 4111 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType())); 4112 4113 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 4114 if (Proto) { 4115 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs, 4116 RParenLoc, IsExecConfig)) 4117 return ExprError(); 4118 } else { 4119 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 4120 4121 if (FDecl) { 4122 // Check if we have too few/too many template arguments, based 4123 // on our knowledge of the function definition. 4124 const FunctionDecl *Def = 0; 4125 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) { 4126 Proto = Def->getType()->getAs<FunctionProtoType>(); 4127 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) 4128 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 4129 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange(); 4130 } 4131 4132 // If the function we're calling isn't a function prototype, but we have 4133 // a function prototype from a prior declaratiom, use that prototype. 4134 if (!FDecl->hasPrototype()) 4135 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 4136 } 4137 4138 // Promote the arguments (C99 6.5.2.2p6). 4139 for (unsigned i = 0; i != NumArgs; i++) { 4140 Expr *Arg = Args[i]; 4141 4142 if (Proto && i < Proto->getNumArgs()) { 4143 InitializedEntity Entity 4144 = InitializedEntity::InitializeParameter(Context, 4145 Proto->getArgType(i), 4146 Proto->isArgConsumed(i)); 4147 ExprResult ArgE = PerformCopyInitialization(Entity, 4148 SourceLocation(), 4149 Owned(Arg)); 4150 if (ArgE.isInvalid()) 4151 return true; 4152 4153 Arg = ArgE.takeAs<Expr>(); 4154 4155 } else { 4156 ExprResult ArgE = DefaultArgumentPromotion(Arg); 4157 4158 if (ArgE.isInvalid()) 4159 return true; 4160 4161 Arg = ArgE.takeAs<Expr>(); 4162 } 4163 4164 if (RequireCompleteType(Arg->getLocStart(), 4165 Arg->getType(), 4166 diag::err_call_incomplete_argument, Arg)) 4167 return ExprError(); 4168 4169 TheCall->setArg(i, Arg); 4170 } 4171 } 4172 4173 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4174 if (!Method->isStatic()) 4175 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 4176 << Fn->getSourceRange()); 4177 4178 // Check for sentinels 4179 if (NDecl) 4180 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs); 4181 4182 // Do special checking on direct calls to functions. 4183 if (FDecl) { 4184 if (CheckFunctionCall(FDecl, TheCall, Proto)) 4185 return ExprError(); 4186 4187 if (BuiltinID) 4188 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4189 } else if (NDecl) { 4190 if (CheckBlockCall(NDecl, TheCall, Proto)) 4191 return ExprError(); 4192 } 4193 4194 return MaybeBindToTemporary(TheCall); 4195} 4196 4197ExprResult 4198Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 4199 SourceLocation RParenLoc, Expr *InitExpr) { 4200 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type"); 4201 // FIXME: put back this assert when initializers are worked out. 4202 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 4203 4204 TypeSourceInfo *TInfo; 4205 QualType literalType = GetTypeFromParser(Ty, &TInfo); 4206 if (!TInfo) 4207 TInfo = Context.getTrivialTypeSourceInfo(literalType); 4208 4209 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 4210} 4211 4212ExprResult 4213Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 4214 SourceLocation RParenLoc, Expr *LiteralExpr) { 4215 QualType literalType = TInfo->getType(); 4216 4217 if (literalType->isArrayType()) { 4218 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 4219 diag::err_illegal_decl_array_incomplete_type, 4220 SourceRange(LParenLoc, 4221 LiteralExpr->getSourceRange().getEnd()))) 4222 return ExprError(); 4223 if (literalType->isVariableArrayType()) 4224 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 4225 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 4226 } else if (!literalType->isDependentType() && 4227 RequireCompleteType(LParenLoc, literalType, 4228 diag::err_typecheck_decl_incomplete_type, 4229 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 4230 return ExprError(); 4231 4232 InitializedEntity Entity 4233 = InitializedEntity::InitializeTemporary(literalType); 4234 InitializationKind Kind 4235 = InitializationKind::CreateCStyleCast(LParenLoc, 4236 SourceRange(LParenLoc, RParenLoc), 4237 /*InitList=*/true); 4238 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1); 4239 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 4240 &literalType); 4241 if (Result.isInvalid()) 4242 return ExprError(); 4243 LiteralExpr = Result.get(); 4244 4245 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 4246 if (isFileScope) { // 6.5.2.5p3 4247 if (CheckForConstantInitializer(LiteralExpr, literalType)) 4248 return ExprError(); 4249 } 4250 4251 // In C, compound literals are l-values for some reason. 4252 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 4253 4254 return MaybeBindToTemporary( 4255 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 4256 VK, LiteralExpr, isFileScope)); 4257} 4258 4259ExprResult 4260Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 4261 SourceLocation RBraceLoc) { 4262 // Immediately handle non-overload placeholders. Overloads can be 4263 // resolved contextually, but everything else here can't. 4264 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 4265 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 4266 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 4267 4268 // Ignore failures; dropping the entire initializer list because 4269 // of one failure would be terrible for indexing/etc. 4270 if (result.isInvalid()) continue; 4271 4272 InitArgList[I] = result.take(); 4273 } 4274 } 4275 4276 // Semantic analysis for initializers is done by ActOnDeclarator() and 4277 // CheckInitializer() - it requires knowledge of the object being intialized. 4278 4279 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 4280 RBraceLoc); 4281 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 4282 return Owned(E); 4283} 4284 4285/// Do an explicit extend of the given block pointer if we're in ARC. 4286static void maybeExtendBlockObject(Sema &S, ExprResult &E) { 4287 assert(E.get()->getType()->isBlockPointerType()); 4288 assert(E.get()->isRValue()); 4289 4290 // Only do this in an r-value context. 4291 if (!S.getLangOpts().ObjCAutoRefCount) return; 4292 4293 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), 4294 CK_ARCExtendBlockObject, E.get(), 4295 /*base path*/ 0, VK_RValue); 4296 S.ExprNeedsCleanups = true; 4297} 4298 4299/// Prepare a conversion of the given expression to an ObjC object 4300/// pointer type. 4301CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 4302 QualType type = E.get()->getType(); 4303 if (type->isObjCObjectPointerType()) { 4304 return CK_BitCast; 4305 } else if (type->isBlockPointerType()) { 4306 maybeExtendBlockObject(*this, E); 4307 return CK_BlockPointerToObjCPointerCast; 4308 } else { 4309 assert(type->isPointerType()); 4310 return CK_CPointerToObjCPointerCast; 4311 } 4312} 4313 4314/// Prepares for a scalar cast, performing all the necessary stages 4315/// except the final cast and returning the kind required. 4316CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 4317 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 4318 // Also, callers should have filtered out the invalid cases with 4319 // pointers. Everything else should be possible. 4320 4321 QualType SrcTy = Src.get()->getType(); 4322 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 4323 return CK_NoOp; 4324 4325 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 4326 case Type::STK_MemberPointer: 4327 llvm_unreachable("member pointer type in C"); 4328 4329 case Type::STK_CPointer: 4330 case Type::STK_BlockPointer: 4331 case Type::STK_ObjCObjectPointer: 4332 switch (DestTy->getScalarTypeKind()) { 4333 case Type::STK_CPointer: 4334 return CK_BitCast; 4335 case Type::STK_BlockPointer: 4336 return (SrcKind == Type::STK_BlockPointer 4337 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 4338 case Type::STK_ObjCObjectPointer: 4339 if (SrcKind == Type::STK_ObjCObjectPointer) 4340 return CK_BitCast; 4341 if (SrcKind == Type::STK_CPointer) 4342 return CK_CPointerToObjCPointerCast; 4343 maybeExtendBlockObject(*this, Src); 4344 return CK_BlockPointerToObjCPointerCast; 4345 case Type::STK_Bool: 4346 return CK_PointerToBoolean; 4347 case Type::STK_Integral: 4348 return CK_PointerToIntegral; 4349 case Type::STK_Floating: 4350 case Type::STK_FloatingComplex: 4351 case Type::STK_IntegralComplex: 4352 case Type::STK_MemberPointer: 4353 llvm_unreachable("illegal cast from pointer"); 4354 } 4355 llvm_unreachable("Should have returned before this"); 4356 4357 case Type::STK_Bool: // casting from bool is like casting from an integer 4358 case Type::STK_Integral: 4359 switch (DestTy->getScalarTypeKind()) { 4360 case Type::STK_CPointer: 4361 case Type::STK_ObjCObjectPointer: 4362 case Type::STK_BlockPointer: 4363 if (Src.get()->isNullPointerConstant(Context, 4364 Expr::NPC_ValueDependentIsNull)) 4365 return CK_NullToPointer; 4366 return CK_IntegralToPointer; 4367 case Type::STK_Bool: 4368 return CK_IntegralToBoolean; 4369 case Type::STK_Integral: 4370 return CK_IntegralCast; 4371 case Type::STK_Floating: 4372 return CK_IntegralToFloating; 4373 case Type::STK_IntegralComplex: 4374 Src = ImpCastExprToType(Src.take(), 4375 DestTy->castAs<ComplexType>()->getElementType(), 4376 CK_IntegralCast); 4377 return CK_IntegralRealToComplex; 4378 case Type::STK_FloatingComplex: 4379 Src = ImpCastExprToType(Src.take(), 4380 DestTy->castAs<ComplexType>()->getElementType(), 4381 CK_IntegralToFloating); 4382 return CK_FloatingRealToComplex; 4383 case Type::STK_MemberPointer: 4384 llvm_unreachable("member pointer type in C"); 4385 } 4386 llvm_unreachable("Should have returned before this"); 4387 4388 case Type::STK_Floating: 4389 switch (DestTy->getScalarTypeKind()) { 4390 case Type::STK_Floating: 4391 return CK_FloatingCast; 4392 case Type::STK_Bool: 4393 return CK_FloatingToBoolean; 4394 case Type::STK_Integral: 4395 return CK_FloatingToIntegral; 4396 case Type::STK_FloatingComplex: 4397 Src = ImpCastExprToType(Src.take(), 4398 DestTy->castAs<ComplexType>()->getElementType(), 4399 CK_FloatingCast); 4400 return CK_FloatingRealToComplex; 4401 case Type::STK_IntegralComplex: 4402 Src = ImpCastExprToType(Src.take(), 4403 DestTy->castAs<ComplexType>()->getElementType(), 4404 CK_FloatingToIntegral); 4405 return CK_IntegralRealToComplex; 4406 case Type::STK_CPointer: 4407 case Type::STK_ObjCObjectPointer: 4408 case Type::STK_BlockPointer: 4409 llvm_unreachable("valid float->pointer cast?"); 4410 case Type::STK_MemberPointer: 4411 llvm_unreachable("member pointer type in C"); 4412 } 4413 llvm_unreachable("Should have returned before this"); 4414 4415 case Type::STK_FloatingComplex: 4416 switch (DestTy->getScalarTypeKind()) { 4417 case Type::STK_FloatingComplex: 4418 return CK_FloatingComplexCast; 4419 case Type::STK_IntegralComplex: 4420 return CK_FloatingComplexToIntegralComplex; 4421 case Type::STK_Floating: { 4422 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4423 if (Context.hasSameType(ET, DestTy)) 4424 return CK_FloatingComplexToReal; 4425 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal); 4426 return CK_FloatingCast; 4427 } 4428 case Type::STK_Bool: 4429 return CK_FloatingComplexToBoolean; 4430 case Type::STK_Integral: 4431 Src = ImpCastExprToType(Src.take(), 4432 SrcTy->castAs<ComplexType>()->getElementType(), 4433 CK_FloatingComplexToReal); 4434 return CK_FloatingToIntegral; 4435 case Type::STK_CPointer: 4436 case Type::STK_ObjCObjectPointer: 4437 case Type::STK_BlockPointer: 4438 llvm_unreachable("valid complex float->pointer cast?"); 4439 case Type::STK_MemberPointer: 4440 llvm_unreachable("member pointer type in C"); 4441 } 4442 llvm_unreachable("Should have returned before this"); 4443 4444 case Type::STK_IntegralComplex: 4445 switch (DestTy->getScalarTypeKind()) { 4446 case Type::STK_FloatingComplex: 4447 return CK_IntegralComplexToFloatingComplex; 4448 case Type::STK_IntegralComplex: 4449 return CK_IntegralComplexCast; 4450 case Type::STK_Integral: { 4451 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4452 if (Context.hasSameType(ET, DestTy)) 4453 return CK_IntegralComplexToReal; 4454 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal); 4455 return CK_IntegralCast; 4456 } 4457 case Type::STK_Bool: 4458 return CK_IntegralComplexToBoolean; 4459 case Type::STK_Floating: 4460 Src = ImpCastExprToType(Src.take(), 4461 SrcTy->castAs<ComplexType>()->getElementType(), 4462 CK_IntegralComplexToReal); 4463 return CK_IntegralToFloating; 4464 case Type::STK_CPointer: 4465 case Type::STK_ObjCObjectPointer: 4466 case Type::STK_BlockPointer: 4467 llvm_unreachable("valid complex int->pointer cast?"); 4468 case Type::STK_MemberPointer: 4469 llvm_unreachable("member pointer type in C"); 4470 } 4471 llvm_unreachable("Should have returned before this"); 4472 } 4473 4474 llvm_unreachable("Unhandled scalar cast"); 4475} 4476 4477bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 4478 CastKind &Kind) { 4479 assert(VectorTy->isVectorType() && "Not a vector type!"); 4480 4481 if (Ty->isVectorType() || Ty->isIntegerType()) { 4482 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 4483 return Diag(R.getBegin(), 4484 Ty->isVectorType() ? 4485 diag::err_invalid_conversion_between_vectors : 4486 diag::err_invalid_conversion_between_vector_and_integer) 4487 << VectorTy << Ty << R; 4488 } else 4489 return Diag(R.getBegin(), 4490 diag::err_invalid_conversion_between_vector_and_scalar) 4491 << VectorTy << Ty << R; 4492 4493 Kind = CK_BitCast; 4494 return false; 4495} 4496 4497ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 4498 Expr *CastExpr, CastKind &Kind) { 4499 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 4500 4501 QualType SrcTy = CastExpr->getType(); 4502 4503 // If SrcTy is a VectorType, the total size must match to explicitly cast to 4504 // an ExtVectorType. 4505 // In OpenCL, casts between vectors of different types are not allowed. 4506 // (See OpenCL 6.2). 4507 if (SrcTy->isVectorType()) { 4508 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy) 4509 || (getLangOpts().OpenCL && 4510 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 4511 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 4512 << DestTy << SrcTy << R; 4513 return ExprError(); 4514 } 4515 Kind = CK_BitCast; 4516 return Owned(CastExpr); 4517 } 4518 4519 // All non-pointer scalars can be cast to ExtVector type. The appropriate 4520 // conversion will take place first from scalar to elt type, and then 4521 // splat from elt type to vector. 4522 if (SrcTy->isPointerType()) 4523 return Diag(R.getBegin(), 4524 diag::err_invalid_conversion_between_vector_and_scalar) 4525 << DestTy << SrcTy << R; 4526 4527 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 4528 ExprResult CastExprRes = Owned(CastExpr); 4529 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 4530 if (CastExprRes.isInvalid()) 4531 return ExprError(); 4532 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take(); 4533 4534 Kind = CK_VectorSplat; 4535 return Owned(CastExpr); 4536} 4537 4538ExprResult 4539Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 4540 Declarator &D, ParsedType &Ty, 4541 SourceLocation RParenLoc, Expr *CastExpr) { 4542 assert(!D.isInvalidType() && (CastExpr != 0) && 4543 "ActOnCastExpr(): missing type or expr"); 4544 4545 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 4546 if (D.isInvalidType()) 4547 return ExprError(); 4548 4549 if (getLangOpts().CPlusPlus) { 4550 // Check that there are no default arguments (C++ only). 4551 CheckExtraCXXDefaultArguments(D); 4552 } 4553 4554 checkUnusedDeclAttributes(D); 4555 4556 QualType castType = castTInfo->getType(); 4557 Ty = CreateParsedType(castType, castTInfo); 4558 4559 bool isVectorLiteral = false; 4560 4561 // Check for an altivec or OpenCL literal, 4562 // i.e. all the elements are integer constants. 4563 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 4564 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 4565 if ((getLangOpts().AltiVec || getLangOpts().OpenCL) 4566 && castType->isVectorType() && (PE || PLE)) { 4567 if (PLE && PLE->getNumExprs() == 0) { 4568 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 4569 return ExprError(); 4570 } 4571 if (PE || PLE->getNumExprs() == 1) { 4572 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 4573 if (!E->getType()->isVectorType()) 4574 isVectorLiteral = true; 4575 } 4576 else 4577 isVectorLiteral = true; 4578 } 4579 4580 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 4581 // then handle it as such. 4582 if (isVectorLiteral) 4583 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 4584 4585 // If the Expr being casted is a ParenListExpr, handle it specially. 4586 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 4587 // sequence of BinOp comma operators. 4588 if (isa<ParenListExpr>(CastExpr)) { 4589 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 4590 if (Result.isInvalid()) return ExprError(); 4591 CastExpr = Result.take(); 4592 } 4593 4594 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 4595} 4596 4597ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 4598 SourceLocation RParenLoc, Expr *E, 4599 TypeSourceInfo *TInfo) { 4600 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 4601 "Expected paren or paren list expression"); 4602 4603 Expr **exprs; 4604 unsigned numExprs; 4605 Expr *subExpr; 4606 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 4607 exprs = PE->getExprs(); 4608 numExprs = PE->getNumExprs(); 4609 } else { 4610 subExpr = cast<ParenExpr>(E)->getSubExpr(); 4611 exprs = &subExpr; 4612 numExprs = 1; 4613 } 4614 4615 QualType Ty = TInfo->getType(); 4616 assert(Ty->isVectorType() && "Expected vector type"); 4617 4618 SmallVector<Expr *, 8> initExprs; 4619 const VectorType *VTy = Ty->getAs<VectorType>(); 4620 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 4621 4622 // '(...)' form of vector initialization in AltiVec: the number of 4623 // initializers must be one or must match the size of the vector. 4624 // If a single value is specified in the initializer then it will be 4625 // replicated to all the components of the vector 4626 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 4627 // The number of initializers must be one or must match the size of the 4628 // vector. If a single value is specified in the initializer then it will 4629 // be replicated to all the components of the vector 4630 if (numExprs == 1) { 4631 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 4632 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 4633 if (Literal.isInvalid()) 4634 return ExprError(); 4635 Literal = ImpCastExprToType(Literal.take(), ElemTy, 4636 PrepareScalarCast(Literal, ElemTy)); 4637 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 4638 } 4639 else if (numExprs < numElems) { 4640 Diag(E->getExprLoc(), 4641 diag::err_incorrect_number_of_vector_initializers); 4642 return ExprError(); 4643 } 4644 else 4645 initExprs.append(exprs, exprs + numExprs); 4646 } 4647 else { 4648 // For OpenCL, when the number of initializers is a single value, 4649 // it will be replicated to all components of the vector. 4650 if (getLangOpts().OpenCL && 4651 VTy->getVectorKind() == VectorType::GenericVector && 4652 numExprs == 1) { 4653 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 4654 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 4655 if (Literal.isInvalid()) 4656 return ExprError(); 4657 Literal = ImpCastExprToType(Literal.take(), ElemTy, 4658 PrepareScalarCast(Literal, ElemTy)); 4659 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 4660 } 4661 4662 initExprs.append(exprs, exprs + numExprs); 4663 } 4664 // FIXME: This means that pretty-printing the final AST will produce curly 4665 // braces instead of the original commas. 4666 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc, 4667 initExprs, RParenLoc); 4668 initE->setType(Ty); 4669 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 4670} 4671 4672/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 4673/// the ParenListExpr into a sequence of comma binary operators. 4674ExprResult 4675Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 4676 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 4677 if (!E) 4678 return Owned(OrigExpr); 4679 4680 ExprResult Result(E->getExpr(0)); 4681 4682 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 4683 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 4684 E->getExpr(i)); 4685 4686 if (Result.isInvalid()) return ExprError(); 4687 4688 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 4689} 4690 4691ExprResult Sema::ActOnParenListExpr(SourceLocation L, 4692 SourceLocation R, 4693 MultiExprArg Val) { 4694 assert(Val.data() != 0 && "ActOnParenOrParenListExpr() missing expr list"); 4695 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 4696 return Owned(expr); 4697} 4698 4699/// \brief Emit a specialized diagnostic when one expression is a null pointer 4700/// constant and the other is not a pointer. Returns true if a diagnostic is 4701/// emitted. 4702bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 4703 SourceLocation QuestionLoc) { 4704 Expr *NullExpr = LHSExpr; 4705 Expr *NonPointerExpr = RHSExpr; 4706 Expr::NullPointerConstantKind NullKind = 4707 NullExpr->isNullPointerConstant(Context, 4708 Expr::NPC_ValueDependentIsNotNull); 4709 4710 if (NullKind == Expr::NPCK_NotNull) { 4711 NullExpr = RHSExpr; 4712 NonPointerExpr = LHSExpr; 4713 NullKind = 4714 NullExpr->isNullPointerConstant(Context, 4715 Expr::NPC_ValueDependentIsNotNull); 4716 } 4717 4718 if (NullKind == Expr::NPCK_NotNull) 4719 return false; 4720 4721 if (NullKind == Expr::NPCK_ZeroExpression) 4722 return false; 4723 4724 if (NullKind == Expr::NPCK_ZeroLiteral) { 4725 // In this case, check to make sure that we got here from a "NULL" 4726 // string in the source code. 4727 NullExpr = NullExpr->IgnoreParenImpCasts(); 4728 SourceLocation loc = NullExpr->getExprLoc(); 4729 if (!findMacroSpelling(loc, "NULL")) 4730 return false; 4731 } 4732 4733 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr); 4734 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 4735 << NonPointerExpr->getType() << DiagType 4736 << NonPointerExpr->getSourceRange(); 4737 return true; 4738} 4739 4740/// \brief Return false if the condition expression is valid, true otherwise. 4741static bool checkCondition(Sema &S, Expr *Cond) { 4742 QualType CondTy = Cond->getType(); 4743 4744 // C99 6.5.15p2 4745 if (CondTy->isScalarType()) return false; 4746 4747 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar. 4748 if (S.getLangOpts().OpenCL && CondTy->isVectorType()) 4749 return false; 4750 4751 // Emit the proper error message. 4752 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ? 4753 diag::err_typecheck_cond_expect_scalar : 4754 diag::err_typecheck_cond_expect_scalar_or_vector) 4755 << CondTy; 4756 return true; 4757} 4758 4759/// \brief Return false if the two expressions can be converted to a vector, 4760/// true otherwise 4761static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS, 4762 ExprResult &RHS, 4763 QualType CondTy) { 4764 // Both operands should be of scalar type. 4765 if (!LHS.get()->getType()->isScalarType()) { 4766 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 4767 << CondTy; 4768 return true; 4769 } 4770 if (!RHS.get()->getType()->isScalarType()) { 4771 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 4772 << CondTy; 4773 return true; 4774 } 4775 4776 // Implicity convert these scalars to the type of the condition. 4777 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast); 4778 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast); 4779 return false; 4780} 4781 4782/// \brief Handle when one or both operands are void type. 4783static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 4784 ExprResult &RHS) { 4785 Expr *LHSExpr = LHS.get(); 4786 Expr *RHSExpr = RHS.get(); 4787 4788 if (!LHSExpr->getType()->isVoidType()) 4789 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 4790 << RHSExpr->getSourceRange(); 4791 if (!RHSExpr->getType()->isVoidType()) 4792 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 4793 << LHSExpr->getSourceRange(); 4794 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid); 4795 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid); 4796 return S.Context.VoidTy; 4797} 4798 4799/// \brief Return false if the NullExpr can be promoted to PointerTy, 4800/// true otherwise. 4801static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 4802 QualType PointerTy) { 4803 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 4804 !NullExpr.get()->isNullPointerConstant(S.Context, 4805 Expr::NPC_ValueDependentIsNull)) 4806 return true; 4807 4808 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer); 4809 return false; 4810} 4811 4812/// \brief Checks compatibility between two pointers and return the resulting 4813/// type. 4814static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 4815 ExprResult &RHS, 4816 SourceLocation Loc) { 4817 QualType LHSTy = LHS.get()->getType(); 4818 QualType RHSTy = RHS.get()->getType(); 4819 4820 if (S.Context.hasSameType(LHSTy, RHSTy)) { 4821 // Two identical pointers types are always compatible. 4822 return LHSTy; 4823 } 4824 4825 QualType lhptee, rhptee; 4826 4827 // Get the pointee types. 4828 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 4829 lhptee = LHSBTy->getPointeeType(); 4830 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 4831 } else { 4832 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 4833 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 4834 } 4835 4836 // C99 6.5.15p6: If both operands are pointers to compatible types or to 4837 // differently qualified versions of compatible types, the result type is 4838 // a pointer to an appropriately qualified version of the composite 4839 // type. 4840 4841 // Only CVR-qualifiers exist in the standard, and the differently-qualified 4842 // clause doesn't make sense for our extensions. E.g. address space 2 should 4843 // be incompatible with address space 3: they may live on different devices or 4844 // anything. 4845 Qualifiers lhQual = lhptee.getQualifiers(); 4846 Qualifiers rhQual = rhptee.getQualifiers(); 4847 4848 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 4849 lhQual.removeCVRQualifiers(); 4850 rhQual.removeCVRQualifiers(); 4851 4852 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 4853 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 4854 4855 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 4856 4857 if (CompositeTy.isNull()) { 4858 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers) 4859 << LHSTy << RHSTy << LHS.get()->getSourceRange() 4860 << RHS.get()->getSourceRange(); 4861 // In this situation, we assume void* type. No especially good 4862 // reason, but this is what gcc does, and we do have to pick 4863 // to get a consistent AST. 4864 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 4865 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 4866 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 4867 return incompatTy; 4868 } 4869 4870 // The pointer types are compatible. 4871 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 4872 ResultTy = S.Context.getPointerType(ResultTy); 4873 4874 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast); 4875 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast); 4876 return ResultTy; 4877} 4878 4879/// \brief Return the resulting type when the operands are both block pointers. 4880static QualType checkConditionalBlockPointerCompatibility(Sema &S, 4881 ExprResult &LHS, 4882 ExprResult &RHS, 4883 SourceLocation Loc) { 4884 QualType LHSTy = LHS.get()->getType(); 4885 QualType RHSTy = RHS.get()->getType(); 4886 4887 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 4888 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 4889 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 4890 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 4891 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 4892 return destType; 4893 } 4894 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 4895 << LHSTy << RHSTy << LHS.get()->getSourceRange() 4896 << RHS.get()->getSourceRange(); 4897 return QualType(); 4898 } 4899 4900 // We have 2 block pointer types. 4901 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 4902} 4903 4904/// \brief Return the resulting type when the operands are both pointers. 4905static QualType 4906checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 4907 ExprResult &RHS, 4908 SourceLocation Loc) { 4909 // get the pointer types 4910 QualType LHSTy = LHS.get()->getType(); 4911 QualType RHSTy = RHS.get()->getType(); 4912 4913 // get the "pointed to" types 4914 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 4915 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 4916 4917 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 4918 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 4919 // Figure out necessary qualifiers (C99 6.5.15p6) 4920 QualType destPointee 4921 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 4922 QualType destType = S.Context.getPointerType(destPointee); 4923 // Add qualifiers if necessary. 4924 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp); 4925 // Promote to void*. 4926 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 4927 return destType; 4928 } 4929 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 4930 QualType destPointee 4931 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 4932 QualType destType = S.Context.getPointerType(destPointee); 4933 // Add qualifiers if necessary. 4934 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp); 4935 // Promote to void*. 4936 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 4937 return destType; 4938 } 4939 4940 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 4941} 4942 4943/// \brief Return false if the first expression is not an integer and the second 4944/// expression is not a pointer, true otherwise. 4945static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 4946 Expr* PointerExpr, SourceLocation Loc, 4947 bool IsIntFirstExpr) { 4948 if (!PointerExpr->getType()->isPointerType() || 4949 !Int.get()->getType()->isIntegerType()) 4950 return false; 4951 4952 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 4953 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 4954 4955 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch) 4956 << Expr1->getType() << Expr2->getType() 4957 << Expr1->getSourceRange() << Expr2->getSourceRange(); 4958 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(), 4959 CK_IntegralToPointer); 4960 return true; 4961} 4962 4963/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 4964/// In that case, LHS = cond. 4965/// C99 6.5.15 4966QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 4967 ExprResult &RHS, ExprValueKind &VK, 4968 ExprObjectKind &OK, 4969 SourceLocation QuestionLoc) { 4970 4971 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 4972 if (!LHSResult.isUsable()) return QualType(); 4973 LHS = LHSResult; 4974 4975 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 4976 if (!RHSResult.isUsable()) return QualType(); 4977 RHS = RHSResult; 4978 4979 // C++ is sufficiently different to merit its own checker. 4980 if (getLangOpts().CPlusPlus) 4981 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 4982 4983 VK = VK_RValue; 4984 OK = OK_Ordinary; 4985 4986 Cond = UsualUnaryConversions(Cond.take()); 4987 if (Cond.isInvalid()) 4988 return QualType(); 4989 LHS = UsualUnaryConversions(LHS.take()); 4990 if (LHS.isInvalid()) 4991 return QualType(); 4992 RHS = UsualUnaryConversions(RHS.take()); 4993 if (RHS.isInvalid()) 4994 return QualType(); 4995 4996 QualType CondTy = Cond.get()->getType(); 4997 QualType LHSTy = LHS.get()->getType(); 4998 QualType RHSTy = RHS.get()->getType(); 4999 5000 // first, check the condition. 5001 if (checkCondition(*this, Cond.get())) 5002 return QualType(); 5003 5004 // Now check the two expressions. 5005 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 5006 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false); 5007 5008 // OpenCL: If the condition is a vector, and both operands are scalar, 5009 // attempt to implicity convert them to the vector type to act like the 5010 // built in select. 5011 if (getLangOpts().OpenCL && CondTy->isVectorType()) 5012 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy)) 5013 return QualType(); 5014 5015 // If both operands have arithmetic type, do the usual arithmetic conversions 5016 // to find a common type: C99 6.5.15p3,5. 5017 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 5018 UsualArithmeticConversions(LHS, RHS); 5019 if (LHS.isInvalid() || RHS.isInvalid()) 5020 return QualType(); 5021 return LHS.get()->getType(); 5022 } 5023 5024 // If both operands are the same structure or union type, the result is that 5025 // type. 5026 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 5027 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 5028 if (LHSRT->getDecl() == RHSRT->getDecl()) 5029 // "If both the operands have structure or union type, the result has 5030 // that type." This implies that CV qualifiers are dropped. 5031 return LHSTy.getUnqualifiedType(); 5032 // FIXME: Type of conditional expression must be complete in C mode. 5033 } 5034 5035 // C99 6.5.15p5: "If both operands have void type, the result has void type." 5036 // The following || allows only one side to be void (a GCC-ism). 5037 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 5038 return checkConditionalVoidType(*this, LHS, RHS); 5039 } 5040 5041 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 5042 // the type of the other operand." 5043 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 5044 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 5045 5046 // All objective-c pointer type analysis is done here. 5047 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 5048 QuestionLoc); 5049 if (LHS.isInvalid() || RHS.isInvalid()) 5050 return QualType(); 5051 if (!compositeType.isNull()) 5052 return compositeType; 5053 5054 5055 // Handle block pointer types. 5056 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 5057 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 5058 QuestionLoc); 5059 5060 // Check constraints for C object pointers types (C99 6.5.15p3,6). 5061 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 5062 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 5063 QuestionLoc); 5064 5065 // GCC compatibility: soften pointer/integer mismatch. Note that 5066 // null pointers have been filtered out by this point. 5067 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 5068 /*isIntFirstExpr=*/true)) 5069 return RHSTy; 5070 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 5071 /*isIntFirstExpr=*/false)) 5072 return LHSTy; 5073 5074 // Emit a better diagnostic if one of the expressions is a null pointer 5075 // constant and the other is not a pointer type. In this case, the user most 5076 // likely forgot to take the address of the other expression. 5077 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 5078 return QualType(); 5079 5080 // Otherwise, the operands are not compatible. 5081 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 5082 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5083 << RHS.get()->getSourceRange(); 5084 return QualType(); 5085} 5086 5087/// FindCompositeObjCPointerType - Helper method to find composite type of 5088/// two objective-c pointer types of the two input expressions. 5089QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 5090 SourceLocation QuestionLoc) { 5091 QualType LHSTy = LHS.get()->getType(); 5092 QualType RHSTy = RHS.get()->getType(); 5093 5094 // Handle things like Class and struct objc_class*. Here we case the result 5095 // to the pseudo-builtin, because that will be implicitly cast back to the 5096 // redefinition type if an attempt is made to access its fields. 5097 if (LHSTy->isObjCClassType() && 5098 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 5099 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5100 return LHSTy; 5101 } 5102 if (RHSTy->isObjCClassType() && 5103 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 5104 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5105 return RHSTy; 5106 } 5107 // And the same for struct objc_object* / id 5108 if (LHSTy->isObjCIdType() && 5109 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 5110 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5111 return LHSTy; 5112 } 5113 if (RHSTy->isObjCIdType() && 5114 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 5115 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5116 return RHSTy; 5117 } 5118 // And the same for struct objc_selector* / SEL 5119 if (Context.isObjCSelType(LHSTy) && 5120 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 5121 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast); 5122 return LHSTy; 5123 } 5124 if (Context.isObjCSelType(RHSTy) && 5125 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 5126 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast); 5127 return RHSTy; 5128 } 5129 // Check constraints for Objective-C object pointers types. 5130 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 5131 5132 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 5133 // Two identical object pointer types are always compatible. 5134 return LHSTy; 5135 } 5136 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 5137 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 5138 QualType compositeType = LHSTy; 5139 5140 // If both operands are interfaces and either operand can be 5141 // assigned to the other, use that type as the composite 5142 // type. This allows 5143 // xxx ? (A*) a : (B*) b 5144 // where B is a subclass of A. 5145 // 5146 // Additionally, as for assignment, if either type is 'id' 5147 // allow silent coercion. Finally, if the types are 5148 // incompatible then make sure to use 'id' as the composite 5149 // type so the result is acceptable for sending messages to. 5150 5151 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 5152 // It could return the composite type. 5153 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 5154 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 5155 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 5156 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 5157 } else if ((LHSTy->isObjCQualifiedIdType() || 5158 RHSTy->isObjCQualifiedIdType()) && 5159 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 5160 // Need to handle "id<xx>" explicitly. 5161 // GCC allows qualified id and any Objective-C type to devolve to 5162 // id. Currently localizing to here until clear this should be 5163 // part of ObjCQualifiedIdTypesAreCompatible. 5164 compositeType = Context.getObjCIdType(); 5165 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 5166 compositeType = Context.getObjCIdType(); 5167 } else if (!(compositeType = 5168 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 5169 ; 5170 else { 5171 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 5172 << LHSTy << RHSTy 5173 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5174 QualType incompatTy = Context.getObjCIdType(); 5175 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5176 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5177 return incompatTy; 5178 } 5179 // The object pointer types are compatible. 5180 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast); 5181 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast); 5182 return compositeType; 5183 } 5184 // Check Objective-C object pointer types and 'void *' 5185 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 5186 if (getLangOpts().ObjCAutoRefCount) { 5187 // ARC forbids the implicit conversion of object pointers to 'void *', 5188 // so these types are not compatible. 5189 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5190 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5191 LHS = RHS = true; 5192 return QualType(); 5193 } 5194 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5195 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5196 QualType destPointee 5197 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5198 QualType destType = Context.getPointerType(destPointee); 5199 // Add qualifiers if necessary. 5200 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5201 // Promote to void*. 5202 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5203 return destType; 5204 } 5205 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 5206 if (getLangOpts().ObjCAutoRefCount) { 5207 // ARC forbids the implicit conversion of object pointers to 'void *', 5208 // so these types are not compatible. 5209 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5210 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5211 LHS = RHS = true; 5212 return QualType(); 5213 } 5214 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5215 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5216 QualType destPointee 5217 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5218 QualType destType = Context.getPointerType(destPointee); 5219 // Add qualifiers if necessary. 5220 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5221 // Promote to void*. 5222 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5223 return destType; 5224 } 5225 return QualType(); 5226} 5227 5228/// SuggestParentheses - Emit a note with a fixit hint that wraps 5229/// ParenRange in parentheses. 5230static void SuggestParentheses(Sema &Self, SourceLocation Loc, 5231 const PartialDiagnostic &Note, 5232 SourceRange ParenRange) { 5233 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 5234 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 5235 EndLoc.isValid()) { 5236 Self.Diag(Loc, Note) 5237 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 5238 << FixItHint::CreateInsertion(EndLoc, ")"); 5239 } else { 5240 // We can't display the parentheses, so just show the bare note. 5241 Self.Diag(Loc, Note) << ParenRange; 5242 } 5243} 5244 5245static bool IsArithmeticOp(BinaryOperatorKind Opc) { 5246 return Opc >= BO_Mul && Opc <= BO_Shr; 5247} 5248 5249/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 5250/// expression, either using a built-in or overloaded operator, 5251/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 5252/// expression. 5253static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 5254 Expr **RHSExprs) { 5255 // Don't strip parenthesis: we should not warn if E is in parenthesis. 5256 E = E->IgnoreImpCasts(); 5257 E = E->IgnoreConversionOperator(); 5258 E = E->IgnoreImpCasts(); 5259 5260 // Built-in binary operator. 5261 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 5262 if (IsArithmeticOp(OP->getOpcode())) { 5263 *Opcode = OP->getOpcode(); 5264 *RHSExprs = OP->getRHS(); 5265 return true; 5266 } 5267 } 5268 5269 // Overloaded operator. 5270 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 5271 if (Call->getNumArgs() != 2) 5272 return false; 5273 5274 // Make sure this is really a binary operator that is safe to pass into 5275 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 5276 OverloadedOperatorKind OO = Call->getOperator(); 5277 if (OO < OO_Plus || OO > OO_Arrow) 5278 return false; 5279 5280 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 5281 if (IsArithmeticOp(OpKind)) { 5282 *Opcode = OpKind; 5283 *RHSExprs = Call->getArg(1); 5284 return true; 5285 } 5286 } 5287 5288 return false; 5289} 5290 5291static bool IsLogicOp(BinaryOperatorKind Opc) { 5292 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 5293} 5294 5295/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 5296/// or is a logical expression such as (x==y) which has int type, but is 5297/// commonly interpreted as boolean. 5298static bool ExprLooksBoolean(Expr *E) { 5299 E = E->IgnoreParenImpCasts(); 5300 5301 if (E->getType()->isBooleanType()) 5302 return true; 5303 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 5304 return IsLogicOp(OP->getOpcode()); 5305 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 5306 return OP->getOpcode() == UO_LNot; 5307 5308 return false; 5309} 5310 5311/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 5312/// and binary operator are mixed in a way that suggests the programmer assumed 5313/// the conditional operator has higher precedence, for example: 5314/// "int x = a + someBinaryCondition ? 1 : 2". 5315static void DiagnoseConditionalPrecedence(Sema &Self, 5316 SourceLocation OpLoc, 5317 Expr *Condition, 5318 Expr *LHSExpr, 5319 Expr *RHSExpr) { 5320 BinaryOperatorKind CondOpcode; 5321 Expr *CondRHS; 5322 5323 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 5324 return; 5325 if (!ExprLooksBoolean(CondRHS)) 5326 return; 5327 5328 // The condition is an arithmetic binary expression, with a right- 5329 // hand side that looks boolean, so warn. 5330 5331 Self.Diag(OpLoc, diag::warn_precedence_conditional) 5332 << Condition->getSourceRange() 5333 << BinaryOperator::getOpcodeStr(CondOpcode); 5334 5335 SuggestParentheses(Self, OpLoc, 5336 Self.PDiag(diag::note_precedence_silence) 5337 << BinaryOperator::getOpcodeStr(CondOpcode), 5338 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 5339 5340 SuggestParentheses(Self, OpLoc, 5341 Self.PDiag(diag::note_precedence_conditional_first), 5342 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 5343} 5344 5345/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 5346/// in the case of a the GNU conditional expr extension. 5347ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 5348 SourceLocation ColonLoc, 5349 Expr *CondExpr, Expr *LHSExpr, 5350 Expr *RHSExpr) { 5351 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 5352 // was the condition. 5353 OpaqueValueExpr *opaqueValue = 0; 5354 Expr *commonExpr = 0; 5355 if (LHSExpr == 0) { 5356 commonExpr = CondExpr; 5357 5358 // We usually want to apply unary conversions *before* saving, except 5359 // in the special case of a C++ l-value conditional. 5360 if (!(getLangOpts().CPlusPlus 5361 && !commonExpr->isTypeDependent() 5362 && commonExpr->getValueKind() == RHSExpr->getValueKind() 5363 && commonExpr->isGLValue() 5364 && commonExpr->isOrdinaryOrBitFieldObject() 5365 && RHSExpr->isOrdinaryOrBitFieldObject() 5366 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 5367 ExprResult commonRes = UsualUnaryConversions(commonExpr); 5368 if (commonRes.isInvalid()) 5369 return ExprError(); 5370 commonExpr = commonRes.take(); 5371 } 5372 5373 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 5374 commonExpr->getType(), 5375 commonExpr->getValueKind(), 5376 commonExpr->getObjectKind(), 5377 commonExpr); 5378 LHSExpr = CondExpr = opaqueValue; 5379 } 5380 5381 ExprValueKind VK = VK_RValue; 5382 ExprObjectKind OK = OK_Ordinary; 5383 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 5384 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 5385 VK, OK, QuestionLoc); 5386 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 5387 RHS.isInvalid()) 5388 return ExprError(); 5389 5390 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 5391 RHS.get()); 5392 5393 if (!commonExpr) 5394 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc, 5395 LHS.take(), ColonLoc, 5396 RHS.take(), result, VK, OK)); 5397 5398 return Owned(new (Context) 5399 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(), 5400 RHS.take(), QuestionLoc, ColonLoc, result, VK, 5401 OK)); 5402} 5403 5404// checkPointerTypesForAssignment - This is a very tricky routine (despite 5405// being closely modeled after the C99 spec:-). The odd characteristic of this 5406// routine is it effectively iqnores the qualifiers on the top level pointee. 5407// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 5408// FIXME: add a couple examples in this comment. 5409static Sema::AssignConvertType 5410checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 5411 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 5412 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 5413 5414 // get the "pointed to" type (ignoring qualifiers at the top level) 5415 const Type *lhptee, *rhptee; 5416 Qualifiers lhq, rhq; 5417 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split(); 5418 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split(); 5419 5420 Sema::AssignConvertType ConvTy = Sema::Compatible; 5421 5422 // C99 6.5.16.1p1: This following citation is common to constraints 5423 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 5424 // qualifiers of the type *pointed to* by the right; 5425 Qualifiers lq; 5426 5427 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 5428 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 5429 lhq.compatiblyIncludesObjCLifetime(rhq)) { 5430 // Ignore lifetime for further calculation. 5431 lhq.removeObjCLifetime(); 5432 rhq.removeObjCLifetime(); 5433 } 5434 5435 if (!lhq.compatiblyIncludes(rhq)) { 5436 // Treat address-space mismatches as fatal. TODO: address subspaces 5437 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 5438 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5439 5440 // It's okay to add or remove GC or lifetime qualifiers when converting to 5441 // and from void*. 5442 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 5443 .compatiblyIncludes( 5444 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 5445 && (lhptee->isVoidType() || rhptee->isVoidType())) 5446 ; // keep old 5447 5448 // Treat lifetime mismatches as fatal. 5449 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 5450 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5451 5452 // For GCC compatibility, other qualifier mismatches are treated 5453 // as still compatible in C. 5454 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 5455 } 5456 5457 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 5458 // incomplete type and the other is a pointer to a qualified or unqualified 5459 // version of void... 5460 if (lhptee->isVoidType()) { 5461 if (rhptee->isIncompleteOrObjectType()) 5462 return ConvTy; 5463 5464 // As an extension, we allow cast to/from void* to function pointer. 5465 assert(rhptee->isFunctionType()); 5466 return Sema::FunctionVoidPointer; 5467 } 5468 5469 if (rhptee->isVoidType()) { 5470 if (lhptee->isIncompleteOrObjectType()) 5471 return ConvTy; 5472 5473 // As an extension, we allow cast to/from void* to function pointer. 5474 assert(lhptee->isFunctionType()); 5475 return Sema::FunctionVoidPointer; 5476 } 5477 5478 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 5479 // unqualified versions of compatible types, ... 5480 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 5481 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 5482 // Check if the pointee types are compatible ignoring the sign. 5483 // We explicitly check for char so that we catch "char" vs 5484 // "unsigned char" on systems where "char" is unsigned. 5485 if (lhptee->isCharType()) 5486 ltrans = S.Context.UnsignedCharTy; 5487 else if (lhptee->hasSignedIntegerRepresentation()) 5488 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 5489 5490 if (rhptee->isCharType()) 5491 rtrans = S.Context.UnsignedCharTy; 5492 else if (rhptee->hasSignedIntegerRepresentation()) 5493 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 5494 5495 if (ltrans == rtrans) { 5496 // Types are compatible ignoring the sign. Qualifier incompatibility 5497 // takes priority over sign incompatibility because the sign 5498 // warning can be disabled. 5499 if (ConvTy != Sema::Compatible) 5500 return ConvTy; 5501 5502 return Sema::IncompatiblePointerSign; 5503 } 5504 5505 // If we are a multi-level pointer, it's possible that our issue is simply 5506 // one of qualification - e.g. char ** -> const char ** is not allowed. If 5507 // the eventual target type is the same and the pointers have the same 5508 // level of indirection, this must be the issue. 5509 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 5510 do { 5511 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 5512 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 5513 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 5514 5515 if (lhptee == rhptee) 5516 return Sema::IncompatibleNestedPointerQualifiers; 5517 } 5518 5519 // General pointer incompatibility takes priority over qualifiers. 5520 return Sema::IncompatiblePointer; 5521 } 5522 if (!S.getLangOpts().CPlusPlus && 5523 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 5524 return Sema::IncompatiblePointer; 5525 return ConvTy; 5526} 5527 5528/// checkBlockPointerTypesForAssignment - This routine determines whether two 5529/// block pointer types are compatible or whether a block and normal pointer 5530/// are compatible. It is more restrict than comparing two function pointer 5531// types. 5532static Sema::AssignConvertType 5533checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 5534 QualType RHSType) { 5535 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 5536 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 5537 5538 QualType lhptee, rhptee; 5539 5540 // get the "pointed to" type (ignoring qualifiers at the top level) 5541 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 5542 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 5543 5544 // In C++, the types have to match exactly. 5545 if (S.getLangOpts().CPlusPlus) 5546 return Sema::IncompatibleBlockPointer; 5547 5548 Sema::AssignConvertType ConvTy = Sema::Compatible; 5549 5550 // For blocks we enforce that qualifiers are identical. 5551 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 5552 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 5553 5554 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 5555 return Sema::IncompatibleBlockPointer; 5556 5557 return ConvTy; 5558} 5559 5560/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 5561/// for assignment compatibility. 5562static Sema::AssignConvertType 5563checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 5564 QualType RHSType) { 5565 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 5566 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 5567 5568 if (LHSType->isObjCBuiltinType()) { 5569 // Class is not compatible with ObjC object pointers. 5570 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 5571 !RHSType->isObjCQualifiedClassType()) 5572 return Sema::IncompatiblePointer; 5573 return Sema::Compatible; 5574 } 5575 if (RHSType->isObjCBuiltinType()) { 5576 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 5577 !LHSType->isObjCQualifiedClassType()) 5578 return Sema::IncompatiblePointer; 5579 return Sema::Compatible; 5580 } 5581 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 5582 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 5583 5584 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 5585 // make an exception for id<P> 5586 !LHSType->isObjCQualifiedIdType()) 5587 return Sema::CompatiblePointerDiscardsQualifiers; 5588 5589 if (S.Context.typesAreCompatible(LHSType, RHSType)) 5590 return Sema::Compatible; 5591 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 5592 return Sema::IncompatibleObjCQualifiedId; 5593 return Sema::IncompatiblePointer; 5594} 5595 5596Sema::AssignConvertType 5597Sema::CheckAssignmentConstraints(SourceLocation Loc, 5598 QualType LHSType, QualType RHSType) { 5599 // Fake up an opaque expression. We don't actually care about what 5600 // cast operations are required, so if CheckAssignmentConstraints 5601 // adds casts to this they'll be wasted, but fortunately that doesn't 5602 // usually happen on valid code. 5603 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 5604 ExprResult RHSPtr = &RHSExpr; 5605 CastKind K = CK_Invalid; 5606 5607 return CheckAssignmentConstraints(LHSType, RHSPtr, K); 5608} 5609 5610/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 5611/// has code to accommodate several GCC extensions when type checking 5612/// pointers. Here are some objectionable examples that GCC considers warnings: 5613/// 5614/// int a, *pint; 5615/// short *pshort; 5616/// struct foo *pfoo; 5617/// 5618/// pint = pshort; // warning: assignment from incompatible pointer type 5619/// a = pint; // warning: assignment makes integer from pointer without a cast 5620/// pint = a; // warning: assignment makes pointer from integer without a cast 5621/// pint = pfoo; // warning: assignment from incompatible pointer type 5622/// 5623/// As a result, the code for dealing with pointers is more complex than the 5624/// C99 spec dictates. 5625/// 5626/// Sets 'Kind' for any result kind except Incompatible. 5627Sema::AssignConvertType 5628Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 5629 CastKind &Kind) { 5630 QualType RHSType = RHS.get()->getType(); 5631 QualType OrigLHSType = LHSType; 5632 5633 // Get canonical types. We're not formatting these types, just comparing 5634 // them. 5635 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 5636 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 5637 5638 5639 // Common case: no conversion required. 5640 if (LHSType == RHSType) { 5641 Kind = CK_NoOp; 5642 return Compatible; 5643 } 5644 5645 // If we have an atomic type, try a non-atomic assignment, then just add an 5646 // atomic qualification step. 5647 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 5648 Sema::AssignConvertType result = 5649 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 5650 if (result != Compatible) 5651 return result; 5652 if (Kind != CK_NoOp) 5653 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind); 5654 Kind = CK_NonAtomicToAtomic; 5655 return Compatible; 5656 } 5657 5658 // If the left-hand side is a reference type, then we are in a 5659 // (rare!) case where we've allowed the use of references in C, 5660 // e.g., as a parameter type in a built-in function. In this case, 5661 // just make sure that the type referenced is compatible with the 5662 // right-hand side type. The caller is responsible for adjusting 5663 // LHSType so that the resulting expression does not have reference 5664 // type. 5665 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 5666 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 5667 Kind = CK_LValueBitCast; 5668 return Compatible; 5669 } 5670 return Incompatible; 5671 } 5672 5673 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 5674 // to the same ExtVector type. 5675 if (LHSType->isExtVectorType()) { 5676 if (RHSType->isExtVectorType()) 5677 return Incompatible; 5678 if (RHSType->isArithmeticType()) { 5679 // CK_VectorSplat does T -> vector T, so first cast to the 5680 // element type. 5681 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 5682 if (elType != RHSType) { 5683 Kind = PrepareScalarCast(RHS, elType); 5684 RHS = ImpCastExprToType(RHS.take(), elType, Kind); 5685 } 5686 Kind = CK_VectorSplat; 5687 return Compatible; 5688 } 5689 } 5690 5691 // Conversions to or from vector type. 5692 if (LHSType->isVectorType() || RHSType->isVectorType()) { 5693 if (LHSType->isVectorType() && RHSType->isVectorType()) { 5694 // Allow assignments of an AltiVec vector type to an equivalent GCC 5695 // vector type and vice versa 5696 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 5697 Kind = CK_BitCast; 5698 return Compatible; 5699 } 5700 5701 // If we are allowing lax vector conversions, and LHS and RHS are both 5702 // vectors, the total size only needs to be the same. This is a bitcast; 5703 // no bits are changed but the result type is different. 5704 if (getLangOpts().LaxVectorConversions && 5705 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) { 5706 Kind = CK_BitCast; 5707 return IncompatibleVectors; 5708 } 5709 } 5710 return Incompatible; 5711 } 5712 5713 // Arithmetic conversions. 5714 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 5715 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 5716 Kind = PrepareScalarCast(RHS, LHSType); 5717 return Compatible; 5718 } 5719 5720 // Conversions to normal pointers. 5721 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 5722 // U* -> T* 5723 if (isa<PointerType>(RHSType)) { 5724 Kind = CK_BitCast; 5725 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 5726 } 5727 5728 // int -> T* 5729 if (RHSType->isIntegerType()) { 5730 Kind = CK_IntegralToPointer; // FIXME: null? 5731 return IntToPointer; 5732 } 5733 5734 // C pointers are not compatible with ObjC object pointers, 5735 // with two exceptions: 5736 if (isa<ObjCObjectPointerType>(RHSType)) { 5737 // - conversions to void* 5738 if (LHSPointer->getPointeeType()->isVoidType()) { 5739 Kind = CK_BitCast; 5740 return Compatible; 5741 } 5742 5743 // - conversions from 'Class' to the redefinition type 5744 if (RHSType->isObjCClassType() && 5745 Context.hasSameType(LHSType, 5746 Context.getObjCClassRedefinitionType())) { 5747 Kind = CK_BitCast; 5748 return Compatible; 5749 } 5750 5751 Kind = CK_BitCast; 5752 return IncompatiblePointer; 5753 } 5754 5755 // U^ -> void* 5756 if (RHSType->getAs<BlockPointerType>()) { 5757 if (LHSPointer->getPointeeType()->isVoidType()) { 5758 Kind = CK_BitCast; 5759 return Compatible; 5760 } 5761 } 5762 5763 return Incompatible; 5764 } 5765 5766 // Conversions to block pointers. 5767 if (isa<BlockPointerType>(LHSType)) { 5768 // U^ -> T^ 5769 if (RHSType->isBlockPointerType()) { 5770 Kind = CK_BitCast; 5771 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 5772 } 5773 5774 // int or null -> T^ 5775 if (RHSType->isIntegerType()) { 5776 Kind = CK_IntegralToPointer; // FIXME: null 5777 return IntToBlockPointer; 5778 } 5779 5780 // id -> T^ 5781 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 5782 Kind = CK_AnyPointerToBlockPointerCast; 5783 return Compatible; 5784 } 5785 5786 // void* -> T^ 5787 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 5788 if (RHSPT->getPointeeType()->isVoidType()) { 5789 Kind = CK_AnyPointerToBlockPointerCast; 5790 return Compatible; 5791 } 5792 5793 return Incompatible; 5794 } 5795 5796 // Conversions to Objective-C pointers. 5797 if (isa<ObjCObjectPointerType>(LHSType)) { 5798 // A* -> B* 5799 if (RHSType->isObjCObjectPointerType()) { 5800 Kind = CK_BitCast; 5801 Sema::AssignConvertType result = 5802 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 5803 if (getLangOpts().ObjCAutoRefCount && 5804 result == Compatible && 5805 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 5806 result = IncompatibleObjCWeakRef; 5807 return result; 5808 } 5809 5810 // int or null -> A* 5811 if (RHSType->isIntegerType()) { 5812 Kind = CK_IntegralToPointer; // FIXME: null 5813 return IntToPointer; 5814 } 5815 5816 // In general, C pointers are not compatible with ObjC object pointers, 5817 // with two exceptions: 5818 if (isa<PointerType>(RHSType)) { 5819 Kind = CK_CPointerToObjCPointerCast; 5820 5821 // - conversions from 'void*' 5822 if (RHSType->isVoidPointerType()) { 5823 return Compatible; 5824 } 5825 5826 // - conversions to 'Class' from its redefinition type 5827 if (LHSType->isObjCClassType() && 5828 Context.hasSameType(RHSType, 5829 Context.getObjCClassRedefinitionType())) { 5830 return Compatible; 5831 } 5832 5833 return IncompatiblePointer; 5834 } 5835 5836 // T^ -> A* 5837 if (RHSType->isBlockPointerType()) { 5838 maybeExtendBlockObject(*this, RHS); 5839 Kind = CK_BlockPointerToObjCPointerCast; 5840 return Compatible; 5841 } 5842 5843 return Incompatible; 5844 } 5845 5846 // Conversions from pointers that are not covered by the above. 5847 if (isa<PointerType>(RHSType)) { 5848 // T* -> _Bool 5849 if (LHSType == Context.BoolTy) { 5850 Kind = CK_PointerToBoolean; 5851 return Compatible; 5852 } 5853 5854 // T* -> int 5855 if (LHSType->isIntegerType()) { 5856 Kind = CK_PointerToIntegral; 5857 return PointerToInt; 5858 } 5859 5860 return Incompatible; 5861 } 5862 5863 // Conversions from Objective-C pointers that are not covered by the above. 5864 if (isa<ObjCObjectPointerType>(RHSType)) { 5865 // T* -> _Bool 5866 if (LHSType == Context.BoolTy) { 5867 Kind = CK_PointerToBoolean; 5868 return Compatible; 5869 } 5870 5871 // T* -> int 5872 if (LHSType->isIntegerType()) { 5873 Kind = CK_PointerToIntegral; 5874 return PointerToInt; 5875 } 5876 5877 return Incompatible; 5878 } 5879 5880 // struct A -> struct B 5881 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 5882 if (Context.typesAreCompatible(LHSType, RHSType)) { 5883 Kind = CK_NoOp; 5884 return Compatible; 5885 } 5886 } 5887 5888 return Incompatible; 5889} 5890 5891/// \brief Constructs a transparent union from an expression that is 5892/// used to initialize the transparent union. 5893static void ConstructTransparentUnion(Sema &S, ASTContext &C, 5894 ExprResult &EResult, QualType UnionType, 5895 FieldDecl *Field) { 5896 // Build an initializer list that designates the appropriate member 5897 // of the transparent union. 5898 Expr *E = EResult.take(); 5899 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 5900 E, SourceLocation()); 5901 Initializer->setType(UnionType); 5902 Initializer->setInitializedFieldInUnion(Field); 5903 5904 // Build a compound literal constructing a value of the transparent 5905 // union type from this initializer list. 5906 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 5907 EResult = S.Owned( 5908 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 5909 VK_RValue, Initializer, false)); 5910} 5911 5912Sema::AssignConvertType 5913Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 5914 ExprResult &RHS) { 5915 QualType RHSType = RHS.get()->getType(); 5916 5917 // If the ArgType is a Union type, we want to handle a potential 5918 // transparent_union GCC extension. 5919 const RecordType *UT = ArgType->getAsUnionType(); 5920 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 5921 return Incompatible; 5922 5923 // The field to initialize within the transparent union. 5924 RecordDecl *UD = UT->getDecl(); 5925 FieldDecl *InitField = 0; 5926 // It's compatible if the expression matches any of the fields. 5927 for (RecordDecl::field_iterator it = UD->field_begin(), 5928 itend = UD->field_end(); 5929 it != itend; ++it) { 5930 if (it->getType()->isPointerType()) { 5931 // If the transparent union contains a pointer type, we allow: 5932 // 1) void pointer 5933 // 2) null pointer constant 5934 if (RHSType->isPointerType()) 5935 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 5936 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast); 5937 InitField = *it; 5938 break; 5939 } 5940 5941 if (RHS.get()->isNullPointerConstant(Context, 5942 Expr::NPC_ValueDependentIsNull)) { 5943 RHS = ImpCastExprToType(RHS.take(), it->getType(), 5944 CK_NullToPointer); 5945 InitField = *it; 5946 break; 5947 } 5948 } 5949 5950 CastKind Kind = CK_Invalid; 5951 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 5952 == Compatible) { 5953 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind); 5954 InitField = *it; 5955 break; 5956 } 5957 } 5958 5959 if (!InitField) 5960 return Incompatible; 5961 5962 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 5963 return Compatible; 5964} 5965 5966Sema::AssignConvertType 5967Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, 5968 bool Diagnose) { 5969 if (getLangOpts().CPlusPlus) { 5970 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 5971 // C++ 5.17p3: If the left operand is not of class type, the 5972 // expression is implicitly converted (C++ 4) to the 5973 // cv-unqualified type of the left operand. 5974 ExprResult Res; 5975 if (Diagnose) { 5976 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 5977 AA_Assigning); 5978 } else { 5979 ImplicitConversionSequence ICS = 5980 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 5981 /*SuppressUserConversions=*/false, 5982 /*AllowExplicit=*/false, 5983 /*InOverloadResolution=*/false, 5984 /*CStyle=*/false, 5985 /*AllowObjCWritebackConversion=*/false); 5986 if (ICS.isFailure()) 5987 return Incompatible; 5988 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 5989 ICS, AA_Assigning); 5990 } 5991 if (Res.isInvalid()) 5992 return Incompatible; 5993 Sema::AssignConvertType result = Compatible; 5994 if (getLangOpts().ObjCAutoRefCount && 5995 !CheckObjCARCUnavailableWeakConversion(LHSType, 5996 RHS.get()->getType())) 5997 result = IncompatibleObjCWeakRef; 5998 RHS = Res; 5999 return result; 6000 } 6001 6002 // FIXME: Currently, we fall through and treat C++ classes like C 6003 // structures. 6004 // FIXME: We also fall through for atomics; not sure what should 6005 // happen there, though. 6006 } 6007 6008 // C99 6.5.16.1p1: the left operand is a pointer and the right is 6009 // a null pointer constant. 6010 if ((LHSType->isPointerType() || 6011 LHSType->isObjCObjectPointerType() || 6012 LHSType->isBlockPointerType()) 6013 && RHS.get()->isNullPointerConstant(Context, 6014 Expr::NPC_ValueDependentIsNull)) { 6015 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 6016 return Compatible; 6017 } 6018 6019 // This check seems unnatural, however it is necessary to ensure the proper 6020 // conversion of functions/arrays. If the conversion were done for all 6021 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 6022 // expressions that suppress this implicit conversion (&, sizeof). 6023 // 6024 // Suppress this for references: C++ 8.5.3p5. 6025 if (!LHSType->isReferenceType()) { 6026 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6027 if (RHS.isInvalid()) 6028 return Incompatible; 6029 } 6030 6031 CastKind Kind = CK_Invalid; 6032 Sema::AssignConvertType result = 6033 CheckAssignmentConstraints(LHSType, RHS, Kind); 6034 6035 // C99 6.5.16.1p2: The value of the right operand is converted to the 6036 // type of the assignment expression. 6037 // CheckAssignmentConstraints allows the left-hand side to be a reference, 6038 // so that we can use references in built-in functions even in C. 6039 // The getNonReferenceType() call makes sure that the resulting expression 6040 // does not have reference type. 6041 if (result != Incompatible && RHS.get()->getType() != LHSType) 6042 RHS = ImpCastExprToType(RHS.take(), 6043 LHSType.getNonLValueExprType(Context), Kind); 6044 return result; 6045} 6046 6047QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 6048 ExprResult &RHS) { 6049 Diag(Loc, diag::err_typecheck_invalid_operands) 6050 << LHS.get()->getType() << RHS.get()->getType() 6051 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6052 return QualType(); 6053} 6054 6055QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 6056 SourceLocation Loc, bool IsCompAssign) { 6057 if (!IsCompAssign) { 6058 LHS = DefaultFunctionArrayLvalueConversion(LHS.take()); 6059 if (LHS.isInvalid()) 6060 return QualType(); 6061 } 6062 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6063 if (RHS.isInvalid()) 6064 return QualType(); 6065 6066 // For conversion purposes, we ignore any qualifiers. 6067 // For example, "const float" and "float" are equivalent. 6068 QualType LHSType = 6069 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6070 QualType RHSType = 6071 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6072 6073 // If the vector types are identical, return. 6074 if (LHSType == RHSType) 6075 return LHSType; 6076 6077 // Handle the case of equivalent AltiVec and GCC vector types 6078 if (LHSType->isVectorType() && RHSType->isVectorType() && 6079 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6080 if (LHSType->isExtVectorType()) { 6081 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6082 return LHSType; 6083 } 6084 6085 if (!IsCompAssign) 6086 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 6087 return RHSType; 6088 } 6089 6090 if (getLangOpts().LaxVectorConversions && 6091 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) { 6092 // If we are allowing lax vector conversions, and LHS and RHS are both 6093 // vectors, the total size only needs to be the same. This is a 6094 // bitcast; no bits are changed but the result type is different. 6095 // FIXME: Should we really be allowing this? 6096 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6097 return LHSType; 6098 } 6099 6100 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can 6101 // swap back (so that we don't reverse the inputs to a subtract, for instance. 6102 bool swapped = false; 6103 if (RHSType->isExtVectorType() && !IsCompAssign) { 6104 swapped = true; 6105 std::swap(RHS, LHS); 6106 std::swap(RHSType, LHSType); 6107 } 6108 6109 // Handle the case of an ext vector and scalar. 6110 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) { 6111 QualType EltTy = LV->getElementType(); 6112 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) { 6113 int order = Context.getIntegerTypeOrder(EltTy, RHSType); 6114 if (order > 0) 6115 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast); 6116 if (order >= 0) { 6117 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 6118 if (swapped) std::swap(RHS, LHS); 6119 return LHSType; 6120 } 6121 } 6122 if (EltTy->isRealFloatingType() && RHSType->isScalarType() && 6123 RHSType->isRealFloatingType()) { 6124 int order = Context.getFloatingTypeOrder(EltTy, RHSType); 6125 if (order > 0) 6126 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast); 6127 if (order >= 0) { 6128 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 6129 if (swapped) std::swap(RHS, LHS); 6130 return LHSType; 6131 } 6132 } 6133 } 6134 6135 // Vectors of different size or scalar and non-ext-vector are errors. 6136 if (swapped) std::swap(RHS, LHS); 6137 Diag(Loc, diag::err_typecheck_vector_not_convertable) 6138 << LHS.get()->getType() << RHS.get()->getType() 6139 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6140 return QualType(); 6141} 6142 6143// checkArithmeticNull - Detect when a NULL constant is used improperly in an 6144// expression. These are mainly cases where the null pointer is used as an 6145// integer instead of a pointer. 6146static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 6147 SourceLocation Loc, bool IsCompare) { 6148 // The canonical way to check for a GNU null is with isNullPointerConstant, 6149 // but we use a bit of a hack here for speed; this is a relatively 6150 // hot path, and isNullPointerConstant is slow. 6151 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 6152 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 6153 6154 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 6155 6156 // Avoid analyzing cases where the result will either be invalid (and 6157 // diagnosed as such) or entirely valid and not something to warn about. 6158 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 6159 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 6160 return; 6161 6162 // Comparison operations would not make sense with a null pointer no matter 6163 // what the other expression is. 6164 if (!IsCompare) { 6165 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 6166 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 6167 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 6168 return; 6169 } 6170 6171 // The rest of the operations only make sense with a null pointer 6172 // if the other expression is a pointer. 6173 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 6174 NonNullType->canDecayToPointerType()) 6175 return; 6176 6177 S.Diag(Loc, diag::warn_null_in_comparison_operation) 6178 << LHSNull /* LHS is NULL */ << NonNullType 6179 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6180} 6181 6182QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 6183 SourceLocation Loc, 6184 bool IsCompAssign, bool IsDiv) { 6185 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6186 6187 if (LHS.get()->getType()->isVectorType() || 6188 RHS.get()->getType()->isVectorType()) 6189 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6190 6191 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6192 if (LHS.isInvalid() || RHS.isInvalid()) 6193 return QualType(); 6194 6195 6196 if (compType.isNull() || !compType->isArithmeticType()) 6197 return InvalidOperands(Loc, LHS, RHS); 6198 6199 // Check for division by zero. 6200 if (IsDiv && 6201 RHS.get()->isNullPointerConstant(Context, 6202 Expr::NPC_ValueDependentIsNotNull)) 6203 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero) 6204 << RHS.get()->getSourceRange()); 6205 6206 return compType; 6207} 6208 6209QualType Sema::CheckRemainderOperands( 6210 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 6211 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6212 6213 if (LHS.get()->getType()->isVectorType() || 6214 RHS.get()->getType()->isVectorType()) { 6215 if (LHS.get()->getType()->hasIntegerRepresentation() && 6216 RHS.get()->getType()->hasIntegerRepresentation()) 6217 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6218 return InvalidOperands(Loc, LHS, RHS); 6219 } 6220 6221 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6222 if (LHS.isInvalid() || RHS.isInvalid()) 6223 return QualType(); 6224 6225 if (compType.isNull() || !compType->isIntegerType()) 6226 return InvalidOperands(Loc, LHS, RHS); 6227 6228 // Check for remainder by zero. 6229 if (RHS.get()->isNullPointerConstant(Context, 6230 Expr::NPC_ValueDependentIsNotNull)) 6231 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero) 6232 << RHS.get()->getSourceRange()); 6233 6234 return compType; 6235} 6236 6237/// \brief Diagnose invalid arithmetic on two void pointers. 6238static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 6239 Expr *LHSExpr, Expr *RHSExpr) { 6240 S.Diag(Loc, S.getLangOpts().CPlusPlus 6241 ? diag::err_typecheck_pointer_arith_void_type 6242 : diag::ext_gnu_void_ptr) 6243 << 1 /* two pointers */ << LHSExpr->getSourceRange() 6244 << RHSExpr->getSourceRange(); 6245} 6246 6247/// \brief Diagnose invalid arithmetic on a void pointer. 6248static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 6249 Expr *Pointer) { 6250 S.Diag(Loc, S.getLangOpts().CPlusPlus 6251 ? diag::err_typecheck_pointer_arith_void_type 6252 : diag::ext_gnu_void_ptr) 6253 << 0 /* one pointer */ << Pointer->getSourceRange(); 6254} 6255 6256/// \brief Diagnose invalid arithmetic on two function pointers. 6257static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 6258 Expr *LHS, Expr *RHS) { 6259 assert(LHS->getType()->isAnyPointerType()); 6260 assert(RHS->getType()->isAnyPointerType()); 6261 S.Diag(Loc, S.getLangOpts().CPlusPlus 6262 ? diag::err_typecheck_pointer_arith_function_type 6263 : diag::ext_gnu_ptr_func_arith) 6264 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 6265 // We only show the second type if it differs from the first. 6266 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 6267 RHS->getType()) 6268 << RHS->getType()->getPointeeType() 6269 << LHS->getSourceRange() << RHS->getSourceRange(); 6270} 6271 6272/// \brief Diagnose invalid arithmetic on a function pointer. 6273static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 6274 Expr *Pointer) { 6275 assert(Pointer->getType()->isAnyPointerType()); 6276 S.Diag(Loc, S.getLangOpts().CPlusPlus 6277 ? diag::err_typecheck_pointer_arith_function_type 6278 : diag::ext_gnu_ptr_func_arith) 6279 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 6280 << 0 /* one pointer, so only one type */ 6281 << Pointer->getSourceRange(); 6282} 6283 6284/// \brief Emit error if Operand is incomplete pointer type 6285/// 6286/// \returns True if pointer has incomplete type 6287static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 6288 Expr *Operand) { 6289 assert(Operand->getType()->isAnyPointerType() && 6290 !Operand->getType()->isDependentType()); 6291 QualType PointeeTy = Operand->getType()->getPointeeType(); 6292 return S.RequireCompleteType(Loc, PointeeTy, 6293 diag::err_typecheck_arithmetic_incomplete_type, 6294 PointeeTy, Operand->getSourceRange()); 6295} 6296 6297/// \brief Check the validity of an arithmetic pointer operand. 6298/// 6299/// If the operand has pointer type, this code will check for pointer types 6300/// which are invalid in arithmetic operations. These will be diagnosed 6301/// appropriately, including whether or not the use is supported as an 6302/// extension. 6303/// 6304/// \returns True when the operand is valid to use (even if as an extension). 6305static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 6306 Expr *Operand) { 6307 if (!Operand->getType()->isAnyPointerType()) return true; 6308 6309 QualType PointeeTy = Operand->getType()->getPointeeType(); 6310 if (PointeeTy->isVoidType()) { 6311 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 6312 return !S.getLangOpts().CPlusPlus; 6313 } 6314 if (PointeeTy->isFunctionType()) { 6315 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 6316 return !S.getLangOpts().CPlusPlus; 6317 } 6318 6319 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 6320 6321 return true; 6322} 6323 6324/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 6325/// operands. 6326/// 6327/// This routine will diagnose any invalid arithmetic on pointer operands much 6328/// like \see checkArithmeticOpPointerOperand. However, it has special logic 6329/// for emitting a single diagnostic even for operations where both LHS and RHS 6330/// are (potentially problematic) pointers. 6331/// 6332/// \returns True when the operand is valid to use (even if as an extension). 6333static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 6334 Expr *LHSExpr, Expr *RHSExpr) { 6335 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 6336 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 6337 if (!isLHSPointer && !isRHSPointer) return true; 6338 6339 QualType LHSPointeeTy, RHSPointeeTy; 6340 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 6341 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 6342 6343 // Check for arithmetic on pointers to incomplete types. 6344 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 6345 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 6346 if (isLHSVoidPtr || isRHSVoidPtr) { 6347 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 6348 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 6349 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 6350 6351 return !S.getLangOpts().CPlusPlus; 6352 } 6353 6354 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 6355 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 6356 if (isLHSFuncPtr || isRHSFuncPtr) { 6357 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 6358 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 6359 RHSExpr); 6360 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 6361 6362 return !S.getLangOpts().CPlusPlus; 6363 } 6364 6365 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 6366 return false; 6367 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 6368 return false; 6369 6370 return true; 6371} 6372 6373/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 6374/// literal. 6375static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 6376 Expr *LHSExpr, Expr *RHSExpr) { 6377 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 6378 Expr* IndexExpr = RHSExpr; 6379 if (!StrExpr) { 6380 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 6381 IndexExpr = LHSExpr; 6382 } 6383 6384 bool IsStringPlusInt = StrExpr && 6385 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 6386 if (!IsStringPlusInt) 6387 return; 6388 6389 llvm::APSInt index; 6390 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 6391 unsigned StrLenWithNull = StrExpr->getLength() + 1; 6392 if (index.isNonNegative() && 6393 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 6394 index.isUnsigned())) 6395 return; 6396 } 6397 6398 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 6399 Self.Diag(OpLoc, diag::warn_string_plus_int) 6400 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 6401 6402 // Only print a fixit for "str" + int, not for int + "str". 6403 if (IndexExpr == RHSExpr) { 6404 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 6405 Self.Diag(OpLoc, diag::note_string_plus_int_silence) 6406 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 6407 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 6408 << FixItHint::CreateInsertion(EndLoc, "]"); 6409 } else 6410 Self.Diag(OpLoc, diag::note_string_plus_int_silence); 6411} 6412 6413/// \brief Emit error when two pointers are incompatible. 6414static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 6415 Expr *LHSExpr, Expr *RHSExpr) { 6416 assert(LHSExpr->getType()->isAnyPointerType()); 6417 assert(RHSExpr->getType()->isAnyPointerType()); 6418 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 6419 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 6420 << RHSExpr->getSourceRange(); 6421} 6422 6423QualType Sema::CheckAdditionOperands( // C99 6.5.6 6424 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 6425 QualType* CompLHSTy) { 6426 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6427 6428 if (LHS.get()->getType()->isVectorType() || 6429 RHS.get()->getType()->isVectorType()) { 6430 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 6431 if (CompLHSTy) *CompLHSTy = compType; 6432 return compType; 6433 } 6434 6435 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 6436 if (LHS.isInvalid() || RHS.isInvalid()) 6437 return QualType(); 6438 6439 // Diagnose "string literal" '+' int. 6440 if (Opc == BO_Add) 6441 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 6442 6443 // handle the common case first (both operands are arithmetic). 6444 if (!compType.isNull() && compType->isArithmeticType()) { 6445 if (CompLHSTy) *CompLHSTy = compType; 6446 return compType; 6447 } 6448 6449 // Type-checking. Ultimately the pointer's going to be in PExp; 6450 // note that we bias towards the LHS being the pointer. 6451 Expr *PExp = LHS.get(), *IExp = RHS.get(); 6452 6453 bool isObjCPointer; 6454 if (PExp->getType()->isPointerType()) { 6455 isObjCPointer = false; 6456 } else if (PExp->getType()->isObjCObjectPointerType()) { 6457 isObjCPointer = true; 6458 } else { 6459 std::swap(PExp, IExp); 6460 if (PExp->getType()->isPointerType()) { 6461 isObjCPointer = false; 6462 } else if (PExp->getType()->isObjCObjectPointerType()) { 6463 isObjCPointer = true; 6464 } else { 6465 return InvalidOperands(Loc, LHS, RHS); 6466 } 6467 } 6468 assert(PExp->getType()->isAnyPointerType()); 6469 6470 if (!IExp->getType()->isIntegerType()) 6471 return InvalidOperands(Loc, LHS, RHS); 6472 6473 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 6474 return QualType(); 6475 6476 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 6477 return QualType(); 6478 6479 // Check array bounds for pointer arithemtic 6480 CheckArrayAccess(PExp, IExp); 6481 6482 if (CompLHSTy) { 6483 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 6484 if (LHSTy.isNull()) { 6485 LHSTy = LHS.get()->getType(); 6486 if (LHSTy->isPromotableIntegerType()) 6487 LHSTy = Context.getPromotedIntegerType(LHSTy); 6488 } 6489 *CompLHSTy = LHSTy; 6490 } 6491 6492 return PExp->getType(); 6493} 6494 6495// C99 6.5.6 6496QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 6497 SourceLocation Loc, 6498 QualType* CompLHSTy) { 6499 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6500 6501 if (LHS.get()->getType()->isVectorType() || 6502 RHS.get()->getType()->isVectorType()) { 6503 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 6504 if (CompLHSTy) *CompLHSTy = compType; 6505 return compType; 6506 } 6507 6508 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 6509 if (LHS.isInvalid() || RHS.isInvalid()) 6510 return QualType(); 6511 6512 // Enforce type constraints: C99 6.5.6p3. 6513 6514 // Handle the common case first (both operands are arithmetic). 6515 if (!compType.isNull() && compType->isArithmeticType()) { 6516 if (CompLHSTy) *CompLHSTy = compType; 6517 return compType; 6518 } 6519 6520 // Either ptr - int or ptr - ptr. 6521 if (LHS.get()->getType()->isAnyPointerType()) { 6522 QualType lpointee = LHS.get()->getType()->getPointeeType(); 6523 6524 // Diagnose bad cases where we step over interface counts. 6525 if (LHS.get()->getType()->isObjCObjectPointerType() && 6526 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 6527 return QualType(); 6528 6529 // The result type of a pointer-int computation is the pointer type. 6530 if (RHS.get()->getType()->isIntegerType()) { 6531 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 6532 return QualType(); 6533 6534 // Check array bounds for pointer arithemtic 6535 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0, 6536 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 6537 6538 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 6539 return LHS.get()->getType(); 6540 } 6541 6542 // Handle pointer-pointer subtractions. 6543 if (const PointerType *RHSPTy 6544 = RHS.get()->getType()->getAs<PointerType>()) { 6545 QualType rpointee = RHSPTy->getPointeeType(); 6546 6547 if (getLangOpts().CPlusPlus) { 6548 // Pointee types must be the same: C++ [expr.add] 6549 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 6550 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 6551 } 6552 } else { 6553 // Pointee types must be compatible C99 6.5.6p3 6554 if (!Context.typesAreCompatible( 6555 Context.getCanonicalType(lpointee).getUnqualifiedType(), 6556 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 6557 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 6558 return QualType(); 6559 } 6560 } 6561 6562 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 6563 LHS.get(), RHS.get())) 6564 return QualType(); 6565 6566 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 6567 return Context.getPointerDiffType(); 6568 } 6569 } 6570 6571 return InvalidOperands(Loc, LHS, RHS); 6572} 6573 6574static bool isScopedEnumerationType(QualType T) { 6575 if (const EnumType *ET = dyn_cast<EnumType>(T)) 6576 return ET->getDecl()->isScoped(); 6577 return false; 6578} 6579 6580static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 6581 SourceLocation Loc, unsigned Opc, 6582 QualType LHSType) { 6583 llvm::APSInt Right; 6584 // Check right/shifter operand 6585 if (RHS.get()->isValueDependent() || 6586 !RHS.get()->isIntegerConstantExpr(Right, S.Context)) 6587 return; 6588 6589 if (Right.isNegative()) { 6590 S.DiagRuntimeBehavior(Loc, RHS.get(), 6591 S.PDiag(diag::warn_shift_negative) 6592 << RHS.get()->getSourceRange()); 6593 return; 6594 } 6595 llvm::APInt LeftBits(Right.getBitWidth(), 6596 S.Context.getTypeSize(LHS.get()->getType())); 6597 if (Right.uge(LeftBits)) { 6598 S.DiagRuntimeBehavior(Loc, RHS.get(), 6599 S.PDiag(diag::warn_shift_gt_typewidth) 6600 << RHS.get()->getSourceRange()); 6601 return; 6602 } 6603 if (Opc != BO_Shl) 6604 return; 6605 6606 // When left shifting an ICE which is signed, we can check for overflow which 6607 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 6608 // integers have defined behavior modulo one more than the maximum value 6609 // representable in the result type, so never warn for those. 6610 llvm::APSInt Left; 6611 if (LHS.get()->isValueDependent() || 6612 !LHS.get()->isIntegerConstantExpr(Left, S.Context) || 6613 LHSType->hasUnsignedIntegerRepresentation()) 6614 return; 6615 llvm::APInt ResultBits = 6616 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 6617 if (LeftBits.uge(ResultBits)) 6618 return; 6619 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 6620 Result = Result.shl(Right); 6621 6622 // Print the bit representation of the signed integer as an unsigned 6623 // hexadecimal number. 6624 SmallString<40> HexResult; 6625 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 6626 6627 // If we are only missing a sign bit, this is less likely to result in actual 6628 // bugs -- if the result is cast back to an unsigned type, it will have the 6629 // expected value. Thus we place this behind a different warning that can be 6630 // turned off separately if needed. 6631 if (LeftBits == ResultBits - 1) { 6632 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 6633 << HexResult.str() << LHSType 6634 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6635 return; 6636 } 6637 6638 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 6639 << HexResult.str() << Result.getMinSignedBits() << LHSType 6640 << Left.getBitWidth() << LHS.get()->getSourceRange() 6641 << RHS.get()->getSourceRange(); 6642} 6643 6644// C99 6.5.7 6645QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 6646 SourceLocation Loc, unsigned Opc, 6647 bool IsCompAssign) { 6648 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6649 6650 // C99 6.5.7p2: Each of the operands shall have integer type. 6651 if (!LHS.get()->getType()->hasIntegerRepresentation() || 6652 !RHS.get()->getType()->hasIntegerRepresentation()) 6653 return InvalidOperands(Loc, LHS, RHS); 6654 6655 // C++0x: Don't allow scoped enums. FIXME: Use something better than 6656 // hasIntegerRepresentation() above instead of this. 6657 if (isScopedEnumerationType(LHS.get()->getType()) || 6658 isScopedEnumerationType(RHS.get()->getType())) { 6659 return InvalidOperands(Loc, LHS, RHS); 6660 } 6661 6662 // Vector shifts promote their scalar inputs to vector type. 6663 if (LHS.get()->getType()->isVectorType() || 6664 RHS.get()->getType()->isVectorType()) 6665 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6666 6667 // Shifts don't perform usual arithmetic conversions, they just do integer 6668 // promotions on each operand. C99 6.5.7p3 6669 6670 // For the LHS, do usual unary conversions, but then reset them away 6671 // if this is a compound assignment. 6672 ExprResult OldLHS = LHS; 6673 LHS = UsualUnaryConversions(LHS.take()); 6674 if (LHS.isInvalid()) 6675 return QualType(); 6676 QualType LHSType = LHS.get()->getType(); 6677 if (IsCompAssign) LHS = OldLHS; 6678 6679 // The RHS is simpler. 6680 RHS = UsualUnaryConversions(RHS.take()); 6681 if (RHS.isInvalid()) 6682 return QualType(); 6683 6684 // Sanity-check shift operands 6685 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 6686 6687 // "The type of the result is that of the promoted left operand." 6688 return LHSType; 6689} 6690 6691static bool IsWithinTemplateSpecialization(Decl *D) { 6692 if (DeclContext *DC = D->getDeclContext()) { 6693 if (isa<ClassTemplateSpecializationDecl>(DC)) 6694 return true; 6695 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 6696 return FD->isFunctionTemplateSpecialization(); 6697 } 6698 return false; 6699} 6700 6701/// If two different enums are compared, raise a warning. 6702static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, 6703 ExprResult &RHS) { 6704 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType(); 6705 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType(); 6706 6707 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 6708 if (!LHSEnumType) 6709 return; 6710 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 6711 if (!RHSEnumType) 6712 return; 6713 6714 // Ignore anonymous enums. 6715 if (!LHSEnumType->getDecl()->getIdentifier()) 6716 return; 6717 if (!RHSEnumType->getDecl()->getIdentifier()) 6718 return; 6719 6720 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 6721 return; 6722 6723 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 6724 << LHSStrippedType << RHSStrippedType 6725 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6726} 6727 6728/// \brief Diagnose bad pointer comparisons. 6729static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 6730 ExprResult &LHS, ExprResult &RHS, 6731 bool IsError) { 6732 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 6733 : diag::ext_typecheck_comparison_of_distinct_pointers) 6734 << LHS.get()->getType() << RHS.get()->getType() 6735 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6736} 6737 6738/// \brief Returns false if the pointers are converted to a composite type, 6739/// true otherwise. 6740static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 6741 ExprResult &LHS, ExprResult &RHS) { 6742 // C++ [expr.rel]p2: 6743 // [...] Pointer conversions (4.10) and qualification 6744 // conversions (4.4) are performed on pointer operands (or on 6745 // a pointer operand and a null pointer constant) to bring 6746 // them to their composite pointer type. [...] 6747 // 6748 // C++ [expr.eq]p1 uses the same notion for (in)equality 6749 // comparisons of pointers. 6750 6751 // C++ [expr.eq]p2: 6752 // In addition, pointers to members can be compared, or a pointer to 6753 // member and a null pointer constant. Pointer to member conversions 6754 // (4.11) and qualification conversions (4.4) are performed to bring 6755 // them to a common type. If one operand is a null pointer constant, 6756 // the common type is the type of the other operand. Otherwise, the 6757 // common type is a pointer to member type similar (4.4) to the type 6758 // of one of the operands, with a cv-qualification signature (4.4) 6759 // that is the union of the cv-qualification signatures of the operand 6760 // types. 6761 6762 QualType LHSType = LHS.get()->getType(); 6763 QualType RHSType = RHS.get()->getType(); 6764 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 6765 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 6766 6767 bool NonStandardCompositeType = false; 6768 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType; 6769 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 6770 if (T.isNull()) { 6771 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 6772 return true; 6773 } 6774 6775 if (NonStandardCompositeType) 6776 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 6777 << LHSType << RHSType << T << LHS.get()->getSourceRange() 6778 << RHS.get()->getSourceRange(); 6779 6780 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast); 6781 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast); 6782 return false; 6783} 6784 6785static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 6786 ExprResult &LHS, 6787 ExprResult &RHS, 6788 bool IsError) { 6789 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 6790 : diag::ext_typecheck_comparison_of_fptr_to_void) 6791 << LHS.get()->getType() << RHS.get()->getType() 6792 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6793} 6794 6795static bool isObjCObjectLiteral(ExprResult &E) { 6796 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 6797 case Stmt::ObjCArrayLiteralClass: 6798 case Stmt::ObjCDictionaryLiteralClass: 6799 case Stmt::ObjCStringLiteralClass: 6800 case Stmt::ObjCBoxedExprClass: 6801 return true; 6802 default: 6803 // Note that ObjCBoolLiteral is NOT an object literal! 6804 return false; 6805 } 6806} 6807 6808static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 6809 // Get the LHS object's interface type. 6810 QualType Type = LHS->getType(); 6811 QualType InterfaceType; 6812 if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) { 6813 InterfaceType = PTy->getPointeeType(); 6814 if (const ObjCObjectType *iQFaceTy = 6815 InterfaceType->getAsObjCQualifiedInterfaceType()) 6816 InterfaceType = iQFaceTy->getBaseType(); 6817 } else { 6818 // If this is not actually an Objective-C object, bail out. 6819 return false; 6820 } 6821 6822 // If the RHS isn't an Objective-C object, bail out. 6823 if (!RHS->getType()->isObjCObjectPointerType()) 6824 return false; 6825 6826 // Try to find the -isEqual: method. 6827 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 6828 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 6829 InterfaceType, 6830 /*instance=*/true); 6831 if (!Method) { 6832 if (Type->isObjCIdType()) { 6833 // For 'id', just check the global pool. 6834 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 6835 /*receiverId=*/true, 6836 /*warn=*/false); 6837 } else { 6838 // Check protocols. 6839 Method = S.LookupMethodInQualifiedType(IsEqualSel, 6840 cast<ObjCObjectPointerType>(Type), 6841 /*instance=*/true); 6842 } 6843 } 6844 6845 if (!Method) 6846 return false; 6847 6848 QualType T = Method->param_begin()[0]->getType(); 6849 if (!T->isObjCObjectPointerType()) 6850 return false; 6851 6852 QualType R = Method->getResultType(); 6853 if (!R->isScalarType()) 6854 return false; 6855 6856 return true; 6857} 6858 6859static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 6860 ExprResult &LHS, ExprResult &RHS, 6861 BinaryOperator::Opcode Opc){ 6862 Expr *Literal; 6863 Expr *Other; 6864 if (isObjCObjectLiteral(LHS)) { 6865 Literal = LHS.get(); 6866 Other = RHS.get(); 6867 } else { 6868 Literal = RHS.get(); 6869 Other = LHS.get(); 6870 } 6871 6872 // Don't warn on comparisons against nil. 6873 Other = Other->IgnoreParenCasts(); 6874 if (Other->isNullPointerConstant(S.getASTContext(), 6875 Expr::NPC_ValueDependentIsNotNull)) 6876 return; 6877 6878 // This should be kept in sync with warn_objc_literal_comparison. 6879 // LK_String should always be last, since it has its own warning flag. 6880 enum { 6881 LK_Array, 6882 LK_Dictionary, 6883 LK_Numeric, 6884 LK_Boxed, 6885 LK_String 6886 } LiteralKind; 6887 6888 Literal = Literal->IgnoreParenImpCasts(); 6889 switch (Literal->getStmtClass()) { 6890 case Stmt::ObjCStringLiteralClass: 6891 // "string literal" 6892 LiteralKind = LK_String; 6893 break; 6894 case Stmt::ObjCArrayLiteralClass: 6895 // "array literal" 6896 LiteralKind = LK_Array; 6897 break; 6898 case Stmt::ObjCDictionaryLiteralClass: 6899 // "dictionary literal" 6900 LiteralKind = LK_Dictionary; 6901 break; 6902 case Stmt::ObjCBoxedExprClass: { 6903 Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr(); 6904 switch (Inner->getStmtClass()) { 6905 case Stmt::IntegerLiteralClass: 6906 case Stmt::FloatingLiteralClass: 6907 case Stmt::CharacterLiteralClass: 6908 case Stmt::ObjCBoolLiteralExprClass: 6909 case Stmt::CXXBoolLiteralExprClass: 6910 // "numeric literal" 6911 LiteralKind = LK_Numeric; 6912 break; 6913 case Stmt::ImplicitCastExprClass: { 6914 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 6915 // Boolean literals can be represented by implicit casts. 6916 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) { 6917 LiteralKind = LK_Numeric; 6918 break; 6919 } 6920 // FALLTHROUGH 6921 } 6922 default: 6923 // "boxed expression" 6924 LiteralKind = LK_Boxed; 6925 break; 6926 } 6927 break; 6928 } 6929 default: 6930 llvm_unreachable("Unknown Objective-C object literal kind"); 6931 } 6932 6933 if (LiteralKind == LK_String) 6934 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 6935 << Literal->getSourceRange(); 6936 else 6937 S.Diag(Loc, diag::warn_objc_literal_comparison) 6938 << LiteralKind << Literal->getSourceRange(); 6939 6940 if (BinaryOperator::isEqualityOp(Opc) && 6941 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 6942 SourceLocation Start = LHS.get()->getLocStart(); 6943 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 6944 SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc)); 6945 6946 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 6947 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 6948 << FixItHint::CreateReplacement(OpRange, "isEqual:") 6949 << FixItHint::CreateInsertion(End, "]"); 6950 } 6951} 6952 6953// C99 6.5.8, C++ [expr.rel] 6954QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 6955 SourceLocation Loc, unsigned OpaqueOpc, 6956 bool IsRelational) { 6957 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 6958 6959 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 6960 6961 // Handle vector comparisons separately. 6962 if (LHS.get()->getType()->isVectorType() || 6963 RHS.get()->getType()->isVectorType()) 6964 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 6965 6966 QualType LHSType = LHS.get()->getType(); 6967 QualType RHSType = RHS.get()->getType(); 6968 6969 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 6970 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 6971 6972 checkEnumComparison(*this, Loc, LHS, RHS); 6973 6974 if (!LHSType->hasFloatingRepresentation() && 6975 !(LHSType->isBlockPointerType() && IsRelational) && 6976 !LHS.get()->getLocStart().isMacroID() && 6977 !RHS.get()->getLocStart().isMacroID()) { 6978 // For non-floating point types, check for self-comparisons of the form 6979 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 6980 // often indicate logic errors in the program. 6981 // 6982 // NOTE: Don't warn about comparison expressions resulting from macro 6983 // expansion. Also don't warn about comparisons which are only self 6984 // comparisons within a template specialization. The warnings should catch 6985 // obvious cases in the definition of the template anyways. The idea is to 6986 // warn when the typed comparison operator will always evaluate to the same 6987 // result. 6988 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) { 6989 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) { 6990 if (DRL->getDecl() == DRR->getDecl() && 6991 !IsWithinTemplateSpecialization(DRL->getDecl())) { 6992 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 6993 << 0 // self- 6994 << (Opc == BO_EQ 6995 || Opc == BO_LE 6996 || Opc == BO_GE)); 6997 } else if (LHSType->isArrayType() && RHSType->isArrayType() && 6998 !DRL->getDecl()->getType()->isReferenceType() && 6999 !DRR->getDecl()->getType()->isReferenceType()) { 7000 // what is it always going to eval to? 7001 char always_evals_to; 7002 switch(Opc) { 7003 case BO_EQ: // e.g. array1 == array2 7004 always_evals_to = 0; // false 7005 break; 7006 case BO_NE: // e.g. array1 != array2 7007 always_evals_to = 1; // true 7008 break; 7009 default: 7010 // best we can say is 'a constant' 7011 always_evals_to = 2; // e.g. array1 <= array2 7012 break; 7013 } 7014 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7015 << 1 // array 7016 << always_evals_to); 7017 } 7018 } 7019 } 7020 7021 if (isa<CastExpr>(LHSStripped)) 7022 LHSStripped = LHSStripped->IgnoreParenCasts(); 7023 if (isa<CastExpr>(RHSStripped)) 7024 RHSStripped = RHSStripped->IgnoreParenCasts(); 7025 7026 // Warn about comparisons against a string constant (unless the other 7027 // operand is null), the user probably wants strcmp. 7028 Expr *literalString = 0; 7029 Expr *literalStringStripped = 0; 7030 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 7031 !RHSStripped->isNullPointerConstant(Context, 7032 Expr::NPC_ValueDependentIsNull)) { 7033 literalString = LHS.get(); 7034 literalStringStripped = LHSStripped; 7035 } else if ((isa<StringLiteral>(RHSStripped) || 7036 isa<ObjCEncodeExpr>(RHSStripped)) && 7037 !LHSStripped->isNullPointerConstant(Context, 7038 Expr::NPC_ValueDependentIsNull)) { 7039 literalString = RHS.get(); 7040 literalStringStripped = RHSStripped; 7041 } 7042 7043 if (literalString) { 7044 std::string resultComparison; 7045 switch (Opc) { 7046 case BO_LT: resultComparison = ") < 0"; break; 7047 case BO_GT: resultComparison = ") > 0"; break; 7048 case BO_LE: resultComparison = ") <= 0"; break; 7049 case BO_GE: resultComparison = ") >= 0"; break; 7050 case BO_EQ: resultComparison = ") == 0"; break; 7051 case BO_NE: resultComparison = ") != 0"; break; 7052 default: llvm_unreachable("Invalid comparison operator"); 7053 } 7054 7055 DiagRuntimeBehavior(Loc, 0, 7056 PDiag(diag::warn_stringcompare) 7057 << isa<ObjCEncodeExpr>(literalStringStripped) 7058 << literalString->getSourceRange()); 7059 } 7060 } 7061 7062 // C99 6.5.8p3 / C99 6.5.9p4 7063 if (LHS.get()->getType()->isArithmeticType() && 7064 RHS.get()->getType()->isArithmeticType()) { 7065 UsualArithmeticConversions(LHS, RHS); 7066 if (LHS.isInvalid() || RHS.isInvalid()) 7067 return QualType(); 7068 } 7069 else { 7070 LHS = UsualUnaryConversions(LHS.take()); 7071 if (LHS.isInvalid()) 7072 return QualType(); 7073 7074 RHS = UsualUnaryConversions(RHS.take()); 7075 if (RHS.isInvalid()) 7076 return QualType(); 7077 } 7078 7079 LHSType = LHS.get()->getType(); 7080 RHSType = RHS.get()->getType(); 7081 7082 // The result of comparisons is 'bool' in C++, 'int' in C. 7083 QualType ResultTy = Context.getLogicalOperationType(); 7084 7085 if (IsRelational) { 7086 if (LHSType->isRealType() && RHSType->isRealType()) 7087 return ResultTy; 7088 } else { 7089 // Check for comparisons of floating point operands using != and ==. 7090 if (LHSType->hasFloatingRepresentation()) 7091 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 7092 7093 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 7094 return ResultTy; 7095 } 7096 7097 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context, 7098 Expr::NPC_ValueDependentIsNull); 7099 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context, 7100 Expr::NPC_ValueDependentIsNull); 7101 7102 // All of the following pointer-related warnings are GCC extensions, except 7103 // when handling null pointer constants. 7104 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 7105 QualType LCanPointeeTy = 7106 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7107 QualType RCanPointeeTy = 7108 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7109 7110 if (getLangOpts().CPlusPlus) { 7111 if (LCanPointeeTy == RCanPointeeTy) 7112 return ResultTy; 7113 if (!IsRelational && 7114 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7115 // Valid unless comparison between non-null pointer and function pointer 7116 // This is a gcc extension compatibility comparison. 7117 // In a SFINAE context, we treat this as a hard error to maintain 7118 // conformance with the C++ standard. 7119 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7120 && !LHSIsNull && !RHSIsNull) { 7121 diagnoseFunctionPointerToVoidComparison( 7122 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext()); 7123 7124 if (isSFINAEContext()) 7125 return QualType(); 7126 7127 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7128 return ResultTy; 7129 } 7130 } 7131 7132 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7133 return QualType(); 7134 else 7135 return ResultTy; 7136 } 7137 // C99 6.5.9p2 and C99 6.5.8p2 7138 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 7139 RCanPointeeTy.getUnqualifiedType())) { 7140 // Valid unless a relational comparison of function pointers 7141 if (IsRelational && LCanPointeeTy->isFunctionType()) { 7142 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 7143 << LHSType << RHSType << LHS.get()->getSourceRange() 7144 << RHS.get()->getSourceRange(); 7145 } 7146 } else if (!IsRelational && 7147 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7148 // Valid unless comparison between non-null pointer and function pointer 7149 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7150 && !LHSIsNull && !RHSIsNull) 7151 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 7152 /*isError*/false); 7153 } else { 7154 // Invalid 7155 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 7156 } 7157 if (LCanPointeeTy != RCanPointeeTy) { 7158 if (LHSIsNull && !RHSIsNull) 7159 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 7160 else 7161 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7162 } 7163 return ResultTy; 7164 } 7165 7166 if (getLangOpts().CPlusPlus) { 7167 // Comparison of nullptr_t with itself. 7168 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 7169 return ResultTy; 7170 7171 // Comparison of pointers with null pointer constants and equality 7172 // comparisons of member pointers to null pointer constants. 7173 if (RHSIsNull && 7174 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 7175 (!IsRelational && 7176 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 7177 RHS = ImpCastExprToType(RHS.take(), LHSType, 7178 LHSType->isMemberPointerType() 7179 ? CK_NullToMemberPointer 7180 : CK_NullToPointer); 7181 return ResultTy; 7182 } 7183 if (LHSIsNull && 7184 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 7185 (!IsRelational && 7186 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 7187 LHS = ImpCastExprToType(LHS.take(), RHSType, 7188 RHSType->isMemberPointerType() 7189 ? CK_NullToMemberPointer 7190 : CK_NullToPointer); 7191 return ResultTy; 7192 } 7193 7194 // Comparison of member pointers. 7195 if (!IsRelational && 7196 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 7197 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7198 return QualType(); 7199 else 7200 return ResultTy; 7201 } 7202 7203 // Handle scoped enumeration types specifically, since they don't promote 7204 // to integers. 7205 if (LHS.get()->getType()->isEnumeralType() && 7206 Context.hasSameUnqualifiedType(LHS.get()->getType(), 7207 RHS.get()->getType())) 7208 return ResultTy; 7209 } 7210 7211 // Handle block pointer types. 7212 if (!IsRelational && LHSType->isBlockPointerType() && 7213 RHSType->isBlockPointerType()) { 7214 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 7215 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 7216 7217 if (!LHSIsNull && !RHSIsNull && 7218 !Context.typesAreCompatible(lpointee, rpointee)) { 7219 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 7220 << LHSType << RHSType << LHS.get()->getSourceRange() 7221 << RHS.get()->getSourceRange(); 7222 } 7223 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7224 return ResultTy; 7225 } 7226 7227 // Allow block pointers to be compared with null pointer constants. 7228 if (!IsRelational 7229 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 7230 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 7231 if (!LHSIsNull && !RHSIsNull) { 7232 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 7233 ->getPointeeType()->isVoidType()) 7234 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 7235 ->getPointeeType()->isVoidType()))) 7236 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 7237 << LHSType << RHSType << LHS.get()->getSourceRange() 7238 << RHS.get()->getSourceRange(); 7239 } 7240 if (LHSIsNull && !RHSIsNull) 7241 LHS = ImpCastExprToType(LHS.take(), RHSType, 7242 RHSType->isPointerType() ? CK_BitCast 7243 : CK_AnyPointerToBlockPointerCast); 7244 else 7245 RHS = ImpCastExprToType(RHS.take(), LHSType, 7246 LHSType->isPointerType() ? CK_BitCast 7247 : CK_AnyPointerToBlockPointerCast); 7248 return ResultTy; 7249 } 7250 7251 if (LHSType->isObjCObjectPointerType() || 7252 RHSType->isObjCObjectPointerType()) { 7253 const PointerType *LPT = LHSType->getAs<PointerType>(); 7254 const PointerType *RPT = RHSType->getAs<PointerType>(); 7255 if (LPT || RPT) { 7256 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 7257 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 7258 7259 if (!LPtrToVoid && !RPtrToVoid && 7260 !Context.typesAreCompatible(LHSType, RHSType)) { 7261 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 7262 /*isError*/false); 7263 } 7264 if (LHSIsNull && !RHSIsNull) 7265 LHS = ImpCastExprToType(LHS.take(), RHSType, 7266 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 7267 else 7268 RHS = ImpCastExprToType(RHS.take(), LHSType, 7269 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 7270 return ResultTy; 7271 } 7272 if (LHSType->isObjCObjectPointerType() && 7273 RHSType->isObjCObjectPointerType()) { 7274 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 7275 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 7276 /*isError*/false); 7277 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 7278 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 7279 7280 if (LHSIsNull && !RHSIsNull) 7281 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 7282 else 7283 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7284 return ResultTy; 7285 } 7286 } 7287 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 7288 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 7289 unsigned DiagID = 0; 7290 bool isError = false; 7291 if (LangOpts.DebuggerSupport) { 7292 // Under a debugger, allow the comparison of pointers to integers, 7293 // since users tend to want to compare addresses. 7294 } else if ((LHSIsNull && LHSType->isIntegerType()) || 7295 (RHSIsNull && RHSType->isIntegerType())) { 7296 if (IsRelational && !getLangOpts().CPlusPlus) 7297 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 7298 } else if (IsRelational && !getLangOpts().CPlusPlus) 7299 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 7300 else if (getLangOpts().CPlusPlus) { 7301 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 7302 isError = true; 7303 } else 7304 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 7305 7306 if (DiagID) { 7307 Diag(Loc, DiagID) 7308 << LHSType << RHSType << LHS.get()->getSourceRange() 7309 << RHS.get()->getSourceRange(); 7310 if (isError) 7311 return QualType(); 7312 } 7313 7314 if (LHSType->isIntegerType()) 7315 LHS = ImpCastExprToType(LHS.take(), RHSType, 7316 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 7317 else 7318 RHS = ImpCastExprToType(RHS.take(), LHSType, 7319 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 7320 return ResultTy; 7321 } 7322 7323 // Handle block pointers. 7324 if (!IsRelational && RHSIsNull 7325 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 7326 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 7327 return ResultTy; 7328 } 7329 if (!IsRelational && LHSIsNull 7330 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 7331 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer); 7332 return ResultTy; 7333 } 7334 7335 return InvalidOperands(Loc, LHS, RHS); 7336} 7337 7338 7339// Return a signed type that is of identical size and number of elements. 7340// For floating point vectors, return an integer type of identical size 7341// and number of elements. 7342QualType Sema::GetSignedVectorType(QualType V) { 7343 const VectorType *VTy = V->getAs<VectorType>(); 7344 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 7345 if (TypeSize == Context.getTypeSize(Context.CharTy)) 7346 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 7347 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 7348 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 7349 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 7350 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 7351 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 7352 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 7353 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 7354 "Unhandled vector element size in vector compare"); 7355 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 7356} 7357 7358/// CheckVectorCompareOperands - vector comparisons are a clang extension that 7359/// operates on extended vector types. Instead of producing an IntTy result, 7360/// like a scalar comparison, a vector comparison produces a vector of integer 7361/// types. 7362QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 7363 SourceLocation Loc, 7364 bool IsRelational) { 7365 // Check to make sure we're operating on vectors of the same type and width, 7366 // Allowing one side to be a scalar of element type. 7367 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false); 7368 if (vType.isNull()) 7369 return vType; 7370 7371 QualType LHSType = LHS.get()->getType(); 7372 7373 // If AltiVec, the comparison results in a numeric type, i.e. 7374 // bool for C++, int for C 7375 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 7376 return Context.getLogicalOperationType(); 7377 7378 // For non-floating point types, check for self-comparisons of the form 7379 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 7380 // often indicate logic errors in the program. 7381 if (!LHSType->hasFloatingRepresentation()) { 7382 if (DeclRefExpr* DRL 7383 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 7384 if (DeclRefExpr* DRR 7385 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 7386 if (DRL->getDecl() == DRR->getDecl()) 7387 DiagRuntimeBehavior(Loc, 0, 7388 PDiag(diag::warn_comparison_always) 7389 << 0 // self- 7390 << 2 // "a constant" 7391 ); 7392 } 7393 7394 // Check for comparisons of floating point operands using != and ==. 7395 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 7396 assert (RHS.get()->getType()->hasFloatingRepresentation()); 7397 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 7398 } 7399 7400 // Return a signed type for the vector. 7401 return GetSignedVectorType(LHSType); 7402} 7403 7404QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 7405 SourceLocation Loc) { 7406 // Ensure that either both operands are of the same vector type, or 7407 // one operand is of a vector type and the other is of its element type. 7408 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false); 7409 if (vType.isNull() || vType->isFloatingType()) 7410 return InvalidOperands(Loc, LHS, RHS); 7411 7412 return GetSignedVectorType(LHS.get()->getType()); 7413} 7414 7415inline QualType Sema::CheckBitwiseOperands( 7416 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 7417 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7418 7419 if (LHS.get()->getType()->isVectorType() || 7420 RHS.get()->getType()->isVectorType()) { 7421 if (LHS.get()->getType()->hasIntegerRepresentation() && 7422 RHS.get()->getType()->hasIntegerRepresentation()) 7423 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 7424 7425 return InvalidOperands(Loc, LHS, RHS); 7426 } 7427 7428 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS); 7429 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 7430 IsCompAssign); 7431 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 7432 return QualType(); 7433 LHS = LHSResult.take(); 7434 RHS = RHSResult.take(); 7435 7436 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 7437 return compType; 7438 return InvalidOperands(Loc, LHS, RHS); 7439} 7440 7441inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 7442 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) { 7443 7444 // Check vector operands differently. 7445 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 7446 return CheckVectorLogicalOperands(LHS, RHS, Loc); 7447 7448 // Diagnose cases where the user write a logical and/or but probably meant a 7449 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 7450 // is a constant. 7451 if (LHS.get()->getType()->isIntegerType() && 7452 !LHS.get()->getType()->isBooleanType() && 7453 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 7454 // Don't warn in macros or template instantiations. 7455 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 7456 // If the RHS can be constant folded, and if it constant folds to something 7457 // that isn't 0 or 1 (which indicate a potential logical operation that 7458 // happened to fold to true/false) then warn. 7459 // Parens on the RHS are ignored. 7460 llvm::APSInt Result; 7461 if (RHS.get()->EvaluateAsInt(Result, Context)) 7462 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) || 7463 (Result != 0 && Result != 1)) { 7464 Diag(Loc, diag::warn_logical_instead_of_bitwise) 7465 << RHS.get()->getSourceRange() 7466 << (Opc == BO_LAnd ? "&&" : "||"); 7467 // Suggest replacing the logical operator with the bitwise version 7468 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 7469 << (Opc == BO_LAnd ? "&" : "|") 7470 << FixItHint::CreateReplacement(SourceRange( 7471 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(), 7472 getLangOpts())), 7473 Opc == BO_LAnd ? "&" : "|"); 7474 if (Opc == BO_LAnd) 7475 // Suggest replacing "Foo() && kNonZero" with "Foo()" 7476 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 7477 << FixItHint::CreateRemoval( 7478 SourceRange( 7479 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(), 7480 0, getSourceManager(), 7481 getLangOpts()), 7482 RHS.get()->getLocEnd())); 7483 } 7484 } 7485 7486 if (!Context.getLangOpts().CPlusPlus) { 7487 LHS = UsualUnaryConversions(LHS.take()); 7488 if (LHS.isInvalid()) 7489 return QualType(); 7490 7491 RHS = UsualUnaryConversions(RHS.take()); 7492 if (RHS.isInvalid()) 7493 return QualType(); 7494 7495 if (!LHS.get()->getType()->isScalarType() || 7496 !RHS.get()->getType()->isScalarType()) 7497 return InvalidOperands(Loc, LHS, RHS); 7498 7499 return Context.IntTy; 7500 } 7501 7502 // The following is safe because we only use this method for 7503 // non-overloadable operands. 7504 7505 // C++ [expr.log.and]p1 7506 // C++ [expr.log.or]p1 7507 // The operands are both contextually converted to type bool. 7508 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 7509 if (LHSRes.isInvalid()) 7510 return InvalidOperands(Loc, LHS, RHS); 7511 LHS = LHSRes; 7512 7513 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 7514 if (RHSRes.isInvalid()) 7515 return InvalidOperands(Loc, LHS, RHS); 7516 RHS = RHSRes; 7517 7518 // C++ [expr.log.and]p2 7519 // C++ [expr.log.or]p2 7520 // The result is a bool. 7521 return Context.BoolTy; 7522} 7523 7524/// IsReadonlyProperty - Verify that otherwise a valid l-value expression 7525/// is a read-only property; return true if so. A readonly property expression 7526/// depends on various declarations and thus must be treated specially. 7527/// 7528static bool IsReadonlyProperty(Expr *E, Sema &S) { 7529 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E); 7530 if (!PropExpr) return false; 7531 if (PropExpr->isImplicitProperty()) return false; 7532 7533 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty(); 7534 QualType BaseType = PropExpr->isSuperReceiver() ? 7535 PropExpr->getSuperReceiverType() : 7536 PropExpr->getBase()->getType(); 7537 7538 if (const ObjCObjectPointerType *OPT = 7539 BaseType->getAsObjCInterfacePointerType()) 7540 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl()) 7541 if (S.isPropertyReadonly(PDecl, IFace)) 7542 return true; 7543 return false; 7544} 7545 7546static bool IsReadonlyMessage(Expr *E, Sema &S) { 7547 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 7548 if (!ME) return false; 7549 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 7550 ObjCMessageExpr *Base = 7551 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 7552 if (!Base) return false; 7553 return Base->getMethodDecl() != 0; 7554} 7555 7556/// Is the given expression (which must be 'const') a reference to a 7557/// variable which was originally non-const, but which has become 7558/// 'const' due to being captured within a block? 7559enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 7560static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 7561 assert(E->isLValue() && E->getType().isConstQualified()); 7562 E = E->IgnoreParens(); 7563 7564 // Must be a reference to a declaration from an enclosing scope. 7565 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 7566 if (!DRE) return NCCK_None; 7567 if (!DRE->refersToEnclosingLocal()) return NCCK_None; 7568 7569 // The declaration must be a variable which is not declared 'const'. 7570 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 7571 if (!var) return NCCK_None; 7572 if (var->getType().isConstQualified()) return NCCK_None; 7573 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 7574 7575 // Decide whether the first capture was for a block or a lambda. 7576 DeclContext *DC = S.CurContext; 7577 while (DC->getParent() != var->getDeclContext()) 7578 DC = DC->getParent(); 7579 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 7580} 7581 7582/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 7583/// emit an error and return true. If so, return false. 7584static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 7585 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 7586 SourceLocation OrigLoc = Loc; 7587 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 7588 &Loc); 7589 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S)) 7590 IsLV = Expr::MLV_ReadonlyProperty; 7591 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 7592 IsLV = Expr::MLV_InvalidMessageExpression; 7593 if (IsLV == Expr::MLV_Valid) 7594 return false; 7595 7596 unsigned Diag = 0; 7597 bool NeedType = false; 7598 switch (IsLV) { // C99 6.5.16p2 7599 case Expr::MLV_ConstQualified: 7600 Diag = diag::err_typecheck_assign_const; 7601 7602 // Use a specialized diagnostic when we're assigning to an object 7603 // from an enclosing function or block. 7604 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 7605 if (NCCK == NCCK_Block) 7606 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 7607 else 7608 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue; 7609 break; 7610 } 7611 7612 // In ARC, use some specialized diagnostics for occasions where we 7613 // infer 'const'. These are always pseudo-strong variables. 7614 if (S.getLangOpts().ObjCAutoRefCount) { 7615 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 7616 if (declRef && isa<VarDecl>(declRef->getDecl())) { 7617 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 7618 7619 // Use the normal diagnostic if it's pseudo-__strong but the 7620 // user actually wrote 'const'. 7621 if (var->isARCPseudoStrong() && 7622 (!var->getTypeSourceInfo() || 7623 !var->getTypeSourceInfo()->getType().isConstQualified())) { 7624 // There are two pseudo-strong cases: 7625 // - self 7626 ObjCMethodDecl *method = S.getCurMethodDecl(); 7627 if (method && var == method->getSelfDecl()) 7628 Diag = method->isClassMethod() 7629 ? diag::err_typecheck_arc_assign_self_class_method 7630 : diag::err_typecheck_arc_assign_self; 7631 7632 // - fast enumeration variables 7633 else 7634 Diag = diag::err_typecheck_arr_assign_enumeration; 7635 7636 SourceRange Assign; 7637 if (Loc != OrigLoc) 7638 Assign = SourceRange(OrigLoc, OrigLoc); 7639 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 7640 // We need to preserve the AST regardless, so migration tool 7641 // can do its job. 7642 return false; 7643 } 7644 } 7645 } 7646 7647 break; 7648 case Expr::MLV_ArrayType: 7649 case Expr::MLV_ArrayTemporary: 7650 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 7651 NeedType = true; 7652 break; 7653 case Expr::MLV_NotObjectType: 7654 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 7655 NeedType = true; 7656 break; 7657 case Expr::MLV_LValueCast: 7658 Diag = diag::err_typecheck_lvalue_casts_not_supported; 7659 break; 7660 case Expr::MLV_Valid: 7661 llvm_unreachable("did not take early return for MLV_Valid"); 7662 case Expr::MLV_InvalidExpression: 7663 case Expr::MLV_MemberFunction: 7664 case Expr::MLV_ClassTemporary: 7665 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 7666 break; 7667 case Expr::MLV_IncompleteType: 7668 case Expr::MLV_IncompleteVoidType: 7669 return S.RequireCompleteType(Loc, E->getType(), 7670 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 7671 case Expr::MLV_DuplicateVectorComponents: 7672 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 7673 break; 7674 case Expr::MLV_ReadonlyProperty: 7675 case Expr::MLV_NoSetterProperty: 7676 llvm_unreachable("readonly properties should be processed differently"); 7677 case Expr::MLV_InvalidMessageExpression: 7678 Diag = diag::error_readonly_message_assignment; 7679 break; 7680 case Expr::MLV_SubObjCPropertySetting: 7681 Diag = diag::error_no_subobject_property_setting; 7682 break; 7683 } 7684 7685 SourceRange Assign; 7686 if (Loc != OrigLoc) 7687 Assign = SourceRange(OrigLoc, OrigLoc); 7688 if (NeedType) 7689 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 7690 else 7691 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 7692 return true; 7693} 7694 7695static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 7696 SourceLocation Loc, 7697 Sema &Sema) { 7698 // C / C++ fields 7699 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 7700 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 7701 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 7702 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 7703 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 7704 } 7705 7706 // Objective-C instance variables 7707 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 7708 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 7709 if (OL && OR && OL->getDecl() == OR->getDecl()) { 7710 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 7711 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 7712 if (RL && RR && RL->getDecl() == RR->getDecl()) 7713 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 7714 } 7715} 7716 7717// C99 6.5.16.1 7718QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 7719 SourceLocation Loc, 7720 QualType CompoundType) { 7721 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 7722 7723 // Verify that LHS is a modifiable lvalue, and emit error if not. 7724 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 7725 return QualType(); 7726 7727 QualType LHSType = LHSExpr->getType(); 7728 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 7729 CompoundType; 7730 AssignConvertType ConvTy; 7731 if (CompoundType.isNull()) { 7732 Expr *RHSCheck = RHS.get(); 7733 7734 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 7735 7736 QualType LHSTy(LHSType); 7737 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 7738 if (RHS.isInvalid()) 7739 return QualType(); 7740 // Special case of NSObject attributes on c-style pointer types. 7741 if (ConvTy == IncompatiblePointer && 7742 ((Context.isObjCNSObjectType(LHSType) && 7743 RHSType->isObjCObjectPointerType()) || 7744 (Context.isObjCNSObjectType(RHSType) && 7745 LHSType->isObjCObjectPointerType()))) 7746 ConvTy = Compatible; 7747 7748 if (ConvTy == Compatible && 7749 LHSType->isObjCObjectType()) 7750 Diag(Loc, diag::err_objc_object_assignment) 7751 << LHSType; 7752 7753 // If the RHS is a unary plus or minus, check to see if they = and + are 7754 // right next to each other. If so, the user may have typo'd "x =+ 4" 7755 // instead of "x += 4". 7756 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 7757 RHSCheck = ICE->getSubExpr(); 7758 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 7759 if ((UO->getOpcode() == UO_Plus || 7760 UO->getOpcode() == UO_Minus) && 7761 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 7762 // Only if the two operators are exactly adjacent. 7763 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 7764 // And there is a space or other character before the subexpr of the 7765 // unary +/-. We don't want to warn on "x=-1". 7766 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 7767 UO->getSubExpr()->getLocStart().isFileID()) { 7768 Diag(Loc, diag::warn_not_compound_assign) 7769 << (UO->getOpcode() == UO_Plus ? "+" : "-") 7770 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 7771 } 7772 } 7773 7774 if (ConvTy == Compatible) { 7775 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 7776 // Warn about retain cycles where a block captures the LHS, but 7777 // not if the LHS is a simple variable into which the block is 7778 // being stored...unless that variable can be captured by reference! 7779 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 7780 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 7781 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 7782 checkRetainCycles(LHSExpr, RHS.get()); 7783 7784 // It is safe to assign a weak reference into a strong variable. 7785 // Although this code can still have problems: 7786 // id x = self.weakProp; 7787 // id y = self.weakProp; 7788 // we do not warn to warn spuriously when 'x' and 'y' are on separate 7789 // paths through the function. This should be revisited if 7790 // -Wrepeated-use-of-weak is made flow-sensitive. 7791 DiagnosticsEngine::Level Level = 7792 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 7793 RHS.get()->getLocStart()); 7794 if (Level != DiagnosticsEngine::Ignored) 7795 getCurFunction()->markSafeWeakUse(RHS.get()); 7796 7797 } else if (getLangOpts().ObjCAutoRefCount) { 7798 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 7799 } 7800 } 7801 } else { 7802 // Compound assignment "x += y" 7803 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 7804 } 7805 7806 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 7807 RHS.get(), AA_Assigning)) 7808 return QualType(); 7809 7810 CheckForNullPointerDereference(*this, LHSExpr); 7811 7812 // C99 6.5.16p3: The type of an assignment expression is the type of the 7813 // left operand unless the left operand has qualified type, in which case 7814 // it is the unqualified version of the type of the left operand. 7815 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 7816 // is converted to the type of the assignment expression (above). 7817 // C++ 5.17p1: the type of the assignment expression is that of its left 7818 // operand. 7819 return (getLangOpts().CPlusPlus 7820 ? LHSType : LHSType.getUnqualifiedType()); 7821} 7822 7823// C99 6.5.17 7824static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 7825 SourceLocation Loc) { 7826 LHS = S.CheckPlaceholderExpr(LHS.take()); 7827 RHS = S.CheckPlaceholderExpr(RHS.take()); 7828 if (LHS.isInvalid() || RHS.isInvalid()) 7829 return QualType(); 7830 7831 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 7832 // operands, but not unary promotions. 7833 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 7834 7835 // So we treat the LHS as a ignored value, and in C++ we allow the 7836 // containing site to determine what should be done with the RHS. 7837 LHS = S.IgnoredValueConversions(LHS.take()); 7838 if (LHS.isInvalid()) 7839 return QualType(); 7840 7841 S.DiagnoseUnusedExprResult(LHS.get()); 7842 7843 if (!S.getLangOpts().CPlusPlus) { 7844 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take()); 7845 if (RHS.isInvalid()) 7846 return QualType(); 7847 if (!RHS.get()->getType()->isVoidType()) 7848 S.RequireCompleteType(Loc, RHS.get()->getType(), 7849 diag::err_incomplete_type); 7850 } 7851 7852 return RHS.get()->getType(); 7853} 7854 7855/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 7856/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 7857static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 7858 ExprValueKind &VK, 7859 SourceLocation OpLoc, 7860 bool IsInc, bool IsPrefix) { 7861 if (Op->isTypeDependent()) 7862 return S.Context.DependentTy; 7863 7864 QualType ResType = Op->getType(); 7865 // Atomic types can be used for increment / decrement where the non-atomic 7866 // versions can, so ignore the _Atomic() specifier for the purpose of 7867 // checking. 7868 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 7869 ResType = ResAtomicType->getValueType(); 7870 7871 assert(!ResType.isNull() && "no type for increment/decrement expression"); 7872 7873 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 7874 // Decrement of bool is not allowed. 7875 if (!IsInc) { 7876 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 7877 return QualType(); 7878 } 7879 // Increment of bool sets it to true, but is deprecated. 7880 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 7881 } else if (ResType->isRealType()) { 7882 // OK! 7883 } else if (ResType->isPointerType()) { 7884 // C99 6.5.2.4p2, 6.5.6p2 7885 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 7886 return QualType(); 7887 } else if (ResType->isObjCObjectPointerType()) { 7888 // On modern runtimes, ObjC pointer arithmetic is forbidden. 7889 // Otherwise, we just need a complete type. 7890 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 7891 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 7892 return QualType(); 7893 } else if (ResType->isAnyComplexType()) { 7894 // C99 does not support ++/-- on complex types, we allow as an extension. 7895 S.Diag(OpLoc, diag::ext_integer_increment_complex) 7896 << ResType << Op->getSourceRange(); 7897 } else if (ResType->isPlaceholderType()) { 7898 ExprResult PR = S.CheckPlaceholderExpr(Op); 7899 if (PR.isInvalid()) return QualType(); 7900 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc, 7901 IsInc, IsPrefix); 7902 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 7903 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 7904 } else { 7905 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 7906 << ResType << int(IsInc) << Op->getSourceRange(); 7907 return QualType(); 7908 } 7909 // At this point, we know we have a real, complex or pointer type. 7910 // Now make sure the operand is a modifiable lvalue. 7911 if (CheckForModifiableLvalue(Op, OpLoc, S)) 7912 return QualType(); 7913 // In C++, a prefix increment is the same type as the operand. Otherwise 7914 // (in C or with postfix), the increment is the unqualified type of the 7915 // operand. 7916 if (IsPrefix && S.getLangOpts().CPlusPlus) { 7917 VK = VK_LValue; 7918 return ResType; 7919 } else { 7920 VK = VK_RValue; 7921 return ResType.getUnqualifiedType(); 7922 } 7923} 7924 7925 7926/// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 7927/// This routine allows us to typecheck complex/recursive expressions 7928/// where the declaration is needed for type checking. We only need to 7929/// handle cases when the expression references a function designator 7930/// or is an lvalue. Here are some examples: 7931/// - &(x) => x 7932/// - &*****f => f for f a function designator. 7933/// - &s.xx => s 7934/// - &s.zz[1].yy -> s, if zz is an array 7935/// - *(x + 1) -> x, if x is an array 7936/// - &"123"[2] -> 0 7937/// - & __real__ x -> x 7938static ValueDecl *getPrimaryDecl(Expr *E) { 7939 switch (E->getStmtClass()) { 7940 case Stmt::DeclRefExprClass: 7941 return cast<DeclRefExpr>(E)->getDecl(); 7942 case Stmt::MemberExprClass: 7943 // If this is an arrow operator, the address is an offset from 7944 // the base's value, so the object the base refers to is 7945 // irrelevant. 7946 if (cast<MemberExpr>(E)->isArrow()) 7947 return 0; 7948 // Otherwise, the expression refers to a part of the base 7949 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 7950 case Stmt::ArraySubscriptExprClass: { 7951 // FIXME: This code shouldn't be necessary! We should catch the implicit 7952 // promotion of register arrays earlier. 7953 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 7954 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 7955 if (ICE->getSubExpr()->getType()->isArrayType()) 7956 return getPrimaryDecl(ICE->getSubExpr()); 7957 } 7958 return 0; 7959 } 7960 case Stmt::UnaryOperatorClass: { 7961 UnaryOperator *UO = cast<UnaryOperator>(E); 7962 7963 switch(UO->getOpcode()) { 7964 case UO_Real: 7965 case UO_Imag: 7966 case UO_Extension: 7967 return getPrimaryDecl(UO->getSubExpr()); 7968 default: 7969 return 0; 7970 } 7971 } 7972 case Stmt::ParenExprClass: 7973 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 7974 case Stmt::ImplicitCastExprClass: 7975 // If the result of an implicit cast is an l-value, we care about 7976 // the sub-expression; otherwise, the result here doesn't matter. 7977 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 7978 default: 7979 return 0; 7980 } 7981} 7982 7983namespace { 7984 enum { 7985 AO_Bit_Field = 0, 7986 AO_Vector_Element = 1, 7987 AO_Property_Expansion = 2, 7988 AO_Register_Variable = 3, 7989 AO_No_Error = 4 7990 }; 7991} 7992/// \brief Diagnose invalid operand for address of operations. 7993/// 7994/// \param Type The type of operand which cannot have its address taken. 7995static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 7996 Expr *E, unsigned Type) { 7997 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 7998} 7999 8000/// CheckAddressOfOperand - The operand of & must be either a function 8001/// designator or an lvalue designating an object. If it is an lvalue, the 8002/// object cannot be declared with storage class register or be a bit field. 8003/// Note: The usual conversions are *not* applied to the operand of the & 8004/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 8005/// In C++, the operand might be an overloaded function name, in which case 8006/// we allow the '&' but retain the overloaded-function type. 8007static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp, 8008 SourceLocation OpLoc) { 8009 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 8010 if (PTy->getKind() == BuiltinType::Overload) { 8011 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) { 8012 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 8013 << OrigOp.get()->getSourceRange(); 8014 return QualType(); 8015 } 8016 8017 return S.Context.OverloadTy; 8018 } 8019 8020 if (PTy->getKind() == BuiltinType::UnknownAny) 8021 return S.Context.UnknownAnyTy; 8022 8023 if (PTy->getKind() == BuiltinType::BoundMember) { 8024 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8025 << OrigOp.get()->getSourceRange(); 8026 return QualType(); 8027 } 8028 8029 OrigOp = S.CheckPlaceholderExpr(OrigOp.take()); 8030 if (OrigOp.isInvalid()) return QualType(); 8031 } 8032 8033 if (OrigOp.get()->isTypeDependent()) 8034 return S.Context.DependentTy; 8035 8036 assert(!OrigOp.get()->getType()->isPlaceholderType()); 8037 8038 // Make sure to ignore parentheses in subsequent checks 8039 Expr *op = OrigOp.get()->IgnoreParens(); 8040 8041 if (S.getLangOpts().C99) { 8042 // Implement C99-only parts of addressof rules. 8043 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 8044 if (uOp->getOpcode() == UO_Deref) 8045 // Per C99 6.5.3.2, the address of a deref always returns a valid result 8046 // (assuming the deref expression is valid). 8047 return uOp->getSubExpr()->getType(); 8048 } 8049 // Technically, there should be a check for array subscript 8050 // expressions here, but the result of one is always an lvalue anyway. 8051 } 8052 ValueDecl *dcl = getPrimaryDecl(op); 8053 Expr::LValueClassification lval = op->ClassifyLValue(S.Context); 8054 unsigned AddressOfError = AO_No_Error; 8055 8056 if (lval == Expr::LV_ClassTemporary) { 8057 bool sfinae = S.isSFINAEContext(); 8058 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary 8059 : diag::ext_typecheck_addrof_class_temporary) 8060 << op->getType() << op->getSourceRange(); 8061 if (sfinae) 8062 return QualType(); 8063 } else if (isa<ObjCSelectorExpr>(op)) { 8064 return S.Context.getPointerType(op->getType()); 8065 } else if (lval == Expr::LV_MemberFunction) { 8066 // If it's an instance method, make a member pointer. 8067 // The expression must have exactly the form &A::foo. 8068 8069 // If the underlying expression isn't a decl ref, give up. 8070 if (!isa<DeclRefExpr>(op)) { 8071 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8072 << OrigOp.get()->getSourceRange(); 8073 return QualType(); 8074 } 8075 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 8076 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 8077 8078 // The id-expression was parenthesized. 8079 if (OrigOp.get() != DRE) { 8080 S.Diag(OpLoc, diag::err_parens_pointer_member_function) 8081 << OrigOp.get()->getSourceRange(); 8082 8083 // The method was named without a qualifier. 8084 } else if (!DRE->getQualifier()) { 8085 if (MD->getParent()->getName().empty()) 8086 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8087 << op->getSourceRange(); 8088 else { 8089 SmallString<32> Str; 8090 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 8091 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8092 << op->getSourceRange() 8093 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 8094 } 8095 } 8096 8097 return S.Context.getMemberPointerType(op->getType(), 8098 S.Context.getTypeDeclType(MD->getParent()).getTypePtr()); 8099 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 8100 // C99 6.5.3.2p1 8101 // The operand must be either an l-value or a function designator 8102 if (!op->getType()->isFunctionType()) { 8103 // Use a special diagnostic for loads from property references. 8104 if (isa<PseudoObjectExpr>(op)) { 8105 AddressOfError = AO_Property_Expansion; 8106 } else { 8107 // FIXME: emit more specific diag... 8108 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 8109 << op->getSourceRange(); 8110 return QualType(); 8111 } 8112 } 8113 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 8114 // The operand cannot be a bit-field 8115 AddressOfError = AO_Bit_Field; 8116 } else if (op->getObjectKind() == OK_VectorComponent) { 8117 // The operand cannot be an element of a vector 8118 AddressOfError = AO_Vector_Element; 8119 } else if (dcl) { // C99 6.5.3.2p1 8120 // We have an lvalue with a decl. Make sure the decl is not declared 8121 // with the register storage-class specifier. 8122 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 8123 // in C++ it is not error to take address of a register 8124 // variable (c++03 7.1.1P3) 8125 if (vd->getStorageClass() == SC_Register && 8126 !S.getLangOpts().CPlusPlus) { 8127 AddressOfError = AO_Register_Variable; 8128 } 8129 } else if (isa<FunctionTemplateDecl>(dcl)) { 8130 return S.Context.OverloadTy; 8131 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 8132 // Okay: we can take the address of a field. 8133 // Could be a pointer to member, though, if there is an explicit 8134 // scope qualifier for the class. 8135 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 8136 DeclContext *Ctx = dcl->getDeclContext(); 8137 if (Ctx && Ctx->isRecord()) { 8138 if (dcl->getType()->isReferenceType()) { 8139 S.Diag(OpLoc, 8140 diag::err_cannot_form_pointer_to_member_of_reference_type) 8141 << dcl->getDeclName() << dcl->getType(); 8142 return QualType(); 8143 } 8144 8145 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 8146 Ctx = Ctx->getParent(); 8147 return S.Context.getMemberPointerType(op->getType(), 8148 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 8149 } 8150 } 8151 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 8152 llvm_unreachable("Unknown/unexpected decl type"); 8153 } 8154 8155 if (AddressOfError != AO_No_Error) { 8156 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError); 8157 return QualType(); 8158 } 8159 8160 if (lval == Expr::LV_IncompleteVoidType) { 8161 // Taking the address of a void variable is technically illegal, but we 8162 // allow it in cases which are otherwise valid. 8163 // Example: "extern void x; void* y = &x;". 8164 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 8165 } 8166 8167 // If the operand has type "type", the result has type "pointer to type". 8168 if (op->getType()->isObjCObjectType()) 8169 return S.Context.getObjCObjectPointerType(op->getType()); 8170 return S.Context.getPointerType(op->getType()); 8171} 8172 8173/// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 8174static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 8175 SourceLocation OpLoc) { 8176 if (Op->isTypeDependent()) 8177 return S.Context.DependentTy; 8178 8179 ExprResult ConvResult = S.UsualUnaryConversions(Op); 8180 if (ConvResult.isInvalid()) 8181 return QualType(); 8182 Op = ConvResult.take(); 8183 QualType OpTy = Op->getType(); 8184 QualType Result; 8185 8186 if (isa<CXXReinterpretCastExpr>(Op)) { 8187 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 8188 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 8189 Op->getSourceRange()); 8190 } 8191 8192 // Note that per both C89 and C99, indirection is always legal, even if OpTy 8193 // is an incomplete type or void. It would be possible to warn about 8194 // dereferencing a void pointer, but it's completely well-defined, and such a 8195 // warning is unlikely to catch any mistakes. 8196 if (const PointerType *PT = OpTy->getAs<PointerType>()) 8197 Result = PT->getPointeeType(); 8198 else if (const ObjCObjectPointerType *OPT = 8199 OpTy->getAs<ObjCObjectPointerType>()) 8200 Result = OPT->getPointeeType(); 8201 else { 8202 ExprResult PR = S.CheckPlaceholderExpr(Op); 8203 if (PR.isInvalid()) return QualType(); 8204 if (PR.take() != Op) 8205 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc); 8206 } 8207 8208 if (Result.isNull()) { 8209 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 8210 << OpTy << Op->getSourceRange(); 8211 return QualType(); 8212 } 8213 8214 // Dereferences are usually l-values... 8215 VK = VK_LValue; 8216 8217 // ...except that certain expressions are never l-values in C. 8218 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 8219 VK = VK_RValue; 8220 8221 return Result; 8222} 8223 8224static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode( 8225 tok::TokenKind Kind) { 8226 BinaryOperatorKind Opc; 8227 switch (Kind) { 8228 default: llvm_unreachable("Unknown binop!"); 8229 case tok::periodstar: Opc = BO_PtrMemD; break; 8230 case tok::arrowstar: Opc = BO_PtrMemI; break; 8231 case tok::star: Opc = BO_Mul; break; 8232 case tok::slash: Opc = BO_Div; break; 8233 case tok::percent: Opc = BO_Rem; break; 8234 case tok::plus: Opc = BO_Add; break; 8235 case tok::minus: Opc = BO_Sub; break; 8236 case tok::lessless: Opc = BO_Shl; break; 8237 case tok::greatergreater: Opc = BO_Shr; break; 8238 case tok::lessequal: Opc = BO_LE; break; 8239 case tok::less: Opc = BO_LT; break; 8240 case tok::greaterequal: Opc = BO_GE; break; 8241 case tok::greater: Opc = BO_GT; break; 8242 case tok::exclaimequal: Opc = BO_NE; break; 8243 case tok::equalequal: Opc = BO_EQ; break; 8244 case tok::amp: Opc = BO_And; break; 8245 case tok::caret: Opc = BO_Xor; break; 8246 case tok::pipe: Opc = BO_Or; break; 8247 case tok::ampamp: Opc = BO_LAnd; break; 8248 case tok::pipepipe: Opc = BO_LOr; break; 8249 case tok::equal: Opc = BO_Assign; break; 8250 case tok::starequal: Opc = BO_MulAssign; break; 8251 case tok::slashequal: Opc = BO_DivAssign; break; 8252 case tok::percentequal: Opc = BO_RemAssign; break; 8253 case tok::plusequal: Opc = BO_AddAssign; break; 8254 case tok::minusequal: Opc = BO_SubAssign; break; 8255 case tok::lesslessequal: Opc = BO_ShlAssign; break; 8256 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 8257 case tok::ampequal: Opc = BO_AndAssign; break; 8258 case tok::caretequal: Opc = BO_XorAssign; break; 8259 case tok::pipeequal: Opc = BO_OrAssign; break; 8260 case tok::comma: Opc = BO_Comma; break; 8261 } 8262 return Opc; 8263} 8264 8265static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 8266 tok::TokenKind Kind) { 8267 UnaryOperatorKind Opc; 8268 switch (Kind) { 8269 default: llvm_unreachable("Unknown unary op!"); 8270 case tok::plusplus: Opc = UO_PreInc; break; 8271 case tok::minusminus: Opc = UO_PreDec; break; 8272 case tok::amp: Opc = UO_AddrOf; break; 8273 case tok::star: Opc = UO_Deref; break; 8274 case tok::plus: Opc = UO_Plus; break; 8275 case tok::minus: Opc = UO_Minus; break; 8276 case tok::tilde: Opc = UO_Not; break; 8277 case tok::exclaim: Opc = UO_LNot; break; 8278 case tok::kw___real: Opc = UO_Real; break; 8279 case tok::kw___imag: Opc = UO_Imag; break; 8280 case tok::kw___extension__: Opc = UO_Extension; break; 8281 } 8282 return Opc; 8283} 8284 8285/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 8286/// This warning is only emitted for builtin assignment operations. It is also 8287/// suppressed in the event of macro expansions. 8288static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 8289 SourceLocation OpLoc) { 8290 if (!S.ActiveTemplateInstantiations.empty()) 8291 return; 8292 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 8293 return; 8294 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 8295 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 8296 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 8297 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 8298 if (!LHSDeclRef || !RHSDeclRef || 8299 LHSDeclRef->getLocation().isMacroID() || 8300 RHSDeclRef->getLocation().isMacroID()) 8301 return; 8302 const ValueDecl *LHSDecl = 8303 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 8304 const ValueDecl *RHSDecl = 8305 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 8306 if (LHSDecl != RHSDecl) 8307 return; 8308 if (LHSDecl->getType().isVolatileQualified()) 8309 return; 8310 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 8311 if (RefTy->getPointeeType().isVolatileQualified()) 8312 return; 8313 8314 S.Diag(OpLoc, diag::warn_self_assignment) 8315 << LHSDeclRef->getType() 8316 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8317} 8318 8319/// CreateBuiltinBinOp - Creates a new built-in binary operation with 8320/// operator @p Opc at location @c TokLoc. This routine only supports 8321/// built-in operations; ActOnBinOp handles overloaded operators. 8322ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 8323 BinaryOperatorKind Opc, 8324 Expr *LHSExpr, Expr *RHSExpr) { 8325 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) { 8326 // The syntax only allows initializer lists on the RHS of assignment, 8327 // so we don't need to worry about accepting invalid code for 8328 // non-assignment operators. 8329 // C++11 5.17p9: 8330 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 8331 // of x = {} is x = T(). 8332 InitializationKind Kind = 8333 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 8334 InitializedEntity Entity = 8335 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 8336 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1); 8337 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 8338 if (Init.isInvalid()) 8339 return Init; 8340 RHSExpr = Init.take(); 8341 } 8342 8343 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 8344 QualType ResultTy; // Result type of the binary operator. 8345 // The following two variables are used for compound assignment operators 8346 QualType CompLHSTy; // Type of LHS after promotions for computation 8347 QualType CompResultTy; // Type of computation result 8348 ExprValueKind VK = VK_RValue; 8349 ExprObjectKind OK = OK_Ordinary; 8350 8351 switch (Opc) { 8352 case BO_Assign: 8353 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 8354 if (getLangOpts().CPlusPlus && 8355 LHS.get()->getObjectKind() != OK_ObjCProperty) { 8356 VK = LHS.get()->getValueKind(); 8357 OK = LHS.get()->getObjectKind(); 8358 } 8359 if (!ResultTy.isNull()) 8360 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 8361 break; 8362 case BO_PtrMemD: 8363 case BO_PtrMemI: 8364 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 8365 Opc == BO_PtrMemI); 8366 break; 8367 case BO_Mul: 8368 case BO_Div: 8369 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 8370 Opc == BO_Div); 8371 break; 8372 case BO_Rem: 8373 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 8374 break; 8375 case BO_Add: 8376 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 8377 break; 8378 case BO_Sub: 8379 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 8380 break; 8381 case BO_Shl: 8382 case BO_Shr: 8383 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 8384 break; 8385 case BO_LE: 8386 case BO_LT: 8387 case BO_GE: 8388 case BO_GT: 8389 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 8390 break; 8391 case BO_EQ: 8392 case BO_NE: 8393 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 8394 break; 8395 case BO_And: 8396 case BO_Xor: 8397 case BO_Or: 8398 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 8399 break; 8400 case BO_LAnd: 8401 case BO_LOr: 8402 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 8403 break; 8404 case BO_MulAssign: 8405 case BO_DivAssign: 8406 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 8407 Opc == BO_DivAssign); 8408 CompLHSTy = CompResultTy; 8409 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8410 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8411 break; 8412 case BO_RemAssign: 8413 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 8414 CompLHSTy = CompResultTy; 8415 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8416 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8417 break; 8418 case BO_AddAssign: 8419 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 8420 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8421 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8422 break; 8423 case BO_SubAssign: 8424 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 8425 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8426 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8427 break; 8428 case BO_ShlAssign: 8429 case BO_ShrAssign: 8430 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 8431 CompLHSTy = CompResultTy; 8432 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8433 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8434 break; 8435 case BO_AndAssign: 8436 case BO_XorAssign: 8437 case BO_OrAssign: 8438 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 8439 CompLHSTy = CompResultTy; 8440 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8441 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8442 break; 8443 case BO_Comma: 8444 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 8445 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 8446 VK = RHS.get()->getValueKind(); 8447 OK = RHS.get()->getObjectKind(); 8448 } 8449 break; 8450 } 8451 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 8452 return ExprError(); 8453 8454 // Check for array bounds violations for both sides of the BinaryOperator 8455 CheckArrayAccess(LHS.get()); 8456 CheckArrayAccess(RHS.get()); 8457 8458 if (CompResultTy.isNull()) 8459 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc, 8460 ResultTy, VK, OK, OpLoc, 8461 FPFeatures.fp_contract)); 8462 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 8463 OK_ObjCProperty) { 8464 VK = VK_LValue; 8465 OK = LHS.get()->getObjectKind(); 8466 } 8467 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc, 8468 ResultTy, VK, OK, CompLHSTy, 8469 CompResultTy, OpLoc, 8470 FPFeatures.fp_contract)); 8471} 8472 8473/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 8474/// operators are mixed in a way that suggests that the programmer forgot that 8475/// comparison operators have higher precedence. The most typical example of 8476/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 8477static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 8478 SourceLocation OpLoc, Expr *LHSExpr, 8479 Expr *RHSExpr) { 8480 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 8481 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 8482 8483 // Check that one of the sides is a comparison operator. 8484 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 8485 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 8486 if (!isLeftComp && !isRightComp) 8487 return; 8488 8489 // Bitwise operations are sometimes used as eager logical ops. 8490 // Don't diagnose this. 8491 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 8492 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 8493 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise)) 8494 return; 8495 8496 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 8497 OpLoc) 8498 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 8499 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 8500 SourceRange ParensRange = isLeftComp ? 8501 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 8502 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart()); 8503 8504 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 8505 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 8506 SuggestParentheses(Self, OpLoc, 8507 Self.PDiag(diag::note_precedence_silence) << OpStr, 8508 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 8509 SuggestParentheses(Self, OpLoc, 8510 Self.PDiag(diag::note_precedence_bitwise_first) 8511 << BinaryOperator::getOpcodeStr(Opc), 8512 ParensRange); 8513} 8514 8515/// \brief It accepts a '&' expr that is inside a '|' one. 8516/// Emit a diagnostic together with a fixit hint that wraps the '&' expression 8517/// in parentheses. 8518static void 8519EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 8520 BinaryOperator *Bop) { 8521 assert(Bop->getOpcode() == BO_And); 8522 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 8523 << Bop->getSourceRange() << OpLoc; 8524 SuggestParentheses(Self, Bop->getOperatorLoc(), 8525 Self.PDiag(diag::note_precedence_silence) 8526 << Bop->getOpcodeStr(), 8527 Bop->getSourceRange()); 8528} 8529 8530/// \brief It accepts a '&&' expr that is inside a '||' one. 8531/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 8532/// in parentheses. 8533static void 8534EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 8535 BinaryOperator *Bop) { 8536 assert(Bop->getOpcode() == BO_LAnd); 8537 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 8538 << Bop->getSourceRange() << OpLoc; 8539 SuggestParentheses(Self, Bop->getOperatorLoc(), 8540 Self.PDiag(diag::note_precedence_silence) 8541 << Bop->getOpcodeStr(), 8542 Bop->getSourceRange()); 8543} 8544 8545/// \brief Returns true if the given expression can be evaluated as a constant 8546/// 'true'. 8547static bool EvaluatesAsTrue(Sema &S, Expr *E) { 8548 bool Res; 8549 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 8550} 8551 8552/// \brief Returns true if the given expression can be evaluated as a constant 8553/// 'false'. 8554static bool EvaluatesAsFalse(Sema &S, Expr *E) { 8555 bool Res; 8556 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 8557} 8558 8559/// \brief Look for '&&' in the left hand of a '||' expr. 8560static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 8561 Expr *LHSExpr, Expr *RHSExpr) { 8562 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 8563 if (Bop->getOpcode() == BO_LAnd) { 8564 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 8565 if (EvaluatesAsFalse(S, RHSExpr)) 8566 return; 8567 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 8568 if (!EvaluatesAsTrue(S, Bop->getLHS())) 8569 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 8570 } else if (Bop->getOpcode() == BO_LOr) { 8571 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 8572 // If it's "a || b && 1 || c" we didn't warn earlier for 8573 // "a || b && 1", but warn now. 8574 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 8575 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 8576 } 8577 } 8578 } 8579} 8580 8581/// \brief Look for '&&' in the right hand of a '||' expr. 8582static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 8583 Expr *LHSExpr, Expr *RHSExpr) { 8584 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 8585 if (Bop->getOpcode() == BO_LAnd) { 8586 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 8587 if (EvaluatesAsFalse(S, LHSExpr)) 8588 return; 8589 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 8590 if (!EvaluatesAsTrue(S, Bop->getRHS())) 8591 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 8592 } 8593 } 8594} 8595 8596/// \brief Look for '&' in the left or right hand of a '|' expr. 8597static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 8598 Expr *OrArg) { 8599 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 8600 if (Bop->getOpcode() == BO_And) 8601 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 8602 } 8603} 8604 8605static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 8606 Expr *SubExpr, StringRef Shift) { 8607 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 8608 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 8609 StringRef Op = Bop->getOpcodeStr(); 8610 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 8611 << Bop->getSourceRange() << OpLoc << Shift << Op; 8612 SuggestParentheses(S, Bop->getOperatorLoc(), 8613 S.PDiag(diag::note_precedence_silence) << Op, 8614 Bop->getSourceRange()); 8615 } 8616 } 8617} 8618 8619/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 8620/// precedence. 8621static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 8622 SourceLocation OpLoc, Expr *LHSExpr, 8623 Expr *RHSExpr){ 8624 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 8625 if (BinaryOperator::isBitwiseOp(Opc)) 8626 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 8627 8628 // Diagnose "arg1 & arg2 | arg3" 8629 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 8630 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr); 8631 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr); 8632 } 8633 8634 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 8635 // We don't warn for 'assert(a || b && "bad")' since this is safe. 8636 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 8637 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 8638 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 8639 } 8640 8641 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 8642 || Opc == BO_Shr) { 8643 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 8644 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 8645 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 8646 } 8647} 8648 8649// Binary Operators. 'Tok' is the token for the operator. 8650ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 8651 tok::TokenKind Kind, 8652 Expr *LHSExpr, Expr *RHSExpr) { 8653 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 8654 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression"); 8655 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression"); 8656 8657 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 8658 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 8659 8660 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 8661} 8662 8663/// Build an overloaded binary operator expression in the given scope. 8664static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 8665 BinaryOperatorKind Opc, 8666 Expr *LHS, Expr *RHS) { 8667 // Find all of the overloaded operators visible from this 8668 // point. We perform both an operator-name lookup from the local 8669 // scope and an argument-dependent lookup based on the types of 8670 // the arguments. 8671 UnresolvedSet<16> Functions; 8672 OverloadedOperatorKind OverOp 8673 = BinaryOperator::getOverloadedOperator(Opc); 8674 if (Sc && OverOp != OO_None) 8675 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 8676 RHS->getType(), Functions); 8677 8678 // Build the (potentially-overloaded, potentially-dependent) 8679 // binary operation. 8680 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 8681} 8682 8683ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 8684 BinaryOperatorKind Opc, 8685 Expr *LHSExpr, Expr *RHSExpr) { 8686 // We want to end up calling one of checkPseudoObjectAssignment 8687 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 8688 // both expressions are overloadable or either is type-dependent), 8689 // or CreateBuiltinBinOp (in any other case). We also want to get 8690 // any placeholder types out of the way. 8691 8692 // Handle pseudo-objects in the LHS. 8693 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 8694 // Assignments with a pseudo-object l-value need special analysis. 8695 if (pty->getKind() == BuiltinType::PseudoObject && 8696 BinaryOperator::isAssignmentOp(Opc)) 8697 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 8698 8699 // Don't resolve overloads if the other type is overloadable. 8700 if (pty->getKind() == BuiltinType::Overload) { 8701 // We can't actually test that if we still have a placeholder, 8702 // though. Fortunately, none of the exceptions we see in that 8703 // code below are valid when the LHS is an overload set. Note 8704 // that an overload set can be dependently-typed, but it never 8705 // instantiates to having an overloadable type. 8706 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 8707 if (resolvedRHS.isInvalid()) return ExprError(); 8708 RHSExpr = resolvedRHS.take(); 8709 8710 if (RHSExpr->isTypeDependent() || 8711 RHSExpr->getType()->isOverloadableType()) 8712 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8713 } 8714 8715 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 8716 if (LHS.isInvalid()) return ExprError(); 8717 LHSExpr = LHS.take(); 8718 } 8719 8720 // Handle pseudo-objects in the RHS. 8721 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 8722 // An overload in the RHS can potentially be resolved by the type 8723 // being assigned to. 8724 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 8725 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 8726 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8727 8728 if (LHSExpr->getType()->isOverloadableType()) 8729 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8730 8731 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 8732 } 8733 8734 // Don't resolve overloads if the other type is overloadable. 8735 if (pty->getKind() == BuiltinType::Overload && 8736 LHSExpr->getType()->isOverloadableType()) 8737 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8738 8739 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 8740 if (!resolvedRHS.isUsable()) return ExprError(); 8741 RHSExpr = resolvedRHS.take(); 8742 } 8743 8744 if (getLangOpts().CPlusPlus) { 8745 // If either expression is type-dependent, always build an 8746 // overloaded op. 8747 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 8748 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8749 8750 // Otherwise, build an overloaded op if either expression has an 8751 // overloadable type. 8752 if (LHSExpr->getType()->isOverloadableType() || 8753 RHSExpr->getType()->isOverloadableType()) 8754 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 8755 } 8756 8757 // Build a built-in binary operation. 8758 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 8759} 8760 8761ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 8762 UnaryOperatorKind Opc, 8763 Expr *InputExpr) { 8764 ExprResult Input = Owned(InputExpr); 8765 ExprValueKind VK = VK_RValue; 8766 ExprObjectKind OK = OK_Ordinary; 8767 QualType resultType; 8768 switch (Opc) { 8769 case UO_PreInc: 8770 case UO_PreDec: 8771 case UO_PostInc: 8772 case UO_PostDec: 8773 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc, 8774 Opc == UO_PreInc || 8775 Opc == UO_PostInc, 8776 Opc == UO_PreInc || 8777 Opc == UO_PreDec); 8778 break; 8779 case UO_AddrOf: 8780 resultType = CheckAddressOfOperand(*this, Input, OpLoc); 8781 break; 8782 case UO_Deref: { 8783 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 8784 if (Input.isInvalid()) return ExprError(); 8785 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 8786 break; 8787 } 8788 case UO_Plus: 8789 case UO_Minus: 8790 Input = UsualUnaryConversions(Input.take()); 8791 if (Input.isInvalid()) return ExprError(); 8792 resultType = Input.get()->getType(); 8793 if (resultType->isDependentType()) 8794 break; 8795 if (resultType->isArithmeticType() || // C99 6.5.3.3p1 8796 resultType->isVectorType()) 8797 break; 8798 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7 8799 resultType->isEnumeralType()) 8800 break; 8801 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 8802 Opc == UO_Plus && 8803 resultType->isPointerType()) 8804 break; 8805 8806 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 8807 << resultType << Input.get()->getSourceRange()); 8808 8809 case UO_Not: // bitwise complement 8810 Input = UsualUnaryConversions(Input.take()); 8811 if (Input.isInvalid()) return ExprError(); 8812 resultType = Input.get()->getType(); 8813 if (resultType->isDependentType()) 8814 break; 8815 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 8816 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 8817 // C99 does not support '~' for complex conjugation. 8818 Diag(OpLoc, diag::ext_integer_complement_complex) 8819 << resultType << Input.get()->getSourceRange(); 8820 else if (resultType->hasIntegerRepresentation()) 8821 break; 8822 else { 8823 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 8824 << resultType << Input.get()->getSourceRange()); 8825 } 8826 break; 8827 8828 case UO_LNot: // logical negation 8829 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 8830 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 8831 if (Input.isInvalid()) return ExprError(); 8832 resultType = Input.get()->getType(); 8833 8834 // Though we still have to promote half FP to float... 8835 if (resultType->isHalfType()) { 8836 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take(); 8837 resultType = Context.FloatTy; 8838 } 8839 8840 if (resultType->isDependentType()) 8841 break; 8842 if (resultType->isScalarType()) { 8843 // C99 6.5.3.3p1: ok, fallthrough; 8844 if (Context.getLangOpts().CPlusPlus) { 8845 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 8846 // operand contextually converted to bool. 8847 Input = ImpCastExprToType(Input.take(), Context.BoolTy, 8848 ScalarTypeToBooleanCastKind(resultType)); 8849 } 8850 } else if (resultType->isExtVectorType()) { 8851 // Vector logical not returns the signed variant of the operand type. 8852 resultType = GetSignedVectorType(resultType); 8853 break; 8854 } else { 8855 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 8856 << resultType << Input.get()->getSourceRange()); 8857 } 8858 8859 // LNot always has type int. C99 6.5.3.3p5. 8860 // In C++, it's bool. C++ 5.3.1p8 8861 resultType = Context.getLogicalOperationType(); 8862 break; 8863 case UO_Real: 8864 case UO_Imag: 8865 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 8866 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 8867 // complex l-values to ordinary l-values and all other values to r-values. 8868 if (Input.isInvalid()) return ExprError(); 8869 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 8870 if (Input.get()->getValueKind() != VK_RValue && 8871 Input.get()->getObjectKind() == OK_Ordinary) 8872 VK = Input.get()->getValueKind(); 8873 } else if (!getLangOpts().CPlusPlus) { 8874 // In C, a volatile scalar is read by __imag. In C++, it is not. 8875 Input = DefaultLvalueConversion(Input.take()); 8876 } 8877 break; 8878 case UO_Extension: 8879 resultType = Input.get()->getType(); 8880 VK = Input.get()->getValueKind(); 8881 OK = Input.get()->getObjectKind(); 8882 break; 8883 } 8884 if (resultType.isNull() || Input.isInvalid()) 8885 return ExprError(); 8886 8887 // Check for array bounds violations in the operand of the UnaryOperator, 8888 // except for the '*' and '&' operators that have to be handled specially 8889 // by CheckArrayAccess (as there are special cases like &array[arraysize] 8890 // that are explicitly defined as valid by the standard). 8891 if (Opc != UO_AddrOf && Opc != UO_Deref) 8892 CheckArrayAccess(Input.get()); 8893 8894 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType, 8895 VK, OK, OpLoc)); 8896} 8897 8898/// \brief Determine whether the given expression is a qualified member 8899/// access expression, of a form that could be turned into a pointer to member 8900/// with the address-of operator. 8901static bool isQualifiedMemberAccess(Expr *E) { 8902 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 8903 if (!DRE->getQualifier()) 8904 return false; 8905 8906 ValueDecl *VD = DRE->getDecl(); 8907 if (!VD->isCXXClassMember()) 8908 return false; 8909 8910 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 8911 return true; 8912 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 8913 return Method->isInstance(); 8914 8915 return false; 8916 } 8917 8918 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 8919 if (!ULE->getQualifier()) 8920 return false; 8921 8922 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(), 8923 DEnd = ULE->decls_end(); 8924 D != DEnd; ++D) { 8925 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) { 8926 if (Method->isInstance()) 8927 return true; 8928 } else { 8929 // Overload set does not contain methods. 8930 break; 8931 } 8932 } 8933 8934 return false; 8935 } 8936 8937 return false; 8938} 8939 8940ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 8941 UnaryOperatorKind Opc, Expr *Input) { 8942 // First things first: handle placeholders so that the 8943 // overloaded-operator check considers the right type. 8944 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 8945 // Increment and decrement of pseudo-object references. 8946 if (pty->getKind() == BuiltinType::PseudoObject && 8947 UnaryOperator::isIncrementDecrementOp(Opc)) 8948 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 8949 8950 // extension is always a builtin operator. 8951 if (Opc == UO_Extension) 8952 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 8953 8954 // & gets special logic for several kinds of placeholder. 8955 // The builtin code knows what to do. 8956 if (Opc == UO_AddrOf && 8957 (pty->getKind() == BuiltinType::Overload || 8958 pty->getKind() == BuiltinType::UnknownAny || 8959 pty->getKind() == BuiltinType::BoundMember)) 8960 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 8961 8962 // Anything else needs to be handled now. 8963 ExprResult Result = CheckPlaceholderExpr(Input); 8964 if (Result.isInvalid()) return ExprError(); 8965 Input = Result.take(); 8966 } 8967 8968 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 8969 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 8970 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 8971 // Find all of the overloaded operators visible from this 8972 // point. We perform both an operator-name lookup from the local 8973 // scope and an argument-dependent lookup based on the types of 8974 // the arguments. 8975 UnresolvedSet<16> Functions; 8976 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 8977 if (S && OverOp != OO_None) 8978 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 8979 Functions); 8980 8981 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 8982 } 8983 8984 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 8985} 8986 8987// Unary Operators. 'Tok' is the token for the operator. 8988ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 8989 tok::TokenKind Op, Expr *Input) { 8990 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 8991} 8992 8993/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 8994ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 8995 LabelDecl *TheDecl) { 8996 TheDecl->setUsed(); 8997 // Create the AST node. The address of a label always has type 'void*'. 8998 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 8999 Context.getPointerType(Context.VoidTy))); 9000} 9001 9002/// Given the last statement in a statement-expression, check whether 9003/// the result is a producing expression (like a call to an 9004/// ns_returns_retained function) and, if so, rebuild it to hoist the 9005/// release out of the full-expression. Otherwise, return null. 9006/// Cannot fail. 9007static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 9008 // Should always be wrapped with one of these. 9009 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 9010 if (!cleanups) return 0; 9011 9012 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 9013 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 9014 return 0; 9015 9016 // Splice out the cast. This shouldn't modify any interesting 9017 // features of the statement. 9018 Expr *producer = cast->getSubExpr(); 9019 assert(producer->getType() == cast->getType()); 9020 assert(producer->getValueKind() == cast->getValueKind()); 9021 cleanups->setSubExpr(producer); 9022 return cleanups; 9023} 9024 9025void Sema::ActOnStartStmtExpr() { 9026 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 9027} 9028 9029void Sema::ActOnStmtExprError() { 9030 // Note that function is also called by TreeTransform when leaving a 9031 // StmtExpr scope without rebuilding anything. 9032 9033 DiscardCleanupsInEvaluationContext(); 9034 PopExpressionEvaluationContext(); 9035} 9036 9037ExprResult 9038Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 9039 SourceLocation RPLoc) { // "({..})" 9040 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 9041 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 9042 9043 if (hasAnyUnrecoverableErrorsInThisFunction()) 9044 DiscardCleanupsInEvaluationContext(); 9045 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 9046 PopExpressionEvaluationContext(); 9047 9048 bool isFileScope 9049 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0); 9050 if (isFileScope) 9051 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 9052 9053 // FIXME: there are a variety of strange constraints to enforce here, for 9054 // example, it is not possible to goto into a stmt expression apparently. 9055 // More semantic analysis is needed. 9056 9057 // If there are sub stmts in the compound stmt, take the type of the last one 9058 // as the type of the stmtexpr. 9059 QualType Ty = Context.VoidTy; 9060 bool StmtExprMayBindToTemp = false; 9061 if (!Compound->body_empty()) { 9062 Stmt *LastStmt = Compound->body_back(); 9063 LabelStmt *LastLabelStmt = 0; 9064 // If LastStmt is a label, skip down through into the body. 9065 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 9066 LastLabelStmt = Label; 9067 LastStmt = Label->getSubStmt(); 9068 } 9069 9070 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 9071 // Do function/array conversion on the last expression, but not 9072 // lvalue-to-rvalue. However, initialize an unqualified type. 9073 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 9074 if (LastExpr.isInvalid()) 9075 return ExprError(); 9076 Ty = LastExpr.get()->getType().getUnqualifiedType(); 9077 9078 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 9079 // In ARC, if the final expression ends in a consume, splice 9080 // the consume out and bind it later. In the alternate case 9081 // (when dealing with a retainable type), the result 9082 // initialization will create a produce. In both cases the 9083 // result will be +1, and we'll need to balance that out with 9084 // a bind. 9085 if (Expr *rebuiltLastStmt 9086 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 9087 LastExpr = rebuiltLastStmt; 9088 } else { 9089 LastExpr = PerformCopyInitialization( 9090 InitializedEntity::InitializeResult(LPLoc, 9091 Ty, 9092 false), 9093 SourceLocation(), 9094 LastExpr); 9095 } 9096 9097 if (LastExpr.isInvalid()) 9098 return ExprError(); 9099 if (LastExpr.get() != 0) { 9100 if (!LastLabelStmt) 9101 Compound->setLastStmt(LastExpr.take()); 9102 else 9103 LastLabelStmt->setSubStmt(LastExpr.take()); 9104 StmtExprMayBindToTemp = true; 9105 } 9106 } 9107 } 9108 } 9109 9110 // FIXME: Check that expression type is complete/non-abstract; statement 9111 // expressions are not lvalues. 9112 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 9113 if (StmtExprMayBindToTemp) 9114 return MaybeBindToTemporary(ResStmtExpr); 9115 return Owned(ResStmtExpr); 9116} 9117 9118ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 9119 TypeSourceInfo *TInfo, 9120 OffsetOfComponent *CompPtr, 9121 unsigned NumComponents, 9122 SourceLocation RParenLoc) { 9123 QualType ArgTy = TInfo->getType(); 9124 bool Dependent = ArgTy->isDependentType(); 9125 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 9126 9127 // We must have at least one component that refers to the type, and the first 9128 // one is known to be a field designator. Verify that the ArgTy represents 9129 // a struct/union/class. 9130 if (!Dependent && !ArgTy->isRecordType()) 9131 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 9132 << ArgTy << TypeRange); 9133 9134 // Type must be complete per C99 7.17p3 because a declaring a variable 9135 // with an incomplete type would be ill-formed. 9136 if (!Dependent 9137 && RequireCompleteType(BuiltinLoc, ArgTy, 9138 diag::err_offsetof_incomplete_type, TypeRange)) 9139 return ExprError(); 9140 9141 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 9142 // GCC extension, diagnose them. 9143 // FIXME: This diagnostic isn't actually visible because the location is in 9144 // a system header! 9145 if (NumComponents != 1) 9146 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 9147 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 9148 9149 bool DidWarnAboutNonPOD = false; 9150 QualType CurrentType = ArgTy; 9151 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 9152 SmallVector<OffsetOfNode, 4> Comps; 9153 SmallVector<Expr*, 4> Exprs; 9154 for (unsigned i = 0; i != NumComponents; ++i) { 9155 const OffsetOfComponent &OC = CompPtr[i]; 9156 if (OC.isBrackets) { 9157 // Offset of an array sub-field. TODO: Should we allow vector elements? 9158 if (!CurrentType->isDependentType()) { 9159 const ArrayType *AT = Context.getAsArrayType(CurrentType); 9160 if(!AT) 9161 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 9162 << CurrentType); 9163 CurrentType = AT->getElementType(); 9164 } else 9165 CurrentType = Context.DependentTy; 9166 9167 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 9168 if (IdxRval.isInvalid()) 9169 return ExprError(); 9170 Expr *Idx = IdxRval.take(); 9171 9172 // The expression must be an integral expression. 9173 // FIXME: An integral constant expression? 9174 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 9175 !Idx->getType()->isIntegerType()) 9176 return ExprError(Diag(Idx->getLocStart(), 9177 diag::err_typecheck_subscript_not_integer) 9178 << Idx->getSourceRange()); 9179 9180 // Record this array index. 9181 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 9182 Exprs.push_back(Idx); 9183 continue; 9184 } 9185 9186 // Offset of a field. 9187 if (CurrentType->isDependentType()) { 9188 // We have the offset of a field, but we can't look into the dependent 9189 // type. Just record the identifier of the field. 9190 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 9191 CurrentType = Context.DependentTy; 9192 continue; 9193 } 9194 9195 // We need to have a complete type to look into. 9196 if (RequireCompleteType(OC.LocStart, CurrentType, 9197 diag::err_offsetof_incomplete_type)) 9198 return ExprError(); 9199 9200 // Look for the designated field. 9201 const RecordType *RC = CurrentType->getAs<RecordType>(); 9202 if (!RC) 9203 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 9204 << CurrentType); 9205 RecordDecl *RD = RC->getDecl(); 9206 9207 // C++ [lib.support.types]p5: 9208 // The macro offsetof accepts a restricted set of type arguments in this 9209 // International Standard. type shall be a POD structure or a POD union 9210 // (clause 9). 9211 // C++11 [support.types]p4: 9212 // If type is not a standard-layout class (Clause 9), the results are 9213 // undefined. 9214 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 9215 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD(); 9216 unsigned DiagID = 9217 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type 9218 : diag::warn_offsetof_non_pod_type; 9219 9220 if (!IsSafe && !DidWarnAboutNonPOD && 9221 DiagRuntimeBehavior(BuiltinLoc, 0, 9222 PDiag(DiagID) 9223 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 9224 << CurrentType)) 9225 DidWarnAboutNonPOD = true; 9226 } 9227 9228 // Look for the field. 9229 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 9230 LookupQualifiedName(R, RD); 9231 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 9232 IndirectFieldDecl *IndirectMemberDecl = 0; 9233 if (!MemberDecl) { 9234 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 9235 MemberDecl = IndirectMemberDecl->getAnonField(); 9236 } 9237 9238 if (!MemberDecl) 9239 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 9240 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 9241 OC.LocEnd)); 9242 9243 // C99 7.17p3: 9244 // (If the specified member is a bit-field, the behavior is undefined.) 9245 // 9246 // We diagnose this as an error. 9247 if (MemberDecl->isBitField()) { 9248 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 9249 << MemberDecl->getDeclName() 9250 << SourceRange(BuiltinLoc, RParenLoc); 9251 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 9252 return ExprError(); 9253 } 9254 9255 RecordDecl *Parent = MemberDecl->getParent(); 9256 if (IndirectMemberDecl) 9257 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 9258 9259 // If the member was found in a base class, introduce OffsetOfNodes for 9260 // the base class indirections. 9261 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 9262 /*DetectVirtual=*/false); 9263 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 9264 CXXBasePath &Path = Paths.front(); 9265 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 9266 B != BEnd; ++B) 9267 Comps.push_back(OffsetOfNode(B->Base)); 9268 } 9269 9270 if (IndirectMemberDecl) { 9271 for (IndirectFieldDecl::chain_iterator FI = 9272 IndirectMemberDecl->chain_begin(), 9273 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) { 9274 assert(isa<FieldDecl>(*FI)); 9275 Comps.push_back(OffsetOfNode(OC.LocStart, 9276 cast<FieldDecl>(*FI), OC.LocEnd)); 9277 } 9278 } else 9279 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 9280 9281 CurrentType = MemberDecl->getType().getNonReferenceType(); 9282 } 9283 9284 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 9285 TInfo, Comps, Exprs, RParenLoc)); 9286} 9287 9288ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 9289 SourceLocation BuiltinLoc, 9290 SourceLocation TypeLoc, 9291 ParsedType ParsedArgTy, 9292 OffsetOfComponent *CompPtr, 9293 unsigned NumComponents, 9294 SourceLocation RParenLoc) { 9295 9296 TypeSourceInfo *ArgTInfo; 9297 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 9298 if (ArgTy.isNull()) 9299 return ExprError(); 9300 9301 if (!ArgTInfo) 9302 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 9303 9304 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 9305 RParenLoc); 9306} 9307 9308 9309ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 9310 Expr *CondExpr, 9311 Expr *LHSExpr, Expr *RHSExpr, 9312 SourceLocation RPLoc) { 9313 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 9314 9315 ExprValueKind VK = VK_RValue; 9316 ExprObjectKind OK = OK_Ordinary; 9317 QualType resType; 9318 bool ValueDependent = false; 9319 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 9320 resType = Context.DependentTy; 9321 ValueDependent = true; 9322 } else { 9323 // The conditional expression is required to be a constant expression. 9324 llvm::APSInt condEval(32); 9325 ExprResult CondICE 9326 = VerifyIntegerConstantExpression(CondExpr, &condEval, 9327 diag::err_typecheck_choose_expr_requires_constant, false); 9328 if (CondICE.isInvalid()) 9329 return ExprError(); 9330 CondExpr = CondICE.take(); 9331 9332 // If the condition is > zero, then the AST type is the same as the LSHExpr. 9333 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr; 9334 9335 resType = ActiveExpr->getType(); 9336 ValueDependent = ActiveExpr->isValueDependent(); 9337 VK = ActiveExpr->getValueKind(); 9338 OK = ActiveExpr->getObjectKind(); 9339 } 9340 9341 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 9342 resType, VK, OK, RPLoc, 9343 resType->isDependentType(), 9344 ValueDependent)); 9345} 9346 9347//===----------------------------------------------------------------------===// 9348// Clang Extensions. 9349//===----------------------------------------------------------------------===// 9350 9351/// ActOnBlockStart - This callback is invoked when a block literal is started. 9352void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 9353 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 9354 PushBlockScope(CurScope, Block); 9355 CurContext->addDecl(Block); 9356 if (CurScope) 9357 PushDeclContext(CurScope, Block); 9358 else 9359 CurContext = Block; 9360 9361 getCurBlock()->HasImplicitReturnType = true; 9362 9363 // Enter a new evaluation context to insulate the block from any 9364 // cleanups from the enclosing full-expression. 9365 PushExpressionEvaluationContext(PotentiallyEvaluated); 9366} 9367 9368void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 9369 Scope *CurScope) { 9370 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!"); 9371 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 9372 BlockScopeInfo *CurBlock = getCurBlock(); 9373 9374 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 9375 QualType T = Sig->getType(); 9376 9377 // FIXME: We should allow unexpanded parameter packs here, but that would, 9378 // in turn, make the block expression contain unexpanded parameter packs. 9379 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 9380 // Drop the parameters. 9381 FunctionProtoType::ExtProtoInfo EPI; 9382 EPI.HasTrailingReturn = false; 9383 EPI.TypeQuals |= DeclSpec::TQ_const; 9384 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0, 9385 EPI); 9386 Sig = Context.getTrivialTypeSourceInfo(T); 9387 } 9388 9389 // GetTypeForDeclarator always produces a function type for a block 9390 // literal signature. Furthermore, it is always a FunctionProtoType 9391 // unless the function was written with a typedef. 9392 assert(T->isFunctionType() && 9393 "GetTypeForDeclarator made a non-function block signature"); 9394 9395 // Look for an explicit signature in that function type. 9396 FunctionProtoTypeLoc ExplicitSignature; 9397 9398 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 9399 if (isa<FunctionProtoTypeLoc>(tmp)) { 9400 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp); 9401 9402 // Check whether that explicit signature was synthesized by 9403 // GetTypeForDeclarator. If so, don't save that as part of the 9404 // written signature. 9405 if (ExplicitSignature.getLocalRangeBegin() == 9406 ExplicitSignature.getLocalRangeEnd()) { 9407 // This would be much cheaper if we stored TypeLocs instead of 9408 // TypeSourceInfos. 9409 TypeLoc Result = ExplicitSignature.getResultLoc(); 9410 unsigned Size = Result.getFullDataSize(); 9411 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 9412 Sig->getTypeLoc().initializeFullCopy(Result, Size); 9413 9414 ExplicitSignature = FunctionProtoTypeLoc(); 9415 } 9416 } 9417 9418 CurBlock->TheDecl->setSignatureAsWritten(Sig); 9419 CurBlock->FunctionType = T; 9420 9421 const FunctionType *Fn = T->getAs<FunctionType>(); 9422 QualType RetTy = Fn->getResultType(); 9423 bool isVariadic = 9424 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 9425 9426 CurBlock->TheDecl->setIsVariadic(isVariadic); 9427 9428 // Don't allow returning a objc interface by value. 9429 if (RetTy->isObjCObjectType()) { 9430 Diag(ParamInfo.getLocStart(), 9431 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy; 9432 return; 9433 } 9434 9435 // Context.DependentTy is used as a placeholder for a missing block 9436 // return type. TODO: what should we do with declarators like: 9437 // ^ * { ... } 9438 // If the answer is "apply template argument deduction".... 9439 if (RetTy != Context.DependentTy) { 9440 CurBlock->ReturnType = RetTy; 9441 CurBlock->TheDecl->setBlockMissingReturnType(false); 9442 CurBlock->HasImplicitReturnType = false; 9443 } 9444 9445 // Push block parameters from the declarator if we had them. 9446 SmallVector<ParmVarDecl*, 8> Params; 9447 if (ExplicitSignature) { 9448 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) { 9449 ParmVarDecl *Param = ExplicitSignature.getArg(I); 9450 if (Param->getIdentifier() == 0 && 9451 !Param->isImplicit() && 9452 !Param->isInvalidDecl() && 9453 !getLangOpts().CPlusPlus) 9454 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 9455 Params.push_back(Param); 9456 } 9457 9458 // Fake up parameter variables if we have a typedef, like 9459 // ^ fntype { ... } 9460 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 9461 for (FunctionProtoType::arg_type_iterator 9462 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) { 9463 ParmVarDecl *Param = 9464 BuildParmVarDeclForTypedef(CurBlock->TheDecl, 9465 ParamInfo.getLocStart(), 9466 *I); 9467 Params.push_back(Param); 9468 } 9469 } 9470 9471 // Set the parameters on the block decl. 9472 if (!Params.empty()) { 9473 CurBlock->TheDecl->setParams(Params); 9474 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 9475 CurBlock->TheDecl->param_end(), 9476 /*CheckParameterNames=*/false); 9477 } 9478 9479 // Finally we can process decl attributes. 9480 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 9481 9482 // Put the parameter variables in scope. We can bail out immediately 9483 // if we don't have any. 9484 if (Params.empty()) 9485 return; 9486 9487 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 9488 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) { 9489 (*AI)->setOwningFunction(CurBlock->TheDecl); 9490 9491 // If this has an identifier, add it to the scope stack. 9492 if ((*AI)->getIdentifier()) { 9493 CheckShadow(CurBlock->TheScope, *AI); 9494 9495 PushOnScopeChains(*AI, CurBlock->TheScope); 9496 } 9497 } 9498} 9499 9500/// ActOnBlockError - If there is an error parsing a block, this callback 9501/// is invoked to pop the information about the block from the action impl. 9502void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 9503 // Leave the expression-evaluation context. 9504 DiscardCleanupsInEvaluationContext(); 9505 PopExpressionEvaluationContext(); 9506 9507 // Pop off CurBlock, handle nested blocks. 9508 PopDeclContext(); 9509 PopFunctionScopeInfo(); 9510} 9511 9512/// ActOnBlockStmtExpr - This is called when the body of a block statement 9513/// literal was successfully completed. ^(int x){...} 9514ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 9515 Stmt *Body, Scope *CurScope) { 9516 // If blocks are disabled, emit an error. 9517 if (!LangOpts.Blocks) 9518 Diag(CaretLoc, diag::err_blocks_disable); 9519 9520 // Leave the expression-evaluation context. 9521 if (hasAnyUnrecoverableErrorsInThisFunction()) 9522 DiscardCleanupsInEvaluationContext(); 9523 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 9524 PopExpressionEvaluationContext(); 9525 9526 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 9527 9528 if (BSI->HasImplicitReturnType) 9529 deduceClosureReturnType(*BSI); 9530 9531 PopDeclContext(); 9532 9533 QualType RetTy = Context.VoidTy; 9534 if (!BSI->ReturnType.isNull()) 9535 RetTy = BSI->ReturnType; 9536 9537 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>(); 9538 QualType BlockTy; 9539 9540 // Set the captured variables on the block. 9541 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 9542 SmallVector<BlockDecl::Capture, 4> Captures; 9543 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) { 9544 CapturingScopeInfo::Capture &Cap = BSI->Captures[i]; 9545 if (Cap.isThisCapture()) 9546 continue; 9547 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 9548 Cap.isNested(), Cap.getCopyExpr()); 9549 Captures.push_back(NewCap); 9550 } 9551 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(), 9552 BSI->CXXThisCaptureIndex != 0); 9553 9554 // If the user wrote a function type in some form, try to use that. 9555 if (!BSI->FunctionType.isNull()) { 9556 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 9557 9558 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 9559 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 9560 9561 // Turn protoless block types into nullary block types. 9562 if (isa<FunctionNoProtoType>(FTy)) { 9563 FunctionProtoType::ExtProtoInfo EPI; 9564 EPI.ExtInfo = Ext; 9565 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI); 9566 9567 // Otherwise, if we don't need to change anything about the function type, 9568 // preserve its sugar structure. 9569 } else if (FTy->getResultType() == RetTy && 9570 (!NoReturn || FTy->getNoReturnAttr())) { 9571 BlockTy = BSI->FunctionType; 9572 9573 // Otherwise, make the minimal modifications to the function type. 9574 } else { 9575 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 9576 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9577 EPI.TypeQuals = 0; // FIXME: silently? 9578 EPI.ExtInfo = Ext; 9579 BlockTy = Context.getFunctionType(RetTy, 9580 FPT->arg_type_begin(), 9581 FPT->getNumArgs(), 9582 EPI); 9583 } 9584 9585 // If we don't have a function type, just build one from nothing. 9586 } else { 9587 FunctionProtoType::ExtProtoInfo EPI; 9588 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 9589 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI); 9590 } 9591 9592 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 9593 BSI->TheDecl->param_end()); 9594 BlockTy = Context.getBlockPointerType(BlockTy); 9595 9596 // If needed, diagnose invalid gotos and switches in the block. 9597 if (getCurFunction()->NeedsScopeChecking() && 9598 !hasAnyUnrecoverableErrorsInThisFunction() && 9599 !PP.isCodeCompletionEnabled()) 9600 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 9601 9602 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 9603 9604 // Try to apply the named return value optimization. We have to check again 9605 // if we can do this, though, because blocks keep return statements around 9606 // to deduce an implicit return type. 9607 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 9608 !BSI->TheDecl->isDependentContext()) 9609 computeNRVO(Body, getCurBlock()); 9610 9611 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 9612 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy(); 9613 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 9614 9615 // If the block isn't obviously global, i.e. it captures anything at 9616 // all, then we need to do a few things in the surrounding context: 9617 if (Result->getBlockDecl()->hasCaptures()) { 9618 // First, this expression has a new cleanup object. 9619 ExprCleanupObjects.push_back(Result->getBlockDecl()); 9620 ExprNeedsCleanups = true; 9621 9622 // It also gets a branch-protected scope if any of the captured 9623 // variables needs destruction. 9624 for (BlockDecl::capture_const_iterator 9625 ci = Result->getBlockDecl()->capture_begin(), 9626 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) { 9627 const VarDecl *var = ci->getVariable(); 9628 if (var->getType().isDestructedType() != QualType::DK_none) { 9629 getCurFunction()->setHasBranchProtectedScope(); 9630 break; 9631 } 9632 } 9633 } 9634 9635 return Owned(Result); 9636} 9637 9638ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 9639 Expr *E, ParsedType Ty, 9640 SourceLocation RPLoc) { 9641 TypeSourceInfo *TInfo; 9642 GetTypeFromParser(Ty, &TInfo); 9643 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 9644} 9645 9646ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 9647 Expr *E, TypeSourceInfo *TInfo, 9648 SourceLocation RPLoc) { 9649 Expr *OrigExpr = E; 9650 9651 // Get the va_list type 9652 QualType VaListType = Context.getBuiltinVaListType(); 9653 if (VaListType->isArrayType()) { 9654 // Deal with implicit array decay; for example, on x86-64, 9655 // va_list is an array, but it's supposed to decay to 9656 // a pointer for va_arg. 9657 VaListType = Context.getArrayDecayedType(VaListType); 9658 // Make sure the input expression also decays appropriately. 9659 ExprResult Result = UsualUnaryConversions(E); 9660 if (Result.isInvalid()) 9661 return ExprError(); 9662 E = Result.take(); 9663 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 9664 // If va_list is a record type and we are compiling in C++ mode, 9665 // check the argument using reference binding. 9666 InitializedEntity Entity 9667 = InitializedEntity::InitializeParameter(Context, 9668 Context.getLValueReferenceType(VaListType), false); 9669 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 9670 if (Init.isInvalid()) 9671 return ExprError(); 9672 E = Init.takeAs<Expr>(); 9673 } else { 9674 // Otherwise, the va_list argument must be an l-value because 9675 // it is modified by va_arg. 9676 if (!E->isTypeDependent() && 9677 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 9678 return ExprError(); 9679 } 9680 9681 if (!E->isTypeDependent() && 9682 !Context.hasSameType(VaListType, E->getType())) { 9683 return ExprError(Diag(E->getLocStart(), 9684 diag::err_first_argument_to_va_arg_not_of_type_va_list) 9685 << OrigExpr->getType() << E->getSourceRange()); 9686 } 9687 9688 if (!TInfo->getType()->isDependentType()) { 9689 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 9690 diag::err_second_parameter_to_va_arg_incomplete, 9691 TInfo->getTypeLoc())) 9692 return ExprError(); 9693 9694 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 9695 TInfo->getType(), 9696 diag::err_second_parameter_to_va_arg_abstract, 9697 TInfo->getTypeLoc())) 9698 return ExprError(); 9699 9700 if (!TInfo->getType().isPODType(Context)) { 9701 Diag(TInfo->getTypeLoc().getBeginLoc(), 9702 TInfo->getType()->isObjCLifetimeType() 9703 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 9704 : diag::warn_second_parameter_to_va_arg_not_pod) 9705 << TInfo->getType() 9706 << TInfo->getTypeLoc().getSourceRange(); 9707 } 9708 9709 // Check for va_arg where arguments of the given type will be promoted 9710 // (i.e. this va_arg is guaranteed to have undefined behavior). 9711 QualType PromoteType; 9712 if (TInfo->getType()->isPromotableIntegerType()) { 9713 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 9714 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 9715 PromoteType = QualType(); 9716 } 9717 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 9718 PromoteType = Context.DoubleTy; 9719 if (!PromoteType.isNull()) 9720 Diag(TInfo->getTypeLoc().getBeginLoc(), 9721 diag::warn_second_parameter_to_va_arg_never_compatible) 9722 << TInfo->getType() 9723 << PromoteType 9724 << TInfo->getTypeLoc().getSourceRange(); 9725 } 9726 9727 QualType T = TInfo->getType().getNonLValueExprType(Context); 9728 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T)); 9729} 9730 9731ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 9732 // The type of __null will be int or long, depending on the size of 9733 // pointers on the target. 9734 QualType Ty; 9735 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 9736 if (pw == Context.getTargetInfo().getIntWidth()) 9737 Ty = Context.IntTy; 9738 else if (pw == Context.getTargetInfo().getLongWidth()) 9739 Ty = Context.LongTy; 9740 else if (pw == Context.getTargetInfo().getLongLongWidth()) 9741 Ty = Context.LongLongTy; 9742 else { 9743 llvm_unreachable("I don't know size of pointer!"); 9744 } 9745 9746 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); 9747} 9748 9749static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType, 9750 Expr *SrcExpr, FixItHint &Hint) { 9751 if (!SemaRef.getLangOpts().ObjC1) 9752 return; 9753 9754 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 9755 if (!PT) 9756 return; 9757 9758 // Check if the destination is of type 'id'. 9759 if (!PT->isObjCIdType()) { 9760 // Check if the destination is the 'NSString' interface. 9761 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 9762 if (!ID || !ID->getIdentifier()->isStr("NSString")) 9763 return; 9764 } 9765 9766 // Ignore any parens, implicit casts (should only be 9767 // array-to-pointer decays), and not-so-opaque values. The last is 9768 // important for making this trigger for property assignments. 9769 SrcExpr = SrcExpr->IgnoreParenImpCasts(); 9770 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 9771 if (OV->getSourceExpr()) 9772 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 9773 9774 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 9775 if (!SL || !SL->isAscii()) 9776 return; 9777 9778 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@"); 9779} 9780 9781bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 9782 SourceLocation Loc, 9783 QualType DstType, QualType SrcType, 9784 Expr *SrcExpr, AssignmentAction Action, 9785 bool *Complained) { 9786 if (Complained) 9787 *Complained = false; 9788 9789 // Decode the result (notice that AST's are still created for extensions). 9790 bool CheckInferredResultType = false; 9791 bool isInvalid = false; 9792 unsigned DiagKind = 0; 9793 FixItHint Hint; 9794 ConversionFixItGenerator ConvHints; 9795 bool MayHaveConvFixit = false; 9796 bool MayHaveFunctionDiff = false; 9797 9798 switch (ConvTy) { 9799 case Compatible: 9800 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 9801 return false; 9802 9803 case PointerToInt: 9804 DiagKind = diag::ext_typecheck_convert_pointer_int; 9805 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 9806 MayHaveConvFixit = true; 9807 break; 9808 case IntToPointer: 9809 DiagKind = diag::ext_typecheck_convert_int_pointer; 9810 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 9811 MayHaveConvFixit = true; 9812 break; 9813 case IncompatiblePointer: 9814 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint); 9815 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 9816 CheckInferredResultType = DstType->isObjCObjectPointerType() && 9817 SrcType->isObjCObjectPointerType(); 9818 if (Hint.isNull() && !CheckInferredResultType) { 9819 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 9820 } 9821 MayHaveConvFixit = true; 9822 break; 9823 case IncompatiblePointerSign: 9824 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 9825 break; 9826 case FunctionVoidPointer: 9827 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 9828 break; 9829 case IncompatiblePointerDiscardsQualifiers: { 9830 // Perform array-to-pointer decay if necessary. 9831 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 9832 9833 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 9834 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 9835 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 9836 DiagKind = diag::err_typecheck_incompatible_address_space; 9837 break; 9838 9839 9840 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 9841 DiagKind = diag::err_typecheck_incompatible_ownership; 9842 break; 9843 } 9844 9845 llvm_unreachable("unknown error case for discarding qualifiers!"); 9846 // fallthrough 9847 } 9848 case CompatiblePointerDiscardsQualifiers: 9849 // If the qualifiers lost were because we were applying the 9850 // (deprecated) C++ conversion from a string literal to a char* 9851 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 9852 // Ideally, this check would be performed in 9853 // checkPointerTypesForAssignment. However, that would require a 9854 // bit of refactoring (so that the second argument is an 9855 // expression, rather than a type), which should be done as part 9856 // of a larger effort to fix checkPointerTypesForAssignment for 9857 // C++ semantics. 9858 if (getLangOpts().CPlusPlus && 9859 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 9860 return false; 9861 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 9862 break; 9863 case IncompatibleNestedPointerQualifiers: 9864 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 9865 break; 9866 case IntToBlockPointer: 9867 DiagKind = diag::err_int_to_block_pointer; 9868 break; 9869 case IncompatibleBlockPointer: 9870 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 9871 break; 9872 case IncompatibleObjCQualifiedId: 9873 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 9874 // it can give a more specific diagnostic. 9875 DiagKind = diag::warn_incompatible_qualified_id; 9876 break; 9877 case IncompatibleVectors: 9878 DiagKind = diag::warn_incompatible_vectors; 9879 break; 9880 case IncompatibleObjCWeakRef: 9881 DiagKind = diag::err_arc_weak_unavailable_assign; 9882 break; 9883 case Incompatible: 9884 DiagKind = diag::err_typecheck_convert_incompatible; 9885 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 9886 MayHaveConvFixit = true; 9887 isInvalid = true; 9888 MayHaveFunctionDiff = true; 9889 break; 9890 } 9891 9892 QualType FirstType, SecondType; 9893 switch (Action) { 9894 case AA_Assigning: 9895 case AA_Initializing: 9896 // The destination type comes first. 9897 FirstType = DstType; 9898 SecondType = SrcType; 9899 break; 9900 9901 case AA_Returning: 9902 case AA_Passing: 9903 case AA_Converting: 9904 case AA_Sending: 9905 case AA_Casting: 9906 // The source type comes first. 9907 FirstType = SrcType; 9908 SecondType = DstType; 9909 break; 9910 } 9911 9912 PartialDiagnostic FDiag = PDiag(DiagKind); 9913 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 9914 9915 // If we can fix the conversion, suggest the FixIts. 9916 assert(ConvHints.isNull() || Hint.isNull()); 9917 if (!ConvHints.isNull()) { 9918 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(), 9919 HE = ConvHints.Hints.end(); HI != HE; ++HI) 9920 FDiag << *HI; 9921 } else { 9922 FDiag << Hint; 9923 } 9924 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 9925 9926 if (MayHaveFunctionDiff) 9927 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 9928 9929 Diag(Loc, FDiag); 9930 9931 if (SecondType == Context.OverloadTy) 9932 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 9933 FirstType); 9934 9935 if (CheckInferredResultType) 9936 EmitRelatedResultTypeNote(SrcExpr); 9937 9938 if (Complained) 9939 *Complained = true; 9940 return isInvalid; 9941} 9942 9943ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 9944 llvm::APSInt *Result) { 9945 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 9946 public: 9947 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 9948 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 9949 } 9950 } Diagnoser; 9951 9952 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 9953} 9954 9955ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 9956 llvm::APSInt *Result, 9957 unsigned DiagID, 9958 bool AllowFold) { 9959 class IDDiagnoser : public VerifyICEDiagnoser { 9960 unsigned DiagID; 9961 9962 public: 9963 IDDiagnoser(unsigned DiagID) 9964 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 9965 9966 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 9967 S.Diag(Loc, DiagID) << SR; 9968 } 9969 } Diagnoser(DiagID); 9970 9971 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 9972} 9973 9974void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 9975 SourceRange SR) { 9976 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 9977} 9978 9979ExprResult 9980Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 9981 VerifyICEDiagnoser &Diagnoser, 9982 bool AllowFold) { 9983 SourceLocation DiagLoc = E->getLocStart(); 9984 9985 if (getLangOpts().CPlusPlus0x) { 9986 // C++11 [expr.const]p5: 9987 // If an expression of literal class type is used in a context where an 9988 // integral constant expression is required, then that class type shall 9989 // have a single non-explicit conversion function to an integral or 9990 // unscoped enumeration type 9991 ExprResult Converted; 9992 if (!Diagnoser.Suppress) { 9993 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 9994 public: 9995 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { } 9996 9997 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 9998 QualType T) { 9999 return S.Diag(Loc, diag::err_ice_not_integral) << T; 10000 } 10001 10002 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, 10003 SourceLocation Loc, 10004 QualType T) { 10005 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 10006 } 10007 10008 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, 10009 SourceLocation Loc, 10010 QualType T, 10011 QualType ConvTy) { 10012 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 10013 } 10014 10015 virtual DiagnosticBuilder noteExplicitConv(Sema &S, 10016 CXXConversionDecl *Conv, 10017 QualType ConvTy) { 10018 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10019 << ConvTy->isEnumeralType() << ConvTy; 10020 } 10021 10022 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 10023 QualType T) { 10024 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 10025 } 10026 10027 virtual DiagnosticBuilder noteAmbiguous(Sema &S, 10028 CXXConversionDecl *Conv, 10029 QualType ConvTy) { 10030 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10031 << ConvTy->isEnumeralType() << ConvTy; 10032 } 10033 10034 virtual DiagnosticBuilder diagnoseConversion(Sema &S, 10035 SourceLocation Loc, 10036 QualType T, 10037 QualType ConvTy) { 10038 return DiagnosticBuilder::getEmpty(); 10039 } 10040 } ConvertDiagnoser; 10041 10042 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E, 10043 ConvertDiagnoser, 10044 /*AllowScopedEnumerations*/ false); 10045 } else { 10046 // The caller wants to silently enquire whether this is an ICE. Don't 10047 // produce any diagnostics if it isn't. 10048 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser { 10049 public: 10050 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { } 10051 10052 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 10053 QualType T) { 10054 return DiagnosticBuilder::getEmpty(); 10055 } 10056 10057 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, 10058 SourceLocation Loc, 10059 QualType T) { 10060 return DiagnosticBuilder::getEmpty(); 10061 } 10062 10063 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, 10064 SourceLocation Loc, 10065 QualType T, 10066 QualType ConvTy) { 10067 return DiagnosticBuilder::getEmpty(); 10068 } 10069 10070 virtual DiagnosticBuilder noteExplicitConv(Sema &S, 10071 CXXConversionDecl *Conv, 10072 QualType ConvTy) { 10073 return DiagnosticBuilder::getEmpty(); 10074 } 10075 10076 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 10077 QualType T) { 10078 return DiagnosticBuilder::getEmpty(); 10079 } 10080 10081 virtual DiagnosticBuilder noteAmbiguous(Sema &S, 10082 CXXConversionDecl *Conv, 10083 QualType ConvTy) { 10084 return DiagnosticBuilder::getEmpty(); 10085 } 10086 10087 virtual DiagnosticBuilder diagnoseConversion(Sema &S, 10088 SourceLocation Loc, 10089 QualType T, 10090 QualType ConvTy) { 10091 return DiagnosticBuilder::getEmpty(); 10092 } 10093 } ConvertDiagnoser; 10094 10095 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E, 10096 ConvertDiagnoser, false); 10097 } 10098 if (Converted.isInvalid()) 10099 return Converted; 10100 E = Converted.take(); 10101 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 10102 return ExprError(); 10103 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 10104 // An ICE must be of integral or unscoped enumeration type. 10105 if (!Diagnoser.Suppress) 10106 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 10107 return ExprError(); 10108 } 10109 10110 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 10111 // in the non-ICE case. 10112 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) { 10113 if (Result) 10114 *Result = E->EvaluateKnownConstInt(Context); 10115 return Owned(E); 10116 } 10117 10118 Expr::EvalResult EvalResult; 10119 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 10120 EvalResult.Diag = &Notes; 10121 10122 // Try to evaluate the expression, and produce diagnostics explaining why it's 10123 // not a constant expression as a side-effect. 10124 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 10125 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 10126 10127 // In C++11, we can rely on diagnostics being produced for any expression 10128 // which is not a constant expression. If no diagnostics were produced, then 10129 // this is a constant expression. 10130 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) { 10131 if (Result) 10132 *Result = EvalResult.Val.getInt(); 10133 return Owned(E); 10134 } 10135 10136 // If our only note is the usual "invalid subexpression" note, just point 10137 // the caret at its location rather than producing an essentially 10138 // redundant note. 10139 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 10140 diag::note_invalid_subexpr_in_const_expr) { 10141 DiagLoc = Notes[0].first; 10142 Notes.clear(); 10143 } 10144 10145 if (!Folded || !AllowFold) { 10146 if (!Diagnoser.Suppress) { 10147 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 10148 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10149 Diag(Notes[I].first, Notes[I].second); 10150 } 10151 10152 return ExprError(); 10153 } 10154 10155 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 10156 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10157 Diag(Notes[I].first, Notes[I].second); 10158 10159 if (Result) 10160 *Result = EvalResult.Val.getInt(); 10161 return Owned(E); 10162} 10163 10164namespace { 10165 // Handle the case where we conclude a expression which we speculatively 10166 // considered to be unevaluated is actually evaluated. 10167 class TransformToPE : public TreeTransform<TransformToPE> { 10168 typedef TreeTransform<TransformToPE> BaseTransform; 10169 10170 public: 10171 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 10172 10173 // Make sure we redo semantic analysis 10174 bool AlwaysRebuild() { return true; } 10175 10176 // Make sure we handle LabelStmts correctly. 10177 // FIXME: This does the right thing, but maybe we need a more general 10178 // fix to TreeTransform? 10179 StmtResult TransformLabelStmt(LabelStmt *S) { 10180 S->getDecl()->setStmt(0); 10181 return BaseTransform::TransformLabelStmt(S); 10182 } 10183 10184 // We need to special-case DeclRefExprs referring to FieldDecls which 10185 // are not part of a member pointer formation; normal TreeTransforming 10186 // doesn't catch this case because of the way we represent them in the AST. 10187 // FIXME: This is a bit ugly; is it really the best way to handle this 10188 // case? 10189 // 10190 // Error on DeclRefExprs referring to FieldDecls. 10191 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 10192 if (isa<FieldDecl>(E->getDecl()) && 10193 !SemaRef.isUnevaluatedContext()) 10194 return SemaRef.Diag(E->getLocation(), 10195 diag::err_invalid_non_static_member_use) 10196 << E->getDecl() << E->getSourceRange(); 10197 10198 return BaseTransform::TransformDeclRefExpr(E); 10199 } 10200 10201 // Exception: filter out member pointer formation 10202 ExprResult TransformUnaryOperator(UnaryOperator *E) { 10203 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 10204 return E; 10205 10206 return BaseTransform::TransformUnaryOperator(E); 10207 } 10208 10209 ExprResult TransformLambdaExpr(LambdaExpr *E) { 10210 // Lambdas never need to be transformed. 10211 return E; 10212 } 10213 }; 10214} 10215 10216ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 10217 assert(ExprEvalContexts.back().Context == Unevaluated && 10218 "Should only transform unevaluated expressions"); 10219 ExprEvalContexts.back().Context = 10220 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 10221 if (ExprEvalContexts.back().Context == Unevaluated) 10222 return E; 10223 return TransformToPE(*this).TransformExpr(E); 10224} 10225 10226void 10227Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 10228 Decl *LambdaContextDecl, 10229 bool IsDecltype) { 10230 ExprEvalContexts.push_back( 10231 ExpressionEvaluationContextRecord(NewContext, 10232 ExprCleanupObjects.size(), 10233 ExprNeedsCleanups, 10234 LambdaContextDecl, 10235 IsDecltype)); 10236 ExprNeedsCleanups = false; 10237 if (!MaybeODRUseExprs.empty()) 10238 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 10239} 10240 10241void 10242Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 10243 ReuseLambdaContextDecl_t, 10244 bool IsDecltype) { 10245 Decl *LambdaContextDecl = ExprEvalContexts.back().LambdaContextDecl; 10246 PushExpressionEvaluationContext(NewContext, LambdaContextDecl, IsDecltype); 10247} 10248 10249void Sema::PopExpressionEvaluationContext() { 10250 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 10251 10252 if (!Rec.Lambdas.empty()) { 10253 if (Rec.Context == Unevaluated) { 10254 // C++11 [expr.prim.lambda]p2: 10255 // A lambda-expression shall not appear in an unevaluated operand 10256 // (Clause 5). 10257 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) 10258 Diag(Rec.Lambdas[I]->getLocStart(), 10259 diag::err_lambda_unevaluated_operand); 10260 } else { 10261 // Mark the capture expressions odr-used. This was deferred 10262 // during lambda expression creation. 10263 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) { 10264 LambdaExpr *Lambda = Rec.Lambdas[I]; 10265 for (LambdaExpr::capture_init_iterator 10266 C = Lambda->capture_init_begin(), 10267 CEnd = Lambda->capture_init_end(); 10268 C != CEnd; ++C) { 10269 MarkDeclarationsReferencedInExpr(*C); 10270 } 10271 } 10272 } 10273 } 10274 10275 // When are coming out of an unevaluated context, clear out any 10276 // temporaries that we may have created as part of the evaluation of 10277 // the expression in that context: they aren't relevant because they 10278 // will never be constructed. 10279 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) { 10280 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 10281 ExprCleanupObjects.end()); 10282 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 10283 CleanupVarDeclMarking(); 10284 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 10285 // Otherwise, merge the contexts together. 10286 } else { 10287 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 10288 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 10289 Rec.SavedMaybeODRUseExprs.end()); 10290 } 10291 10292 // Pop the current expression evaluation context off the stack. 10293 ExprEvalContexts.pop_back(); 10294} 10295 10296void Sema::DiscardCleanupsInEvaluationContext() { 10297 ExprCleanupObjects.erase( 10298 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 10299 ExprCleanupObjects.end()); 10300 ExprNeedsCleanups = false; 10301 MaybeODRUseExprs.clear(); 10302} 10303 10304ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 10305 if (!E->getType()->isVariablyModifiedType()) 10306 return E; 10307 return TransformToPotentiallyEvaluated(E); 10308} 10309 10310static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 10311 // Do not mark anything as "used" within a dependent context; wait for 10312 // an instantiation. 10313 if (SemaRef.CurContext->isDependentContext()) 10314 return false; 10315 10316 switch (SemaRef.ExprEvalContexts.back().Context) { 10317 case Sema::Unevaluated: 10318 // We are in an expression that is not potentially evaluated; do nothing. 10319 // (Depending on how you read the standard, we actually do need to do 10320 // something here for null pointer constants, but the standard's 10321 // definition of a null pointer constant is completely crazy.) 10322 return false; 10323 10324 case Sema::ConstantEvaluated: 10325 case Sema::PotentiallyEvaluated: 10326 // We are in a potentially evaluated expression (or a constant-expression 10327 // in C++03); we need to do implicit template instantiation, implicitly 10328 // define class members, and mark most declarations as used. 10329 return true; 10330 10331 case Sema::PotentiallyEvaluatedIfUsed: 10332 // Referenced declarations will only be used if the construct in the 10333 // containing expression is used. 10334 return false; 10335 } 10336 llvm_unreachable("Invalid context"); 10337} 10338 10339/// \brief Mark a function referenced, and check whether it is odr-used 10340/// (C++ [basic.def.odr]p2, C99 6.9p3) 10341void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) { 10342 assert(Func && "No function?"); 10343 10344 Func->setReferenced(); 10345 10346 // C++11 [basic.def.odr]p3: 10347 // A function whose name appears as a potentially-evaluated expression is 10348 // odr-used if it is the unique lookup result or the selected member of a 10349 // set of overloaded functions [...]. 10350 // 10351 // We (incorrectly) mark overload resolution as an unevaluated context, so we 10352 // can just check that here. Skip the rest of this function if we've already 10353 // marked the function as used. 10354 if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) { 10355 // C++11 [temp.inst]p3: 10356 // Unless a function template specialization has been explicitly 10357 // instantiated or explicitly specialized, the function template 10358 // specialization is implicitly instantiated when the specialization is 10359 // referenced in a context that requires a function definition to exist. 10360 // 10361 // We consider constexpr function templates to be referenced in a context 10362 // that requires a definition to exist whenever they are referenced. 10363 // 10364 // FIXME: This instantiates constexpr functions too frequently. If this is 10365 // really an unevaluated context (and we're not just in the definition of a 10366 // function template or overload resolution or other cases which we 10367 // incorrectly consider to be unevaluated contexts), and we're not in a 10368 // subexpression which we actually need to evaluate (for instance, a 10369 // template argument, array bound or an expression in a braced-init-list), 10370 // we are not permitted to instantiate this constexpr function definition. 10371 // 10372 // FIXME: This also implicitly defines special members too frequently. They 10373 // are only supposed to be implicitly defined if they are odr-used, but they 10374 // are not odr-used from constant expressions in unevaluated contexts. 10375 // However, they cannot be referenced if they are deleted, and they are 10376 // deleted whenever the implicit definition of the special member would 10377 // fail. 10378 if (!Func->isConstexpr() || Func->getBody()) 10379 return; 10380 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 10381 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 10382 return; 10383 } 10384 10385 // Note that this declaration has been used. 10386 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 10387 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 10388 if (Constructor->isDefaultConstructor()) { 10389 if (Constructor->isTrivial()) 10390 return; 10391 if (!Constructor->isUsed(false)) 10392 DefineImplicitDefaultConstructor(Loc, Constructor); 10393 } else if (Constructor->isCopyConstructor()) { 10394 if (!Constructor->isUsed(false)) 10395 DefineImplicitCopyConstructor(Loc, Constructor); 10396 } else if (Constructor->isMoveConstructor()) { 10397 if (!Constructor->isUsed(false)) 10398 DefineImplicitMoveConstructor(Loc, Constructor); 10399 } 10400 } 10401 10402 MarkVTableUsed(Loc, Constructor->getParent()); 10403 } else if (CXXDestructorDecl *Destructor = 10404 dyn_cast<CXXDestructorDecl>(Func)) { 10405 if (Destructor->isDefaulted() && !Destructor->isDeleted() && 10406 !Destructor->isUsed(false)) 10407 DefineImplicitDestructor(Loc, Destructor); 10408 if (Destructor->isVirtual()) 10409 MarkVTableUsed(Loc, Destructor->getParent()); 10410 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 10411 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() && 10412 MethodDecl->isOverloadedOperator() && 10413 MethodDecl->getOverloadedOperator() == OO_Equal) { 10414 if (!MethodDecl->isUsed(false)) { 10415 if (MethodDecl->isCopyAssignmentOperator()) 10416 DefineImplicitCopyAssignment(Loc, MethodDecl); 10417 else 10418 DefineImplicitMoveAssignment(Loc, MethodDecl); 10419 } 10420 } else if (isa<CXXConversionDecl>(MethodDecl) && 10421 MethodDecl->getParent()->isLambda()) { 10422 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl); 10423 if (Conversion->isLambdaToBlockPointerConversion()) 10424 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 10425 else 10426 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 10427 } else if (MethodDecl->isVirtual()) 10428 MarkVTableUsed(Loc, MethodDecl->getParent()); 10429 } 10430 10431 // Recursive functions should be marked when used from another function. 10432 // FIXME: Is this really right? 10433 if (CurContext == Func) return; 10434 10435 // Resolve the exception specification for any function which is 10436 // used: CodeGen will need it. 10437 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 10438 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 10439 ResolveExceptionSpec(Loc, FPT); 10440 10441 // Implicit instantiation of function templates and member functions of 10442 // class templates. 10443 if (Func->isImplicitlyInstantiable()) { 10444 bool AlreadyInstantiated = false; 10445 SourceLocation PointOfInstantiation = Loc; 10446 if (FunctionTemplateSpecializationInfo *SpecInfo 10447 = Func->getTemplateSpecializationInfo()) { 10448 if (SpecInfo->getPointOfInstantiation().isInvalid()) 10449 SpecInfo->setPointOfInstantiation(Loc); 10450 else if (SpecInfo->getTemplateSpecializationKind() 10451 == TSK_ImplicitInstantiation) { 10452 AlreadyInstantiated = true; 10453 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 10454 } 10455 } else if (MemberSpecializationInfo *MSInfo 10456 = Func->getMemberSpecializationInfo()) { 10457 if (MSInfo->getPointOfInstantiation().isInvalid()) 10458 MSInfo->setPointOfInstantiation(Loc); 10459 else if (MSInfo->getTemplateSpecializationKind() 10460 == TSK_ImplicitInstantiation) { 10461 AlreadyInstantiated = true; 10462 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 10463 } 10464 } 10465 10466 if (!AlreadyInstantiated || Func->isConstexpr()) { 10467 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 10468 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass()) 10469 PendingLocalImplicitInstantiations.push_back( 10470 std::make_pair(Func, PointOfInstantiation)); 10471 else if (Func->isConstexpr()) 10472 // Do not defer instantiations of constexpr functions, to avoid the 10473 // expression evaluator needing to call back into Sema if it sees a 10474 // call to such a function. 10475 InstantiateFunctionDefinition(PointOfInstantiation, Func); 10476 else { 10477 PendingInstantiations.push_back(std::make_pair(Func, 10478 PointOfInstantiation)); 10479 // Notify the consumer that a function was implicitly instantiated. 10480 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 10481 } 10482 } 10483 } else { 10484 // Walk redefinitions, as some of them may be instantiable. 10485 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()), 10486 e(Func->redecls_end()); i != e; ++i) { 10487 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 10488 MarkFunctionReferenced(Loc, *i); 10489 } 10490 } 10491 10492 // Keep track of used but undefined functions. 10493 if (!Func->isPure() && !Func->hasBody() && 10494 Func->getLinkage() != ExternalLinkage) { 10495 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()]; 10496 if (old.isInvalid()) old = Loc; 10497 } 10498 10499 Func->setUsed(true); 10500} 10501 10502static void 10503diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 10504 VarDecl *var, DeclContext *DC) { 10505 DeclContext *VarDC = var->getDeclContext(); 10506 10507 // If the parameter still belongs to the translation unit, then 10508 // we're actually just using one parameter in the declaration of 10509 // the next. 10510 if (isa<ParmVarDecl>(var) && 10511 isa<TranslationUnitDecl>(VarDC)) 10512 return; 10513 10514 // For C code, don't diagnose about capture if we're not actually in code 10515 // right now; it's impossible to write a non-constant expression outside of 10516 // function context, so we'll get other (more useful) diagnostics later. 10517 // 10518 // For C++, things get a bit more nasty... it would be nice to suppress this 10519 // diagnostic for certain cases like using a local variable in an array bound 10520 // for a member of a local class, but the correct predicate is not obvious. 10521 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 10522 return; 10523 10524 if (isa<CXXMethodDecl>(VarDC) && 10525 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 10526 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 10527 << var->getIdentifier(); 10528 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 10529 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 10530 << var->getIdentifier() << fn->getDeclName(); 10531 } else if (isa<BlockDecl>(VarDC)) { 10532 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 10533 << var->getIdentifier(); 10534 } else { 10535 // FIXME: Is there any other context where a local variable can be 10536 // declared? 10537 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 10538 << var->getIdentifier(); 10539 } 10540 10541 S.Diag(var->getLocation(), diag::note_local_variable_declared_here) 10542 << var->getIdentifier(); 10543 10544 // FIXME: Add additional diagnostic info about class etc. which prevents 10545 // capture. 10546} 10547 10548/// \brief Capture the given variable in the given lambda expression. 10549static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI, 10550 VarDecl *Var, QualType FieldType, 10551 QualType DeclRefType, 10552 SourceLocation Loc, 10553 bool RefersToEnclosingLocal) { 10554 CXXRecordDecl *Lambda = LSI->Lambda; 10555 10556 // Build the non-static data member. 10557 FieldDecl *Field 10558 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType, 10559 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 10560 0, false, ICIS_NoInit); 10561 Field->setImplicit(true); 10562 Field->setAccess(AS_private); 10563 Lambda->addDecl(Field); 10564 10565 // C++11 [expr.prim.lambda]p21: 10566 // When the lambda-expression is evaluated, the entities that 10567 // are captured by copy are used to direct-initialize each 10568 // corresponding non-static data member of the resulting closure 10569 // object. (For array members, the array elements are 10570 // direct-initialized in increasing subscript order.) These 10571 // initializations are performed in the (unspecified) order in 10572 // which the non-static data members are declared. 10573 10574 // Introduce a new evaluation context for the initialization, so 10575 // that temporaries introduced as part of the capture are retained 10576 // to be re-"exported" from the lambda expression itself. 10577 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 10578 10579 // C++ [expr.prim.labda]p12: 10580 // An entity captured by a lambda-expression is odr-used (3.2) in 10581 // the scope containing the lambda-expression. 10582 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 10583 DeclRefType, VK_LValue, Loc); 10584 Var->setReferenced(true); 10585 Var->setUsed(true); 10586 10587 // When the field has array type, create index variables for each 10588 // dimension of the array. We use these index variables to subscript 10589 // the source array, and other clients (e.g., CodeGen) will perform 10590 // the necessary iteration with these index variables. 10591 SmallVector<VarDecl *, 4> IndexVariables; 10592 QualType BaseType = FieldType; 10593 QualType SizeType = S.Context.getSizeType(); 10594 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size()); 10595 while (const ConstantArrayType *Array 10596 = S.Context.getAsConstantArrayType(BaseType)) { 10597 // Create the iteration variable for this array index. 10598 IdentifierInfo *IterationVarName = 0; 10599 { 10600 SmallString<8> Str; 10601 llvm::raw_svector_ostream OS(Str); 10602 OS << "__i" << IndexVariables.size(); 10603 IterationVarName = &S.Context.Idents.get(OS.str()); 10604 } 10605 VarDecl *IterationVar 10606 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 10607 IterationVarName, SizeType, 10608 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 10609 SC_None, SC_None); 10610 IndexVariables.push_back(IterationVar); 10611 LSI->ArrayIndexVars.push_back(IterationVar); 10612 10613 // Create a reference to the iteration variable. 10614 ExprResult IterationVarRef 10615 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 10616 assert(!IterationVarRef.isInvalid() && 10617 "Reference to invented variable cannot fail!"); 10618 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take()); 10619 assert(!IterationVarRef.isInvalid() && 10620 "Conversion of invented variable cannot fail!"); 10621 10622 // Subscript the array with this iteration variable. 10623 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr( 10624 Ref, Loc, IterationVarRef.take(), Loc); 10625 if (Subscript.isInvalid()) { 10626 S.CleanupVarDeclMarking(); 10627 S.DiscardCleanupsInEvaluationContext(); 10628 S.PopExpressionEvaluationContext(); 10629 return ExprError(); 10630 } 10631 10632 Ref = Subscript.take(); 10633 BaseType = Array->getElementType(); 10634 } 10635 10636 // Construct the entity that we will be initializing. For an array, this 10637 // will be first element in the array, which may require several levels 10638 // of array-subscript entities. 10639 SmallVector<InitializedEntity, 4> Entities; 10640 Entities.reserve(1 + IndexVariables.size()); 10641 Entities.push_back( 10642 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc)); 10643 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 10644 Entities.push_back(InitializedEntity::InitializeElement(S.Context, 10645 0, 10646 Entities.back())); 10647 10648 InitializationKind InitKind 10649 = InitializationKind::CreateDirect(Loc, Loc, Loc); 10650 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1); 10651 ExprResult Result(true); 10652 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1)) 10653 Result = Init.Perform(S, Entities.back(), InitKind, Ref); 10654 10655 // If this initialization requires any cleanups (e.g., due to a 10656 // default argument to a copy constructor), note that for the 10657 // lambda. 10658 if (S.ExprNeedsCleanups) 10659 LSI->ExprNeedsCleanups = true; 10660 10661 // Exit the expression evaluation context used for the capture. 10662 S.CleanupVarDeclMarking(); 10663 S.DiscardCleanupsInEvaluationContext(); 10664 S.PopExpressionEvaluationContext(); 10665 return Result; 10666} 10667 10668bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 10669 TryCaptureKind Kind, SourceLocation EllipsisLoc, 10670 bool BuildAndDiagnose, 10671 QualType &CaptureType, 10672 QualType &DeclRefType) { 10673 bool Nested = false; 10674 10675 DeclContext *DC = CurContext; 10676 if (Var->getDeclContext() == DC) return true; 10677 if (!Var->hasLocalStorage()) return true; 10678 10679 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 10680 10681 // Walk up the stack to determine whether we can capture the variable, 10682 // performing the "simple" checks that don't depend on type. We stop when 10683 // we've either hit the declared scope of the variable or find an existing 10684 // capture of that variable. 10685 CaptureType = Var->getType(); 10686 DeclRefType = CaptureType.getNonReferenceType(); 10687 bool Explicit = (Kind != TryCapture_Implicit); 10688 unsigned FunctionScopesIndex = FunctionScopes.size() - 1; 10689 do { 10690 // Only block literals and lambda expressions can capture; other 10691 // scopes don't work. 10692 DeclContext *ParentDC; 10693 if (isa<BlockDecl>(DC)) 10694 ParentDC = DC->getParent(); 10695 else if (isa<CXXMethodDecl>(DC) && 10696 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call && 10697 cast<CXXRecordDecl>(DC->getParent())->isLambda()) 10698 ParentDC = DC->getParent()->getParent(); 10699 else { 10700 if (BuildAndDiagnose) 10701 diagnoseUncapturableValueReference(*this, Loc, Var, DC); 10702 return true; 10703 } 10704 10705 CapturingScopeInfo *CSI = 10706 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]); 10707 10708 // Check whether we've already captured it. 10709 if (CSI->CaptureMap.count(Var)) { 10710 // If we found a capture, any subcaptures are nested. 10711 Nested = true; 10712 10713 // Retrieve the capture type for this variable. 10714 CaptureType = CSI->getCapture(Var).getCaptureType(); 10715 10716 // Compute the type of an expression that refers to this variable. 10717 DeclRefType = CaptureType.getNonReferenceType(); 10718 10719 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 10720 if (Cap.isCopyCapture() && 10721 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable)) 10722 DeclRefType.addConst(); 10723 break; 10724 } 10725 10726 bool IsBlock = isa<BlockScopeInfo>(CSI); 10727 bool IsLambda = !IsBlock; 10728 10729 // Lambdas are not allowed to capture unnamed variables 10730 // (e.g. anonymous unions). 10731 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 10732 // assuming that's the intent. 10733 if (IsLambda && !Var->getDeclName()) { 10734 if (BuildAndDiagnose) { 10735 Diag(Loc, diag::err_lambda_capture_anonymous_var); 10736 Diag(Var->getLocation(), diag::note_declared_at); 10737 } 10738 return true; 10739 } 10740 10741 // Prohibit variably-modified types; they're difficult to deal with. 10742 if (Var->getType()->isVariablyModifiedType()) { 10743 if (BuildAndDiagnose) { 10744 if (IsBlock) 10745 Diag(Loc, diag::err_ref_vm_type); 10746 else 10747 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName(); 10748 Diag(Var->getLocation(), diag::note_previous_decl) 10749 << Var->getDeclName(); 10750 } 10751 return true; 10752 } 10753 10754 // Lambdas are not allowed to capture __block variables; they don't 10755 // support the expected semantics. 10756 if (IsLambda && HasBlocksAttr) { 10757 if (BuildAndDiagnose) { 10758 Diag(Loc, diag::err_lambda_capture_block) 10759 << Var->getDeclName(); 10760 Diag(Var->getLocation(), diag::note_previous_decl) 10761 << Var->getDeclName(); 10762 } 10763 return true; 10764 } 10765 10766 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 10767 // No capture-default 10768 if (BuildAndDiagnose) { 10769 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName(); 10770 Diag(Var->getLocation(), diag::note_previous_decl) 10771 << Var->getDeclName(); 10772 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 10773 diag::note_lambda_decl); 10774 } 10775 return true; 10776 } 10777 10778 FunctionScopesIndex--; 10779 DC = ParentDC; 10780 Explicit = false; 10781 } while (!Var->getDeclContext()->Equals(DC)); 10782 10783 // Walk back down the scope stack, computing the type of the capture at 10784 // each step, checking type-specific requirements, and adding captures if 10785 // requested. 10786 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N; 10787 ++I) { 10788 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 10789 10790 // Compute the type of the capture and of a reference to the capture within 10791 // this scope. 10792 if (isa<BlockScopeInfo>(CSI)) { 10793 Expr *CopyExpr = 0; 10794 bool ByRef = false; 10795 10796 // Blocks are not allowed to capture arrays. 10797 if (CaptureType->isArrayType()) { 10798 if (BuildAndDiagnose) { 10799 Diag(Loc, diag::err_ref_array_type); 10800 Diag(Var->getLocation(), diag::note_previous_decl) 10801 << Var->getDeclName(); 10802 } 10803 return true; 10804 } 10805 10806 // Forbid the block-capture of autoreleasing variables. 10807 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 10808 if (BuildAndDiagnose) { 10809 Diag(Loc, diag::err_arc_autoreleasing_capture) 10810 << /*block*/ 0; 10811 Diag(Var->getLocation(), diag::note_previous_decl) 10812 << Var->getDeclName(); 10813 } 10814 return true; 10815 } 10816 10817 if (HasBlocksAttr || CaptureType->isReferenceType()) { 10818 // Block capture by reference does not change the capture or 10819 // declaration reference types. 10820 ByRef = true; 10821 } else { 10822 // Block capture by copy introduces 'const'. 10823 CaptureType = CaptureType.getNonReferenceType().withConst(); 10824 DeclRefType = CaptureType; 10825 10826 if (getLangOpts().CPlusPlus && BuildAndDiagnose) { 10827 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 10828 // The capture logic needs the destructor, so make sure we mark it. 10829 // Usually this is unnecessary because most local variables have 10830 // their destructors marked at declaration time, but parameters are 10831 // an exception because it's technically only the call site that 10832 // actually requires the destructor. 10833 if (isa<ParmVarDecl>(Var)) 10834 FinalizeVarWithDestructor(Var, Record); 10835 10836 // According to the blocks spec, the capture of a variable from 10837 // the stack requires a const copy constructor. This is not true 10838 // of the copy/move done to move a __block variable to the heap. 10839 Expr *DeclRef = new (Context) DeclRefExpr(Var, false, 10840 DeclRefType.withConst(), 10841 VK_LValue, Loc); 10842 ExprResult Result 10843 = PerformCopyInitialization( 10844 InitializedEntity::InitializeBlock(Var->getLocation(), 10845 CaptureType, false), 10846 Loc, Owned(DeclRef)); 10847 10848 // Build a full-expression copy expression if initialization 10849 // succeeded and used a non-trivial constructor. Recover from 10850 // errors by pretending that the copy isn't necessary. 10851 if (!Result.isInvalid() && 10852 !cast<CXXConstructExpr>(Result.get())->getConstructor() 10853 ->isTrivial()) { 10854 Result = MaybeCreateExprWithCleanups(Result); 10855 CopyExpr = Result.take(); 10856 } 10857 } 10858 } 10859 } 10860 10861 // Actually capture the variable. 10862 if (BuildAndDiagnose) 10863 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 10864 SourceLocation(), CaptureType, CopyExpr); 10865 Nested = true; 10866 continue; 10867 } 10868 10869 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 10870 10871 // Determine whether we are capturing by reference or by value. 10872 bool ByRef = false; 10873 if (I == N - 1 && Kind != TryCapture_Implicit) { 10874 ByRef = (Kind == TryCapture_ExplicitByRef); 10875 } else { 10876 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 10877 } 10878 10879 // Compute the type of the field that will capture this variable. 10880 if (ByRef) { 10881 // C++11 [expr.prim.lambda]p15: 10882 // An entity is captured by reference if it is implicitly or 10883 // explicitly captured but not captured by copy. It is 10884 // unspecified whether additional unnamed non-static data 10885 // members are declared in the closure type for entities 10886 // captured by reference. 10887 // 10888 // FIXME: It is not clear whether we want to build an lvalue reference 10889 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 10890 // to do the former, while EDG does the latter. Core issue 1249 will 10891 // clarify, but for now we follow GCC because it's a more permissive and 10892 // easily defensible position. 10893 CaptureType = Context.getLValueReferenceType(DeclRefType); 10894 } else { 10895 // C++11 [expr.prim.lambda]p14: 10896 // For each entity captured by copy, an unnamed non-static 10897 // data member is declared in the closure type. The 10898 // declaration order of these members is unspecified. The type 10899 // of such a data member is the type of the corresponding 10900 // captured entity if the entity is not a reference to an 10901 // object, or the referenced type otherwise. [Note: If the 10902 // captured entity is a reference to a function, the 10903 // corresponding data member is also a reference to a 10904 // function. - end note ] 10905 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 10906 if (!RefType->getPointeeType()->isFunctionType()) 10907 CaptureType = RefType->getPointeeType(); 10908 } 10909 10910 // Forbid the lambda copy-capture of autoreleasing variables. 10911 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 10912 if (BuildAndDiagnose) { 10913 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 10914 Diag(Var->getLocation(), diag::note_previous_decl) 10915 << Var->getDeclName(); 10916 } 10917 return true; 10918 } 10919 } 10920 10921 // Capture this variable in the lambda. 10922 Expr *CopyExpr = 0; 10923 if (BuildAndDiagnose) { 10924 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType, 10925 DeclRefType, Loc, 10926 I == N-1); 10927 if (!Result.isInvalid()) 10928 CopyExpr = Result.take(); 10929 } 10930 10931 // Compute the type of a reference to this captured variable. 10932 if (ByRef) 10933 DeclRefType = CaptureType.getNonReferenceType(); 10934 else { 10935 // C++ [expr.prim.lambda]p5: 10936 // The closure type for a lambda-expression has a public inline 10937 // function call operator [...]. This function call operator is 10938 // declared const (9.3.1) if and only if the lambda-expression’s 10939 // parameter-declaration-clause is not followed by mutable. 10940 DeclRefType = CaptureType.getNonReferenceType(); 10941 if (!LSI->Mutable && !CaptureType->isReferenceType()) 10942 DeclRefType.addConst(); 10943 } 10944 10945 // Add the capture. 10946 if (BuildAndDiagnose) 10947 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc, 10948 EllipsisLoc, CaptureType, CopyExpr); 10949 Nested = true; 10950 } 10951 10952 return false; 10953} 10954 10955bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 10956 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 10957 QualType CaptureType; 10958 QualType DeclRefType; 10959 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 10960 /*BuildAndDiagnose=*/true, CaptureType, 10961 DeclRefType); 10962} 10963 10964QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 10965 QualType CaptureType; 10966 QualType DeclRefType; 10967 10968 // Determine whether we can capture this variable. 10969 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 10970 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType)) 10971 return QualType(); 10972 10973 return DeclRefType; 10974} 10975 10976static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var, 10977 SourceLocation Loc) { 10978 // Keep track of used but undefined variables. 10979 // FIXME: We shouldn't suppress this warning for static data members. 10980 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 10981 Var->getLinkage() != ExternalLinkage && 10982 !(Var->isStaticDataMember() && Var->hasInit())) { 10983 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()]; 10984 if (old.isInvalid()) old = Loc; 10985 } 10986 10987 SemaRef.tryCaptureVariable(Var, Loc); 10988 10989 Var->setUsed(true); 10990} 10991 10992void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 10993 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 10994 // an object that satisfies the requirements for appearing in a 10995 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 10996 // is immediately applied." This function handles the lvalue-to-rvalue 10997 // conversion part. 10998 MaybeODRUseExprs.erase(E->IgnoreParens()); 10999} 11000 11001ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 11002 if (!Res.isUsable()) 11003 return Res; 11004 11005 // If a constant-expression is a reference to a variable where we delay 11006 // deciding whether it is an odr-use, just assume we will apply the 11007 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 11008 // (a non-type template argument), we have special handling anyway. 11009 UpdateMarkingForLValueToRValue(Res.get()); 11010 return Res; 11011} 11012 11013void Sema::CleanupVarDeclMarking() { 11014 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(), 11015 e = MaybeODRUseExprs.end(); 11016 i != e; ++i) { 11017 VarDecl *Var; 11018 SourceLocation Loc; 11019 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) { 11020 Var = cast<VarDecl>(DRE->getDecl()); 11021 Loc = DRE->getLocation(); 11022 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) { 11023 Var = cast<VarDecl>(ME->getMemberDecl()); 11024 Loc = ME->getMemberLoc(); 11025 } else { 11026 llvm_unreachable("Unexpcted expression"); 11027 } 11028 11029 MarkVarDeclODRUsed(*this, Var, Loc); 11030 } 11031 11032 MaybeODRUseExprs.clear(); 11033} 11034 11035// Mark a VarDecl referenced, and perform the necessary handling to compute 11036// odr-uses. 11037static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 11038 VarDecl *Var, Expr *E) { 11039 Var->setReferenced(); 11040 11041 if (!IsPotentiallyEvaluatedContext(SemaRef)) 11042 return; 11043 11044 // Implicit instantiation of static data members of class templates. 11045 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) { 11046 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 11047 assert(MSInfo && "Missing member specialization information?"); 11048 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid(); 11049 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && 11050 (!AlreadyInstantiated || 11051 Var->isUsableInConstantExpressions(SemaRef.Context))) { 11052 if (!AlreadyInstantiated) { 11053 // This is a modification of an existing AST node. Notify listeners. 11054 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 11055 L->StaticDataMemberInstantiated(Var); 11056 MSInfo->setPointOfInstantiation(Loc); 11057 } 11058 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation(); 11059 if (Var->isUsableInConstantExpressions(SemaRef.Context)) 11060 // Do not defer instantiations of variables which could be used in a 11061 // constant expression. 11062 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var); 11063 else 11064 SemaRef.PendingInstantiations.push_back( 11065 std::make_pair(Var, PointOfInstantiation)); 11066 } 11067 } 11068 11069 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 11070 // the requirements for appearing in a constant expression (5.19) and, if 11071 // it is an object, the lvalue-to-rvalue conversion (4.1) 11072 // is immediately applied." We check the first part here, and 11073 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 11074 // Note that we use the C++11 definition everywhere because nothing in 11075 // C++03 depends on whether we get the C++03 version correct. The second 11076 // part does not apply to references, since they are not objects. 11077 const VarDecl *DefVD; 11078 if (E && !isa<ParmVarDecl>(Var) && 11079 Var->isUsableInConstantExpressions(SemaRef.Context) && 11080 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) { 11081 if (!Var->getType()->isReferenceType()) 11082 SemaRef.MaybeODRUseExprs.insert(E); 11083 } else 11084 MarkVarDeclODRUsed(SemaRef, Var, Loc); 11085} 11086 11087/// \brief Mark a variable referenced, and check whether it is odr-used 11088/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 11089/// used directly for normal expressions referring to VarDecl. 11090void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 11091 DoMarkVarDeclReferenced(*this, Loc, Var, 0); 11092} 11093 11094static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 11095 Decl *D, Expr *E) { 11096 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 11097 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 11098 return; 11099 } 11100 11101 SemaRef.MarkAnyDeclReferenced(Loc, D); 11102 11103 // If this is a call to a method via a cast, also mark the method in the 11104 // derived class used in case codegen can devirtualize the call. 11105 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 11106 if (!ME) 11107 return; 11108 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 11109 if (!MD) 11110 return; 11111 const Expr *Base = ME->getBase(); 11112 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 11113 if (!MostDerivedClassDecl) 11114 return; 11115 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 11116 if (!DM) 11117 return; 11118 SemaRef.MarkAnyDeclReferenced(Loc, DM); 11119} 11120 11121/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 11122void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 11123 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E); 11124} 11125 11126/// \brief Perform reference-marking and odr-use handling for a MemberExpr. 11127void Sema::MarkMemberReferenced(MemberExpr *E) { 11128 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E); 11129} 11130 11131/// \brief Perform marking for a reference to an arbitrary declaration. It 11132/// marks the declaration referenced, and performs odr-use checking for functions 11133/// and variables. This method should not be used when building an normal 11134/// expression which refers to a variable. 11135void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) { 11136 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 11137 MarkVariableReferenced(Loc, VD); 11138 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 11139 MarkFunctionReferenced(Loc, FD); 11140 else 11141 D->setReferenced(); 11142} 11143 11144namespace { 11145 // Mark all of the declarations referenced 11146 // FIXME: Not fully implemented yet! We need to have a better understanding 11147 // of when we're entering 11148 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 11149 Sema &S; 11150 SourceLocation Loc; 11151 11152 public: 11153 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 11154 11155 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 11156 11157 bool TraverseTemplateArgument(const TemplateArgument &Arg); 11158 bool TraverseRecordType(RecordType *T); 11159 }; 11160} 11161 11162bool MarkReferencedDecls::TraverseTemplateArgument( 11163 const TemplateArgument &Arg) { 11164 if (Arg.getKind() == TemplateArgument::Declaration) { 11165 if (Decl *D = Arg.getAsDecl()) 11166 S.MarkAnyDeclReferenced(Loc, D); 11167 } 11168 11169 return Inherited::TraverseTemplateArgument(Arg); 11170} 11171 11172bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 11173 if (ClassTemplateSpecializationDecl *Spec 11174 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 11175 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 11176 return TraverseTemplateArguments(Args.data(), Args.size()); 11177 } 11178 11179 return true; 11180} 11181 11182void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 11183 MarkReferencedDecls Marker(*this, Loc); 11184 Marker.TraverseType(Context.getCanonicalType(T)); 11185} 11186 11187namespace { 11188 /// \brief Helper class that marks all of the declarations referenced by 11189 /// potentially-evaluated subexpressions as "referenced". 11190 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 11191 Sema &S; 11192 bool SkipLocalVariables; 11193 11194 public: 11195 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 11196 11197 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 11198 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 11199 11200 void VisitDeclRefExpr(DeclRefExpr *E) { 11201 // If we were asked not to visit local variables, don't. 11202 if (SkipLocalVariables) { 11203 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 11204 if (VD->hasLocalStorage()) 11205 return; 11206 } 11207 11208 S.MarkDeclRefReferenced(E); 11209 } 11210 11211 void VisitMemberExpr(MemberExpr *E) { 11212 S.MarkMemberReferenced(E); 11213 Inherited::VisitMemberExpr(E); 11214 } 11215 11216 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 11217 S.MarkFunctionReferenced(E->getLocStart(), 11218 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 11219 Visit(E->getSubExpr()); 11220 } 11221 11222 void VisitCXXNewExpr(CXXNewExpr *E) { 11223 if (E->getOperatorNew()) 11224 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 11225 if (E->getOperatorDelete()) 11226 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 11227 Inherited::VisitCXXNewExpr(E); 11228 } 11229 11230 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 11231 if (E->getOperatorDelete()) 11232 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 11233 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 11234 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 11235 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 11236 S.MarkFunctionReferenced(E->getLocStart(), 11237 S.LookupDestructor(Record)); 11238 } 11239 11240 Inherited::VisitCXXDeleteExpr(E); 11241 } 11242 11243 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11244 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 11245 Inherited::VisitCXXConstructExpr(E); 11246 } 11247 11248 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 11249 Visit(E->getExpr()); 11250 } 11251 11252 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11253 Inherited::VisitImplicitCastExpr(E); 11254 11255 if (E->getCastKind() == CK_LValueToRValue) 11256 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 11257 } 11258 }; 11259} 11260 11261/// \brief Mark any declarations that appear within this expression or any 11262/// potentially-evaluated subexpressions as "referenced". 11263/// 11264/// \param SkipLocalVariables If true, don't mark local variables as 11265/// 'referenced'. 11266void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 11267 bool SkipLocalVariables) { 11268 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 11269} 11270 11271/// \brief Emit a diagnostic that describes an effect on the run-time behavior 11272/// of the program being compiled. 11273/// 11274/// This routine emits the given diagnostic when the code currently being 11275/// type-checked is "potentially evaluated", meaning that there is a 11276/// possibility that the code will actually be executable. Code in sizeof() 11277/// expressions, code used only during overload resolution, etc., are not 11278/// potentially evaluated. This routine will suppress such diagnostics or, 11279/// in the absolutely nutty case of potentially potentially evaluated 11280/// expressions (C++ typeid), queue the diagnostic to potentially emit it 11281/// later. 11282/// 11283/// This routine should be used for all diagnostics that describe the run-time 11284/// behavior of a program, such as passing a non-POD value through an ellipsis. 11285/// Failure to do so will likely result in spurious diagnostics or failures 11286/// during overload resolution or within sizeof/alignof/typeof/typeid. 11287bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 11288 const PartialDiagnostic &PD) { 11289 switch (ExprEvalContexts.back().Context) { 11290 case Unevaluated: 11291 // The argument will never be evaluated, so don't complain. 11292 break; 11293 11294 case ConstantEvaluated: 11295 // Relevant diagnostics should be produced by constant evaluation. 11296 break; 11297 11298 case PotentiallyEvaluated: 11299 case PotentiallyEvaluatedIfUsed: 11300 if (Statement && getCurFunctionOrMethodDecl()) { 11301 FunctionScopes.back()->PossiblyUnreachableDiags. 11302 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 11303 } 11304 else 11305 Diag(Loc, PD); 11306 11307 return true; 11308 } 11309 11310 return false; 11311} 11312 11313bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 11314 CallExpr *CE, FunctionDecl *FD) { 11315 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 11316 return false; 11317 11318 // If we're inside a decltype's expression, don't check for a valid return 11319 // type or construct temporaries until we know whether this is the last call. 11320 if (ExprEvalContexts.back().IsDecltype) { 11321 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 11322 return false; 11323 } 11324 11325 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 11326 FunctionDecl *FD; 11327 CallExpr *CE; 11328 11329 public: 11330 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 11331 : FD(FD), CE(CE) { } 11332 11333 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 11334 if (!FD) { 11335 S.Diag(Loc, diag::err_call_incomplete_return) 11336 << T << CE->getSourceRange(); 11337 return; 11338 } 11339 11340 S.Diag(Loc, diag::err_call_function_incomplete_return) 11341 << CE->getSourceRange() << FD->getDeclName() << T; 11342 S.Diag(FD->getLocation(), 11343 diag::note_function_with_incomplete_return_type_declared_here) 11344 << FD->getDeclName(); 11345 } 11346 } Diagnoser(FD, CE); 11347 11348 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 11349 return true; 11350 11351 return false; 11352} 11353 11354// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 11355// will prevent this condition from triggering, which is what we want. 11356void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 11357 SourceLocation Loc; 11358 11359 unsigned diagnostic = diag::warn_condition_is_assignment; 11360 bool IsOrAssign = false; 11361 11362 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 11363 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 11364 return; 11365 11366 IsOrAssign = Op->getOpcode() == BO_OrAssign; 11367 11368 // Greylist some idioms by putting them into a warning subcategory. 11369 if (ObjCMessageExpr *ME 11370 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 11371 Selector Sel = ME->getSelector(); 11372 11373 // self = [<foo> init...] 11374 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init")) 11375 diagnostic = diag::warn_condition_is_idiomatic_assignment; 11376 11377 // <foo> = [<bar> nextObject] 11378 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 11379 diagnostic = diag::warn_condition_is_idiomatic_assignment; 11380 } 11381 11382 Loc = Op->getOperatorLoc(); 11383 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 11384 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 11385 return; 11386 11387 IsOrAssign = Op->getOperator() == OO_PipeEqual; 11388 Loc = Op->getOperatorLoc(); 11389 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 11390 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 11391 else { 11392 // Not an assignment. 11393 return; 11394 } 11395 11396 Diag(Loc, diagnostic) << E->getSourceRange(); 11397 11398 SourceLocation Open = E->getLocStart(); 11399 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 11400 Diag(Loc, diag::note_condition_assign_silence) 11401 << FixItHint::CreateInsertion(Open, "(") 11402 << FixItHint::CreateInsertion(Close, ")"); 11403 11404 if (IsOrAssign) 11405 Diag(Loc, diag::note_condition_or_assign_to_comparison) 11406 << FixItHint::CreateReplacement(Loc, "!="); 11407 else 11408 Diag(Loc, diag::note_condition_assign_to_comparison) 11409 << FixItHint::CreateReplacement(Loc, "=="); 11410} 11411 11412/// \brief Redundant parentheses over an equality comparison can indicate 11413/// that the user intended an assignment used as condition. 11414void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 11415 // Don't warn if the parens came from a macro. 11416 SourceLocation parenLoc = ParenE->getLocStart(); 11417 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 11418 return; 11419 // Don't warn for dependent expressions. 11420 if (ParenE->isTypeDependent()) 11421 return; 11422 11423 Expr *E = ParenE->IgnoreParens(); 11424 11425 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 11426 if (opE->getOpcode() == BO_EQ && 11427 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 11428 == Expr::MLV_Valid) { 11429 SourceLocation Loc = opE->getOperatorLoc(); 11430 11431 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 11432 SourceRange ParenERange = ParenE->getSourceRange(); 11433 Diag(Loc, diag::note_equality_comparison_silence) 11434 << FixItHint::CreateRemoval(ParenERange.getBegin()) 11435 << FixItHint::CreateRemoval(ParenERange.getEnd()); 11436 Diag(Loc, diag::note_equality_comparison_to_assign) 11437 << FixItHint::CreateReplacement(Loc, "="); 11438 } 11439} 11440 11441ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 11442 DiagnoseAssignmentAsCondition(E); 11443 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 11444 DiagnoseEqualityWithExtraParens(parenE); 11445 11446 ExprResult result = CheckPlaceholderExpr(E); 11447 if (result.isInvalid()) return ExprError(); 11448 E = result.take(); 11449 11450 if (!E->isTypeDependent()) { 11451 if (getLangOpts().CPlusPlus) 11452 return CheckCXXBooleanCondition(E); // C++ 6.4p4 11453 11454 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 11455 if (ERes.isInvalid()) 11456 return ExprError(); 11457 E = ERes.take(); 11458 11459 QualType T = E->getType(); 11460 if (!T->isScalarType()) { // C99 6.8.4.1p1 11461 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 11462 << T << E->getSourceRange(); 11463 return ExprError(); 11464 } 11465 } 11466 11467 return Owned(E); 11468} 11469 11470ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 11471 Expr *SubExpr) { 11472 if (!SubExpr) 11473 return ExprError(); 11474 11475 return CheckBooleanCondition(SubExpr, Loc); 11476} 11477 11478namespace { 11479 /// A visitor for rebuilding a call to an __unknown_any expression 11480 /// to have an appropriate type. 11481 struct RebuildUnknownAnyFunction 11482 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 11483 11484 Sema &S; 11485 11486 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 11487 11488 ExprResult VisitStmt(Stmt *S) { 11489 llvm_unreachable("unexpected statement!"); 11490 } 11491 11492 ExprResult VisitExpr(Expr *E) { 11493 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 11494 << E->getSourceRange(); 11495 return ExprError(); 11496 } 11497 11498 /// Rebuild an expression which simply semantically wraps another 11499 /// expression which it shares the type and value kind of. 11500 template <class T> ExprResult rebuildSugarExpr(T *E) { 11501 ExprResult SubResult = Visit(E->getSubExpr()); 11502 if (SubResult.isInvalid()) return ExprError(); 11503 11504 Expr *SubExpr = SubResult.take(); 11505 E->setSubExpr(SubExpr); 11506 E->setType(SubExpr->getType()); 11507 E->setValueKind(SubExpr->getValueKind()); 11508 assert(E->getObjectKind() == OK_Ordinary); 11509 return E; 11510 } 11511 11512 ExprResult VisitParenExpr(ParenExpr *E) { 11513 return rebuildSugarExpr(E); 11514 } 11515 11516 ExprResult VisitUnaryExtension(UnaryOperator *E) { 11517 return rebuildSugarExpr(E); 11518 } 11519 11520 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 11521 ExprResult SubResult = Visit(E->getSubExpr()); 11522 if (SubResult.isInvalid()) return ExprError(); 11523 11524 Expr *SubExpr = SubResult.take(); 11525 E->setSubExpr(SubExpr); 11526 E->setType(S.Context.getPointerType(SubExpr->getType())); 11527 assert(E->getValueKind() == VK_RValue); 11528 assert(E->getObjectKind() == OK_Ordinary); 11529 return E; 11530 } 11531 11532 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 11533 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 11534 11535 E->setType(VD->getType()); 11536 11537 assert(E->getValueKind() == VK_RValue); 11538 if (S.getLangOpts().CPlusPlus && 11539 !(isa<CXXMethodDecl>(VD) && 11540 cast<CXXMethodDecl>(VD)->isInstance())) 11541 E->setValueKind(VK_LValue); 11542 11543 return E; 11544 } 11545 11546 ExprResult VisitMemberExpr(MemberExpr *E) { 11547 return resolveDecl(E, E->getMemberDecl()); 11548 } 11549 11550 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 11551 return resolveDecl(E, E->getDecl()); 11552 } 11553 }; 11554} 11555 11556/// Given a function expression of unknown-any type, try to rebuild it 11557/// to have a function type. 11558static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 11559 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 11560 if (Result.isInvalid()) return ExprError(); 11561 return S.DefaultFunctionArrayConversion(Result.take()); 11562} 11563 11564namespace { 11565 /// A visitor for rebuilding an expression of type __unknown_anytype 11566 /// into one which resolves the type directly on the referring 11567 /// expression. Strict preservation of the original source 11568 /// structure is not a goal. 11569 struct RebuildUnknownAnyExpr 11570 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 11571 11572 Sema &S; 11573 11574 /// The current destination type. 11575 QualType DestType; 11576 11577 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 11578 : S(S), DestType(CastType) {} 11579 11580 ExprResult VisitStmt(Stmt *S) { 11581 llvm_unreachable("unexpected statement!"); 11582 } 11583 11584 ExprResult VisitExpr(Expr *E) { 11585 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 11586 << E->getSourceRange(); 11587 return ExprError(); 11588 } 11589 11590 ExprResult VisitCallExpr(CallExpr *E); 11591 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 11592 11593 /// Rebuild an expression which simply semantically wraps another 11594 /// expression which it shares the type and value kind of. 11595 template <class T> ExprResult rebuildSugarExpr(T *E) { 11596 ExprResult SubResult = Visit(E->getSubExpr()); 11597 if (SubResult.isInvalid()) return ExprError(); 11598 Expr *SubExpr = SubResult.take(); 11599 E->setSubExpr(SubExpr); 11600 E->setType(SubExpr->getType()); 11601 E->setValueKind(SubExpr->getValueKind()); 11602 assert(E->getObjectKind() == OK_Ordinary); 11603 return E; 11604 } 11605 11606 ExprResult VisitParenExpr(ParenExpr *E) { 11607 return rebuildSugarExpr(E); 11608 } 11609 11610 ExprResult VisitUnaryExtension(UnaryOperator *E) { 11611 return rebuildSugarExpr(E); 11612 } 11613 11614 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 11615 const PointerType *Ptr = DestType->getAs<PointerType>(); 11616 if (!Ptr) { 11617 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 11618 << E->getSourceRange(); 11619 return ExprError(); 11620 } 11621 assert(E->getValueKind() == VK_RValue); 11622 assert(E->getObjectKind() == OK_Ordinary); 11623 E->setType(DestType); 11624 11625 // Build the sub-expression as if it were an object of the pointee type. 11626 DestType = Ptr->getPointeeType(); 11627 ExprResult SubResult = Visit(E->getSubExpr()); 11628 if (SubResult.isInvalid()) return ExprError(); 11629 E->setSubExpr(SubResult.take()); 11630 return E; 11631 } 11632 11633 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 11634 11635 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 11636 11637 ExprResult VisitMemberExpr(MemberExpr *E) { 11638 return resolveDecl(E, E->getMemberDecl()); 11639 } 11640 11641 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 11642 return resolveDecl(E, E->getDecl()); 11643 } 11644 }; 11645} 11646 11647/// Rebuilds a call expression which yielded __unknown_anytype. 11648ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 11649 Expr *CalleeExpr = E->getCallee(); 11650 11651 enum FnKind { 11652 FK_MemberFunction, 11653 FK_FunctionPointer, 11654 FK_BlockPointer 11655 }; 11656 11657 FnKind Kind; 11658 QualType CalleeType = CalleeExpr->getType(); 11659 if (CalleeType == S.Context.BoundMemberTy) { 11660 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 11661 Kind = FK_MemberFunction; 11662 CalleeType = Expr::findBoundMemberType(CalleeExpr); 11663 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 11664 CalleeType = Ptr->getPointeeType(); 11665 Kind = FK_FunctionPointer; 11666 } else { 11667 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 11668 Kind = FK_BlockPointer; 11669 } 11670 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 11671 11672 // Verify that this is a legal result type of a function. 11673 if (DestType->isArrayType() || DestType->isFunctionType()) { 11674 unsigned diagID = diag::err_func_returning_array_function; 11675 if (Kind == FK_BlockPointer) 11676 diagID = diag::err_block_returning_array_function; 11677 11678 S.Diag(E->getExprLoc(), diagID) 11679 << DestType->isFunctionType() << DestType; 11680 return ExprError(); 11681 } 11682 11683 // Otherwise, go ahead and set DestType as the call's result. 11684 E->setType(DestType.getNonLValueExprType(S.Context)); 11685 E->setValueKind(Expr::getValueKindForType(DestType)); 11686 assert(E->getObjectKind() == OK_Ordinary); 11687 11688 // Rebuild the function type, replacing the result type with DestType. 11689 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType)) 11690 DestType = S.Context.getFunctionType(DestType, 11691 Proto->arg_type_begin(), 11692 Proto->getNumArgs(), 11693 Proto->getExtProtoInfo()); 11694 else 11695 DestType = S.Context.getFunctionNoProtoType(DestType, 11696 FnType->getExtInfo()); 11697 11698 // Rebuild the appropriate pointer-to-function type. 11699 switch (Kind) { 11700 case FK_MemberFunction: 11701 // Nothing to do. 11702 break; 11703 11704 case FK_FunctionPointer: 11705 DestType = S.Context.getPointerType(DestType); 11706 break; 11707 11708 case FK_BlockPointer: 11709 DestType = S.Context.getBlockPointerType(DestType); 11710 break; 11711 } 11712 11713 // Finally, we can recurse. 11714 ExprResult CalleeResult = Visit(CalleeExpr); 11715 if (!CalleeResult.isUsable()) return ExprError(); 11716 E->setCallee(CalleeResult.take()); 11717 11718 // Bind a temporary if necessary. 11719 return S.MaybeBindToTemporary(E); 11720} 11721 11722ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 11723 // Verify that this is a legal result type of a call. 11724 if (DestType->isArrayType() || DestType->isFunctionType()) { 11725 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 11726 << DestType->isFunctionType() << DestType; 11727 return ExprError(); 11728 } 11729 11730 // Rewrite the method result type if available. 11731 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 11732 assert(Method->getResultType() == S.Context.UnknownAnyTy); 11733 Method->setResultType(DestType); 11734 } 11735 11736 // Change the type of the message. 11737 E->setType(DestType.getNonReferenceType()); 11738 E->setValueKind(Expr::getValueKindForType(DestType)); 11739 11740 return S.MaybeBindToTemporary(E); 11741} 11742 11743ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 11744 // The only case we should ever see here is a function-to-pointer decay. 11745 if (E->getCastKind() == CK_FunctionToPointerDecay) { 11746 assert(E->getValueKind() == VK_RValue); 11747 assert(E->getObjectKind() == OK_Ordinary); 11748 11749 E->setType(DestType); 11750 11751 // Rebuild the sub-expression as the pointee (function) type. 11752 DestType = DestType->castAs<PointerType>()->getPointeeType(); 11753 11754 ExprResult Result = Visit(E->getSubExpr()); 11755 if (!Result.isUsable()) return ExprError(); 11756 11757 E->setSubExpr(Result.take()); 11758 return S.Owned(E); 11759 } else if (E->getCastKind() == CK_LValueToRValue) { 11760 assert(E->getValueKind() == VK_RValue); 11761 assert(E->getObjectKind() == OK_Ordinary); 11762 11763 assert(isa<BlockPointerType>(E->getType())); 11764 11765 E->setType(DestType); 11766 11767 // The sub-expression has to be a lvalue reference, so rebuild it as such. 11768 DestType = S.Context.getLValueReferenceType(DestType); 11769 11770 ExprResult Result = Visit(E->getSubExpr()); 11771 if (!Result.isUsable()) return ExprError(); 11772 11773 E->setSubExpr(Result.take()); 11774 return S.Owned(E); 11775 } else { 11776 llvm_unreachable("Unhandled cast type!"); 11777 } 11778} 11779 11780ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 11781 ExprValueKind ValueKind = VK_LValue; 11782 QualType Type = DestType; 11783 11784 // We know how to make this work for certain kinds of decls: 11785 11786 // - functions 11787 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 11788 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 11789 DestType = Ptr->getPointeeType(); 11790 ExprResult Result = resolveDecl(E, VD); 11791 if (Result.isInvalid()) return ExprError(); 11792 return S.ImpCastExprToType(Result.take(), Type, 11793 CK_FunctionToPointerDecay, VK_RValue); 11794 } 11795 11796 if (!Type->isFunctionType()) { 11797 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 11798 << VD << E->getSourceRange(); 11799 return ExprError(); 11800 } 11801 11802 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 11803 if (MD->isInstance()) { 11804 ValueKind = VK_RValue; 11805 Type = S.Context.BoundMemberTy; 11806 } 11807 11808 // Function references aren't l-values in C. 11809 if (!S.getLangOpts().CPlusPlus) 11810 ValueKind = VK_RValue; 11811 11812 // - variables 11813 } else if (isa<VarDecl>(VD)) { 11814 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 11815 Type = RefTy->getPointeeType(); 11816 } else if (Type->isFunctionType()) { 11817 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 11818 << VD << E->getSourceRange(); 11819 return ExprError(); 11820 } 11821 11822 // - nothing else 11823 } else { 11824 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 11825 << VD << E->getSourceRange(); 11826 return ExprError(); 11827 } 11828 11829 VD->setType(DestType); 11830 E->setType(Type); 11831 E->setValueKind(ValueKind); 11832 return S.Owned(E); 11833} 11834 11835/// Check a cast of an unknown-any type. We intentionally only 11836/// trigger this for C-style casts. 11837ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 11838 Expr *CastExpr, CastKind &CastKind, 11839 ExprValueKind &VK, CXXCastPath &Path) { 11840 // Rewrite the casted expression from scratch. 11841 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 11842 if (!result.isUsable()) return ExprError(); 11843 11844 CastExpr = result.take(); 11845 VK = CastExpr->getValueKind(); 11846 CastKind = CK_NoOp; 11847 11848 return CastExpr; 11849} 11850 11851ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 11852 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 11853} 11854 11855QualType Sema::checkUnknownAnyArg(Expr *&arg) { 11856 // Filter out placeholders. 11857 ExprResult argR = CheckPlaceholderExpr(arg); 11858 if (argR.isInvalid()) return QualType(); 11859 arg = argR.take(); 11860 11861 // If the argument is an explicit cast, use that exact type as the 11862 // effective parameter type. 11863 if (ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg)) { 11864 return castArg->getTypeAsWritten(); 11865 } 11866 11867 // Otherwise, try to pass by value. 11868 return arg->getType().getUnqualifiedType(); 11869} 11870 11871static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 11872 Expr *orig = E; 11873 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 11874 while (true) { 11875 E = E->IgnoreParenImpCasts(); 11876 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 11877 E = call->getCallee(); 11878 diagID = diag::err_uncasted_call_of_unknown_any; 11879 } else { 11880 break; 11881 } 11882 } 11883 11884 SourceLocation loc; 11885 NamedDecl *d; 11886 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 11887 loc = ref->getLocation(); 11888 d = ref->getDecl(); 11889 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 11890 loc = mem->getMemberLoc(); 11891 d = mem->getMemberDecl(); 11892 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 11893 diagID = diag::err_uncasted_call_of_unknown_any; 11894 loc = msg->getSelectorStartLoc(); 11895 d = msg->getMethodDecl(); 11896 if (!d) { 11897 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 11898 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 11899 << orig->getSourceRange(); 11900 return ExprError(); 11901 } 11902 } else { 11903 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 11904 << E->getSourceRange(); 11905 return ExprError(); 11906 } 11907 11908 S.Diag(loc, diagID) << d << orig->getSourceRange(); 11909 11910 // Never recoverable. 11911 return ExprError(); 11912} 11913 11914/// Check for operands with placeholder types and complain if found. 11915/// Returns true if there was an error and no recovery was possible. 11916ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 11917 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 11918 if (!placeholderType) return Owned(E); 11919 11920 switch (placeholderType->getKind()) { 11921 11922 // Overloaded expressions. 11923 case BuiltinType::Overload: { 11924 // Try to resolve a single function template specialization. 11925 // This is obligatory. 11926 ExprResult result = Owned(E); 11927 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 11928 return result; 11929 11930 // If that failed, try to recover with a call. 11931 } else { 11932 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 11933 /*complain*/ true); 11934 return result; 11935 } 11936 } 11937 11938 // Bound member functions. 11939 case BuiltinType::BoundMember: { 11940 ExprResult result = Owned(E); 11941 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function), 11942 /*complain*/ true); 11943 return result; 11944 } 11945 11946 // ARC unbridged casts. 11947 case BuiltinType::ARCUnbridgedCast: { 11948 Expr *realCast = stripARCUnbridgedCast(E); 11949 diagnoseARCUnbridgedCast(realCast); 11950 return Owned(realCast); 11951 } 11952 11953 // Expressions of unknown type. 11954 case BuiltinType::UnknownAny: 11955 return diagnoseUnknownAnyExpr(*this, E); 11956 11957 // Pseudo-objects. 11958 case BuiltinType::PseudoObject: 11959 return checkPseudoObjectRValue(E); 11960 11961 case BuiltinType::BuiltinFn: 11962 Diag(E->getLocStart(), diag::err_builtin_fn_use); 11963 return ExprError(); 11964 11965 // Everything else should be impossible. 11966#define BUILTIN_TYPE(Id, SingletonId) \ 11967 case BuiltinType::Id: 11968#define PLACEHOLDER_TYPE(Id, SingletonId) 11969#include "clang/AST/BuiltinTypes.def" 11970 break; 11971 } 11972 11973 llvm_unreachable("invalid placeholder type!"); 11974} 11975 11976bool Sema::CheckCaseExpression(Expr *E) { 11977 if (E->isTypeDependent()) 11978 return true; 11979 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 11980 return E->getType()->isIntegralOrEnumerationType(); 11981 return false; 11982} 11983 11984/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 11985ExprResult 11986Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 11987 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 11988 "Unknown Objective-C Boolean value!"); 11989 QualType BoolT = Context.ObjCBuiltinBoolTy; 11990 if (!Context.getBOOLDecl()) { 11991 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 11992 Sema::LookupOrdinaryName); 11993 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 11994 NamedDecl *ND = Result.getFoundDecl(); 11995 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 11996 Context.setBOOLDecl(TD); 11997 } 11998 } 11999 if (Context.getBOOLDecl()) 12000 BoolT = Context.getBOOLType(); 12001 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, 12002 BoolT, OpLoc)); 12003} 12004