SemaExpr.cpp revision 09d19efaa147762f84aed55efa7930bb3616a4e5
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 "TreeTransform.h" 16#include "clang/AST/ASTConsumer.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/AST/ASTMutationListener.h" 19#include "clang/AST/CXXInheritance.h" 20#include "clang/AST/DeclObjC.h" 21#include "clang/AST/DeclTemplate.h" 22#include "clang/AST/EvaluatedExprVisitor.h" 23#include "clang/AST/Expr.h" 24#include "clang/AST/ExprCXX.h" 25#include "clang/AST/ExprObjC.h" 26#include "clang/AST/RecursiveASTVisitor.h" 27#include "clang/AST/TypeLoc.h" 28#include "clang/Basic/PartialDiagnostic.h" 29#include "clang/Basic/SourceManager.h" 30#include "clang/Basic/TargetInfo.h" 31#include "clang/Lex/LiteralSupport.h" 32#include "clang/Lex/Preprocessor.h" 33#include "clang/Sema/AnalysisBasedWarnings.h" 34#include "clang/Sema/DeclSpec.h" 35#include "clang/Sema/DelayedDiagnostic.h" 36#include "clang/Sema/Designator.h" 37#include "clang/Sema/Initialization.h" 38#include "clang/Sema/Lookup.h" 39#include "clang/Sema/ParsedTemplate.h" 40#include "clang/Sema/Scope.h" 41#include "clang/Sema/ScopeInfo.h" 42#include "clang/Sema/SemaFixItUtils.h" 43#include "clang/Sema/Template.h" 44using namespace clang; 45using namespace sema; 46 47/// \brief Determine whether the use of this declaration is valid, without 48/// emitting diagnostics. 49bool Sema::CanUseDecl(NamedDecl *D) { 50 // See if this is an auto-typed variable whose initializer we are parsing. 51 if (ParsingInitForAutoVars.count(D)) 52 return false; 53 54 // See if this is a deleted function. 55 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 56 if (FD->isDeleted()) 57 return false; 58 59 // If the function has a deduced return type, and we can't deduce it, 60 // then we can't use it either. 61 if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() && 62 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/false)) 63 return false; 64 } 65 66 // See if this function is unavailable. 67 if (D->getAvailability() == AR_Unavailable && 68 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 69 return false; 70 71 return true; 72} 73 74static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 75 // Warn if this is used but marked unused. 76 if (D->hasAttr<UnusedAttr>()) { 77 const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext()); 78 if (!DC->hasAttr<UnusedAttr>()) 79 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 80 } 81} 82 83static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S, 84 NamedDecl *D, SourceLocation Loc, 85 const ObjCInterfaceDecl *UnknownObjCClass) { 86 // See if this declaration is unavailable or deprecated. 87 std::string Message; 88 AvailabilityResult Result = D->getAvailability(&Message); 89 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 90 if (Result == AR_Available) { 91 const DeclContext *DC = ECD->getDeclContext(); 92 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 93 Result = TheEnumDecl->getAvailability(&Message); 94 } 95 96 const ObjCPropertyDecl *ObjCPDecl = 0; 97 if (Result == AR_Deprecated || Result == AR_Unavailable) { 98 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 99 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 100 AvailabilityResult PDeclResult = PD->getAvailability(0); 101 if (PDeclResult == Result) 102 ObjCPDecl = PD; 103 } 104 } 105 } 106 107 switch (Result) { 108 case AR_Available: 109 case AR_NotYetIntroduced: 110 break; 111 112 case AR_Deprecated: 113 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl); 114 break; 115 116 case AR_Unavailable: 117 if (S.getCurContextAvailability() != AR_Unavailable) { 118 if (Message.empty()) { 119 if (!UnknownObjCClass) { 120 S.Diag(Loc, diag::err_unavailable) << D->getDeclName(); 121 if (ObjCPDecl) 122 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute) 123 << ObjCPDecl->getDeclName() << 1; 124 } 125 else 126 S.Diag(Loc, diag::warn_unavailable_fwdclass_message) 127 << D->getDeclName(); 128 } 129 else 130 S.Diag(Loc, diag::err_unavailable_message) 131 << D->getDeclName() << Message; 132 S.Diag(D->getLocation(), diag::note_unavailable_here) 133 << isa<FunctionDecl>(D) << false; 134 if (ObjCPDecl) 135 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute) 136 << ObjCPDecl->getDeclName() << 1; 137 } 138 break; 139 } 140 return Result; 141} 142 143/// \brief Emit a note explaining that this function is deleted or unavailable. 144void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 145 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 146 147 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) { 148 // If the method was explicitly defaulted, point at that declaration. 149 if (!Method->isImplicit()) 150 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 151 152 // Try to diagnose why this special member function was implicitly 153 // deleted. This might fail, if that reason no longer applies. 154 CXXSpecialMember CSM = getSpecialMember(Method); 155 if (CSM != CXXInvalid) 156 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true); 157 158 return; 159 } 160 161 Diag(Decl->getLocation(), diag::note_unavailable_here) 162 << 1 << Decl->isDeleted(); 163} 164 165/// \brief Determine whether a FunctionDecl was ever declared with an 166/// explicit storage class. 167static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 168 for (FunctionDecl::redecl_iterator I = D->redecls_begin(), 169 E = D->redecls_end(); 170 I != E; ++I) { 171 if (I->getStorageClass() != SC_None) 172 return true; 173 } 174 return false; 175} 176 177/// \brief Check whether we're in an extern inline function and referring to a 178/// variable or function with internal linkage (C11 6.7.4p3). 179/// 180/// This is only a warning because we used to silently accept this code, but 181/// in many cases it will not behave correctly. This is not enabled in C++ mode 182/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 183/// and so while there may still be user mistakes, most of the time we can't 184/// prove that there are errors. 185static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 186 const NamedDecl *D, 187 SourceLocation Loc) { 188 // This is disabled under C++; there are too many ways for this to fire in 189 // contexts where the warning is a false positive, or where it is technically 190 // correct but benign. 191 if (S.getLangOpts().CPlusPlus) 192 return; 193 194 // Check if this is an inlined function or method. 195 FunctionDecl *Current = S.getCurFunctionDecl(); 196 if (!Current) 197 return; 198 if (!Current->isInlined()) 199 return; 200 if (!Current->isExternallyVisible()) 201 return; 202 203 // Check if the decl has internal linkage. 204 if (D->getFormalLinkage() != InternalLinkage) 205 return; 206 207 // Downgrade from ExtWarn to Extension if 208 // (1) the supposedly external inline function is in the main file, 209 // and probably won't be included anywhere else. 210 // (2) the thing we're referencing is a pure function. 211 // (3) the thing we're referencing is another inline function. 212 // This last can give us false negatives, but it's better than warning on 213 // wrappers for simple C library functions. 214 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 215 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc); 216 if (!DowngradeWarning && UsedFn) 217 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 218 219 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline 220 : diag::warn_internal_in_extern_inline) 221 << /*IsVar=*/!UsedFn << D; 222 223 S.MaybeSuggestAddingStaticToDecl(Current); 224 225 S.Diag(D->getCanonicalDecl()->getLocation(), 226 diag::note_internal_decl_declared_here) 227 << D; 228} 229 230void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 231 const FunctionDecl *First = Cur->getFirstDeclaration(); 232 233 // Suggest "static" on the function, if possible. 234 if (!hasAnyExplicitStorageClass(First)) { 235 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 236 Diag(DeclBegin, diag::note_convert_inline_to_static) 237 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 238 } 239} 240 241/// \brief Determine whether the use of this declaration is valid, and 242/// emit any corresponding diagnostics. 243/// 244/// This routine diagnoses various problems with referencing 245/// declarations that can occur when using a declaration. For example, 246/// it might warn if a deprecated or unavailable declaration is being 247/// used, or produce an error (and return true) if a C++0x deleted 248/// function is being used. 249/// 250/// \returns true if there was an error (this declaration cannot be 251/// referenced), false otherwise. 252/// 253bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 254 const ObjCInterfaceDecl *UnknownObjCClass) { 255 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 256 // If there were any diagnostics suppressed by template argument deduction, 257 // emit them now. 258 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator 259 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 260 if (Pos != SuppressedDiagnostics.end()) { 261 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second; 262 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I) 263 Diag(Suppressed[I].first, Suppressed[I].second); 264 265 // Clear out the list of suppressed diagnostics, so that we don't emit 266 // them again for this specialization. However, we don't obsolete this 267 // entry from the table, because we want to avoid ever emitting these 268 // diagnostics again. 269 Suppressed.clear(); 270 } 271 } 272 273 // See if this is an auto-typed variable whose initializer we are parsing. 274 if (ParsingInitForAutoVars.count(D)) { 275 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 276 << D->getDeclName(); 277 return true; 278 } 279 280 // See if this is a deleted function. 281 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 282 if (FD->isDeleted()) { 283 Diag(Loc, diag::err_deleted_function_use); 284 NoteDeletedFunction(FD); 285 return true; 286 } 287 288 // If the function has a deduced return type, and we can't deduce it, 289 // then we can't use it either. 290 if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() && 291 DeduceReturnType(FD, Loc)) 292 return true; 293 } 294 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass); 295 296 DiagnoseUnusedOfDecl(*this, D, Loc); 297 298 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 299 300 return false; 301} 302 303/// \brief Retrieve the message suffix that should be added to a 304/// diagnostic complaining about the given function being deleted or 305/// unavailable. 306std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 307 std::string Message; 308 if (FD->getAvailability(&Message)) 309 return ": " + Message; 310 311 return std::string(); 312} 313 314/// DiagnoseSentinelCalls - This routine checks whether a call or 315/// message-send is to a declaration with the sentinel attribute, and 316/// if so, it checks that the requirements of the sentinel are 317/// satisfied. 318void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 319 ArrayRef<Expr *> Args) { 320 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 321 if (!attr) 322 return; 323 324 // The number of formal parameters of the declaration. 325 unsigned numFormalParams; 326 327 // The kind of declaration. This is also an index into a %select in 328 // the diagnostic. 329 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 330 331 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 332 numFormalParams = MD->param_size(); 333 calleeType = CT_Method; 334 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 335 numFormalParams = FD->param_size(); 336 calleeType = CT_Function; 337 } else if (isa<VarDecl>(D)) { 338 QualType type = cast<ValueDecl>(D)->getType(); 339 const FunctionType *fn = 0; 340 if (const PointerType *ptr = type->getAs<PointerType>()) { 341 fn = ptr->getPointeeType()->getAs<FunctionType>(); 342 if (!fn) return; 343 calleeType = CT_Function; 344 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 345 fn = ptr->getPointeeType()->castAs<FunctionType>(); 346 calleeType = CT_Block; 347 } else { 348 return; 349 } 350 351 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 352 numFormalParams = proto->getNumArgs(); 353 } else { 354 numFormalParams = 0; 355 } 356 } else { 357 return; 358 } 359 360 // "nullPos" is the number of formal parameters at the end which 361 // effectively count as part of the variadic arguments. This is 362 // useful if you would prefer to not have *any* formal parameters, 363 // but the language forces you to have at least one. 364 unsigned nullPos = attr->getNullPos(); 365 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 366 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 367 368 // The number of arguments which should follow the sentinel. 369 unsigned numArgsAfterSentinel = attr->getSentinel(); 370 371 // If there aren't enough arguments for all the formal parameters, 372 // the sentinel, and the args after the sentinel, complain. 373 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 374 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 375 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 376 return; 377 } 378 379 // Otherwise, find the sentinel expression. 380 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 381 if (!sentinelExpr) return; 382 if (sentinelExpr->isValueDependent()) return; 383 if (Context.isSentinelNullExpr(sentinelExpr)) return; 384 385 // Pick a reasonable string to insert. Optimistically use 'nil' or 386 // 'NULL' if those are actually defined in the context. Only use 387 // 'nil' for ObjC methods, where it's much more likely that the 388 // variadic arguments form a list of object pointers. 389 SourceLocation MissingNilLoc 390 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd()); 391 std::string NullValue; 392 if (calleeType == CT_Method && 393 PP.getIdentifierInfo("nil")->hasMacroDefinition()) 394 NullValue = "nil"; 395 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition()) 396 NullValue = "NULL"; 397 else 398 NullValue = "(void*) 0"; 399 400 if (MissingNilLoc.isInvalid()) 401 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 402 else 403 Diag(MissingNilLoc, diag::warn_missing_sentinel) 404 << int(calleeType) 405 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 406 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 407} 408 409SourceRange Sema::getExprRange(Expr *E) const { 410 return E ? E->getSourceRange() : SourceRange(); 411} 412 413//===----------------------------------------------------------------------===// 414// Standard Promotions and Conversions 415//===----------------------------------------------------------------------===// 416 417/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 418ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) { 419 // Handle any placeholder expressions which made it here. 420 if (E->getType()->isPlaceholderType()) { 421 ExprResult result = CheckPlaceholderExpr(E); 422 if (result.isInvalid()) return ExprError(); 423 E = result.take(); 424 } 425 426 QualType Ty = E->getType(); 427 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 428 429 if (Ty->isFunctionType()) 430 E = ImpCastExprToType(E, Context.getPointerType(Ty), 431 CK_FunctionToPointerDecay).take(); 432 else if (Ty->isArrayType()) { 433 // In C90 mode, arrays only promote to pointers if the array expression is 434 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 435 // type 'array of type' is converted to an expression that has type 'pointer 436 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 437 // that has type 'array of type' ...". The relevant change is "an lvalue" 438 // (C90) to "an expression" (C99). 439 // 440 // C++ 4.2p1: 441 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 442 // T" can be converted to an rvalue of type "pointer to T". 443 // 444 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 445 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 446 CK_ArrayToPointerDecay).take(); 447 } 448 return Owned(E); 449} 450 451static void CheckForNullPointerDereference(Sema &S, Expr *E) { 452 // Check to see if we are dereferencing a null pointer. If so, 453 // and if not volatile-qualified, this is undefined behavior that the 454 // optimizer will delete, so warn about it. People sometimes try to use this 455 // to get a deterministic trap and are surprised by clang's behavior. This 456 // only handles the pattern "*null", which is a very syntactic check. 457 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 458 if (UO->getOpcode() == UO_Deref && 459 UO->getSubExpr()->IgnoreParenCasts()-> 460 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 461 !UO->getType().isVolatileQualified()) { 462 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 463 S.PDiag(diag::warn_indirection_through_null) 464 << UO->getSubExpr()->getSourceRange()); 465 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 466 S.PDiag(diag::note_indirection_through_null)); 467 } 468} 469 470static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 471 SourceLocation AssignLoc, 472 const Expr* RHS) { 473 const ObjCIvarDecl *IV = OIRE->getDecl(); 474 if (!IV) 475 return; 476 477 DeclarationName MemberName = IV->getDeclName(); 478 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 479 if (!Member || !Member->isStr("isa")) 480 return; 481 482 const Expr *Base = OIRE->getBase(); 483 QualType BaseType = Base->getType(); 484 if (OIRE->isArrow()) 485 BaseType = BaseType->getPointeeType(); 486 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 487 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 488 ObjCInterfaceDecl *ClassDeclared = 0; 489 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 490 if (!ClassDeclared->getSuperClass() 491 && (*ClassDeclared->ivar_begin()) == IV) { 492 if (RHS) { 493 NamedDecl *ObjectSetClass = 494 S.LookupSingleName(S.TUScope, 495 &S.Context.Idents.get("object_setClass"), 496 SourceLocation(), S.LookupOrdinaryName); 497 if (ObjectSetClass) { 498 SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd()); 499 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 500 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 501 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 502 AssignLoc), ",") << 503 FixItHint::CreateInsertion(RHSLocEnd, ")"); 504 } 505 else 506 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 507 } else { 508 NamedDecl *ObjectGetClass = 509 S.LookupSingleName(S.TUScope, 510 &S.Context.Idents.get("object_getClass"), 511 SourceLocation(), S.LookupOrdinaryName); 512 if (ObjectGetClass) 513 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 514 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 515 FixItHint::CreateReplacement( 516 SourceRange(OIRE->getOpLoc(), 517 OIRE->getLocEnd()), ")"); 518 else 519 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 520 } 521 S.Diag(IV->getLocation(), diag::note_ivar_decl); 522 } 523 } 524} 525 526ExprResult Sema::DefaultLvalueConversion(Expr *E) { 527 // Handle any placeholder expressions which made it here. 528 if (E->getType()->isPlaceholderType()) { 529 ExprResult result = CheckPlaceholderExpr(E); 530 if (result.isInvalid()) return ExprError(); 531 E = result.take(); 532 } 533 534 // C++ [conv.lval]p1: 535 // A glvalue of a non-function, non-array type T can be 536 // converted to a prvalue. 537 if (!E->isGLValue()) return Owned(E); 538 539 QualType T = E->getType(); 540 assert(!T.isNull() && "r-value conversion on typeless expression?"); 541 542 // We don't want to throw lvalue-to-rvalue casts on top of 543 // expressions of certain types in C++. 544 if (getLangOpts().CPlusPlus && 545 (E->getType() == Context.OverloadTy || 546 T->isDependentType() || 547 T->isRecordType())) 548 return Owned(E); 549 550 // The C standard is actually really unclear on this point, and 551 // DR106 tells us what the result should be but not why. It's 552 // generally best to say that void types just doesn't undergo 553 // lvalue-to-rvalue at all. Note that expressions of unqualified 554 // 'void' type are never l-values, but qualified void can be. 555 if (T->isVoidType()) 556 return Owned(E); 557 558 // OpenCL usually rejects direct accesses to values of 'half' type. 559 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 560 T->isHalfType()) { 561 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 562 << 0 << T; 563 return ExprError(); 564 } 565 566 CheckForNullPointerDereference(*this, E); 567 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 568 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 569 &Context.Idents.get("object_getClass"), 570 SourceLocation(), LookupOrdinaryName); 571 if (ObjectGetClass) 572 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 573 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 574 FixItHint::CreateReplacement( 575 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 576 else 577 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 578 } 579 else if (const ObjCIvarRefExpr *OIRE = 580 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 581 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/0); 582 583 // C++ [conv.lval]p1: 584 // [...] If T is a non-class type, the type of the prvalue is the 585 // cv-unqualified version of T. Otherwise, the type of the 586 // rvalue is T. 587 // 588 // C99 6.3.2.1p2: 589 // If the lvalue has qualified type, the value has the unqualified 590 // version of the type of the lvalue; otherwise, the value has the 591 // type of the lvalue. 592 if (T.hasQualifiers()) 593 T = T.getUnqualifiedType(); 594 595 UpdateMarkingForLValueToRValue(E); 596 597 // Loading a __weak object implicitly retains the value, so we need a cleanup to 598 // balance that. 599 if (getLangOpts().ObjCAutoRefCount && 600 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 601 ExprNeedsCleanups = true; 602 603 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, 604 E, 0, VK_RValue)); 605 606 // C11 6.3.2.1p2: 607 // ... if the lvalue has atomic type, the value has the non-atomic version 608 // of the type of the lvalue ... 609 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 610 T = Atomic->getValueType().getUnqualifiedType(); 611 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, 612 Res.get(), 0, VK_RValue)); 613 } 614 615 return Res; 616} 617 618ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 619 ExprResult Res = DefaultFunctionArrayConversion(E); 620 if (Res.isInvalid()) 621 return ExprError(); 622 Res = DefaultLvalueConversion(Res.take()); 623 if (Res.isInvalid()) 624 return ExprError(); 625 return Res; 626} 627 628 629/// UsualUnaryConversions - Performs various conversions that are common to most 630/// operators (C99 6.3). The conversions of array and function types are 631/// sometimes suppressed. For example, the array->pointer conversion doesn't 632/// apply if the array is an argument to the sizeof or address (&) operators. 633/// In these instances, this routine should *not* be called. 634ExprResult Sema::UsualUnaryConversions(Expr *E) { 635 // First, convert to an r-value. 636 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 637 if (Res.isInvalid()) 638 return ExprError(); 639 E = Res.take(); 640 641 QualType Ty = E->getType(); 642 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 643 644 // Half FP have to be promoted to float unless it is natively supported 645 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 646 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast); 647 648 // Try to perform integral promotions if the object has a theoretically 649 // promotable type. 650 if (Ty->isIntegralOrUnscopedEnumerationType()) { 651 // C99 6.3.1.1p2: 652 // 653 // The following may be used in an expression wherever an int or 654 // unsigned int may be used: 655 // - an object or expression with an integer type whose integer 656 // conversion rank is less than or equal to the rank of int 657 // and unsigned int. 658 // - A bit-field of type _Bool, int, signed int, or unsigned int. 659 // 660 // If an int can represent all values of the original type, the 661 // value is converted to an int; otherwise, it is converted to an 662 // unsigned int. These are called the integer promotions. All 663 // other types are unchanged by the integer promotions. 664 665 QualType PTy = Context.isPromotableBitField(E); 666 if (!PTy.isNull()) { 667 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take(); 668 return Owned(E); 669 } 670 if (Ty->isPromotableIntegerType()) { 671 QualType PT = Context.getPromotedIntegerType(Ty); 672 E = ImpCastExprToType(E, PT, CK_IntegralCast).take(); 673 return Owned(E); 674 } 675 } 676 return Owned(E); 677} 678 679/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 680/// do not have a prototype. Arguments that have type float or __fp16 681/// are promoted to double. All other argument types are converted by 682/// UsualUnaryConversions(). 683ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 684 QualType Ty = E->getType(); 685 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 686 687 ExprResult Res = UsualUnaryConversions(E); 688 if (Res.isInvalid()) 689 return ExprError(); 690 E = Res.take(); 691 692 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 693 // double. 694 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 695 if (BTy && (BTy->getKind() == BuiltinType::Half || 696 BTy->getKind() == BuiltinType::Float)) 697 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take(); 698 699 // C++ performs lvalue-to-rvalue conversion as a default argument 700 // promotion, even on class types, but note: 701 // C++11 [conv.lval]p2: 702 // When an lvalue-to-rvalue conversion occurs in an unevaluated 703 // operand or a subexpression thereof the value contained in the 704 // referenced object is not accessed. Otherwise, if the glvalue 705 // has a class type, the conversion copy-initializes a temporary 706 // of type T from the glvalue and the result of the conversion 707 // is a prvalue for the temporary. 708 // FIXME: add some way to gate this entire thing for correctness in 709 // potentially potentially evaluated contexts. 710 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 711 ExprResult Temp = PerformCopyInitialization( 712 InitializedEntity::InitializeTemporary(E->getType()), 713 E->getExprLoc(), 714 Owned(E)); 715 if (Temp.isInvalid()) 716 return ExprError(); 717 E = Temp.get(); 718 } 719 720 return Owned(E); 721} 722 723/// Determine the degree of POD-ness for an expression. 724/// Incomplete types are considered POD, since this check can be performed 725/// when we're in an unevaluated context. 726Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 727 if (Ty->isIncompleteType()) { 728 if (Ty->isObjCObjectType()) 729 return VAK_Invalid; 730 return VAK_Valid; 731 } 732 733 if (Ty.isCXX98PODType(Context)) 734 return VAK_Valid; 735 736 // C++11 [expr.call]p7: 737 // Passing a potentially-evaluated argument of class type (Clause 9) 738 // having a non-trivial copy constructor, a non-trivial move constructor, 739 // or a non-trivial destructor, with no corresponding parameter, 740 // is conditionally-supported with implementation-defined semantics. 741 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 742 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 743 if (!Record->hasNonTrivialCopyConstructor() && 744 !Record->hasNonTrivialMoveConstructor() && 745 !Record->hasNonTrivialDestructor()) 746 return VAK_ValidInCXX11; 747 748 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 749 return VAK_Valid; 750 return VAK_Invalid; 751} 752 753bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) { 754 // Don't allow one to pass an Objective-C interface to a vararg. 755 const QualType & Ty = E->getType(); 756 757 // Complain about passing non-POD types through varargs. 758 switch (isValidVarArgType(Ty)) { 759 case VAK_Valid: 760 break; 761 case VAK_ValidInCXX11: 762 DiagRuntimeBehavior(E->getLocStart(), 0, 763 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 764 << E->getType() << CT); 765 break; 766 case VAK_Invalid: { 767 if (Ty->isObjCObjectType()) 768 return DiagRuntimeBehavior(E->getLocStart(), 0, 769 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 770 << Ty << CT); 771 772 return DiagRuntimeBehavior(E->getLocStart(), 0, 773 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 774 << getLangOpts().CPlusPlus11 << Ty << CT); 775 } 776 } 777 // c++ rules are enforced elsewhere. 778 return false; 779} 780 781/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 782/// will create a trap if the resulting type is not a POD type. 783ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 784 FunctionDecl *FDecl) { 785 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 786 // Strip the unbridged-cast placeholder expression off, if applicable. 787 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 788 (CT == VariadicMethod || 789 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 790 E = stripARCUnbridgedCast(E); 791 792 // Otherwise, do normal placeholder checking. 793 } else { 794 ExprResult ExprRes = CheckPlaceholderExpr(E); 795 if (ExprRes.isInvalid()) 796 return ExprError(); 797 E = ExprRes.take(); 798 } 799 } 800 801 ExprResult ExprRes = DefaultArgumentPromotion(E); 802 if (ExprRes.isInvalid()) 803 return ExprError(); 804 E = ExprRes.take(); 805 806 // Diagnostics regarding non-POD argument types are 807 // emitted along with format string checking in Sema::CheckFunctionCall(). 808 if (isValidVarArgType(E->getType()) == VAK_Invalid) { 809 // Turn this into a trap. 810 CXXScopeSpec SS; 811 SourceLocation TemplateKWLoc; 812 UnqualifiedId Name; 813 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 814 E->getLocStart()); 815 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 816 Name, true, false); 817 if (TrapFn.isInvalid()) 818 return ExprError(); 819 820 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 821 E->getLocStart(), None, 822 E->getLocEnd()); 823 if (Call.isInvalid()) 824 return ExprError(); 825 826 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 827 Call.get(), E); 828 if (Comma.isInvalid()) 829 return ExprError(); 830 return Comma.get(); 831 } 832 833 if (!getLangOpts().CPlusPlus && 834 RequireCompleteType(E->getExprLoc(), E->getType(), 835 diag::err_call_incomplete_argument)) 836 return ExprError(); 837 838 return Owned(E); 839} 840 841/// \brief Converts an integer to complex float type. Helper function of 842/// UsualArithmeticConversions() 843/// 844/// \return false if the integer expression is an integer type and is 845/// successfully converted to the complex type. 846static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 847 ExprResult &ComplexExpr, 848 QualType IntTy, 849 QualType ComplexTy, 850 bool SkipCast) { 851 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 852 if (SkipCast) return false; 853 if (IntTy->isIntegerType()) { 854 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 855 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating); 856 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 857 CK_FloatingRealToComplex); 858 } else { 859 assert(IntTy->isComplexIntegerType()); 860 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 861 CK_IntegralComplexToFloatingComplex); 862 } 863 return false; 864} 865 866/// \brief Takes two complex float types and converts them to the same type. 867/// Helper function of UsualArithmeticConversions() 868static QualType 869handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS, 870 ExprResult &RHS, QualType LHSType, 871 QualType RHSType, 872 bool IsCompAssign) { 873 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 874 875 if (order < 0) { 876 // _Complex float -> _Complex double 877 if (!IsCompAssign) 878 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast); 879 return RHSType; 880 } 881 if (order > 0) 882 // _Complex float -> _Complex double 883 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast); 884 return LHSType; 885} 886 887/// \brief Converts otherExpr to complex float and promotes complexExpr if 888/// necessary. Helper function of UsualArithmeticConversions() 889static QualType handleOtherComplexFloatConversion(Sema &S, 890 ExprResult &ComplexExpr, 891 ExprResult &OtherExpr, 892 QualType ComplexTy, 893 QualType OtherTy, 894 bool ConvertComplexExpr, 895 bool ConvertOtherExpr) { 896 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy); 897 898 // If just the complexExpr is complex, the otherExpr needs to be converted, 899 // and the complexExpr might need to be promoted. 900 if (order > 0) { // complexExpr is wider 901 // float -> _Complex double 902 if (ConvertOtherExpr) { 903 QualType fp = cast<ComplexType>(ComplexTy)->getElementType(); 904 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast); 905 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy, 906 CK_FloatingRealToComplex); 907 } 908 return ComplexTy; 909 } 910 911 // otherTy is at least as wide. Find its corresponding complex type. 912 QualType result = (order == 0 ? ComplexTy : 913 S.Context.getComplexType(OtherTy)); 914 915 // double -> _Complex double 916 if (ConvertOtherExpr) 917 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result, 918 CK_FloatingRealToComplex); 919 920 // _Complex float -> _Complex double 921 if (ConvertComplexExpr && order < 0) 922 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result, 923 CK_FloatingComplexCast); 924 925 return result; 926} 927 928/// \brief Handle arithmetic conversion with complex types. Helper function of 929/// UsualArithmeticConversions() 930static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 931 ExprResult &RHS, QualType LHSType, 932 QualType RHSType, 933 bool IsCompAssign) { 934 // if we have an integer operand, the result is the complex type. 935 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 936 /*skipCast*/false)) 937 return LHSType; 938 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 939 /*skipCast*/IsCompAssign)) 940 return RHSType; 941 942 // This handles complex/complex, complex/float, or float/complex. 943 // When both operands are complex, the shorter operand is converted to the 944 // type of the longer, and that is the type of the result. This corresponds 945 // to what is done when combining two real floating-point operands. 946 // The fun begins when size promotion occur across type domains. 947 // From H&S 6.3.4: When one operand is complex and the other is a real 948 // floating-point type, the less precise type is converted, within it's 949 // real or complex domain, to the precision of the other type. For example, 950 // when combining a "long double" with a "double _Complex", the 951 // "double _Complex" is promoted to "long double _Complex". 952 953 bool LHSComplexFloat = LHSType->isComplexType(); 954 bool RHSComplexFloat = RHSType->isComplexType(); 955 956 // If both are complex, just cast to the more precise type. 957 if (LHSComplexFloat && RHSComplexFloat) 958 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS, 959 LHSType, RHSType, 960 IsCompAssign); 961 962 // If only one operand is complex, promote it if necessary and convert the 963 // other operand to complex. 964 if (LHSComplexFloat) 965 return handleOtherComplexFloatConversion( 966 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign, 967 /*convertOtherExpr*/ true); 968 969 assert(RHSComplexFloat); 970 return handleOtherComplexFloatConversion( 971 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true, 972 /*convertOtherExpr*/ !IsCompAssign); 973} 974 975/// \brief Hande arithmetic conversion from integer to float. Helper function 976/// of UsualArithmeticConversions() 977static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 978 ExprResult &IntExpr, 979 QualType FloatTy, QualType IntTy, 980 bool ConvertFloat, bool ConvertInt) { 981 if (IntTy->isIntegerType()) { 982 if (ConvertInt) 983 // Convert intExpr to the lhs floating point type. 984 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy, 985 CK_IntegralToFloating); 986 return FloatTy; 987 } 988 989 // Convert both sides to the appropriate complex float. 990 assert(IntTy->isComplexIntegerType()); 991 QualType result = S.Context.getComplexType(FloatTy); 992 993 // _Complex int -> _Complex float 994 if (ConvertInt) 995 IntExpr = S.ImpCastExprToType(IntExpr.take(), result, 996 CK_IntegralComplexToFloatingComplex); 997 998 // float -> _Complex float 999 if (ConvertFloat) 1000 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result, 1001 CK_FloatingRealToComplex); 1002 1003 return result; 1004} 1005 1006/// \brief Handle arithmethic conversion with floating point types. Helper 1007/// function of UsualArithmeticConversions() 1008static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1009 ExprResult &RHS, QualType LHSType, 1010 QualType RHSType, bool IsCompAssign) { 1011 bool LHSFloat = LHSType->isRealFloatingType(); 1012 bool RHSFloat = RHSType->isRealFloatingType(); 1013 1014 // If we have two real floating types, convert the smaller operand 1015 // to the bigger result. 1016 if (LHSFloat && RHSFloat) { 1017 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1018 if (order > 0) { 1019 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast); 1020 return LHSType; 1021 } 1022 1023 assert(order < 0 && "illegal float comparison"); 1024 if (!IsCompAssign) 1025 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast); 1026 return RHSType; 1027 } 1028 1029 if (LHSFloat) 1030 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1031 /*convertFloat=*/!IsCompAssign, 1032 /*convertInt=*/ true); 1033 assert(RHSFloat); 1034 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1035 /*convertInt=*/ true, 1036 /*convertFloat=*/!IsCompAssign); 1037} 1038 1039typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1040 1041namespace { 1042/// These helper callbacks are placed in an anonymous namespace to 1043/// permit their use as function template parameters. 1044ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1045 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1046} 1047 1048ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1049 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1050 CK_IntegralComplexCast); 1051} 1052} 1053 1054/// \brief Handle integer arithmetic conversions. Helper function of 1055/// UsualArithmeticConversions() 1056template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1057static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1058 ExprResult &RHS, QualType LHSType, 1059 QualType RHSType, bool IsCompAssign) { 1060 // The rules for this case are in C99 6.3.1.8 1061 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1062 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1063 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1064 if (LHSSigned == RHSSigned) { 1065 // Same signedness; use the higher-ranked type 1066 if (order >= 0) { 1067 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1068 return LHSType; 1069 } else if (!IsCompAssign) 1070 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1071 return RHSType; 1072 } else if (order != (LHSSigned ? 1 : -1)) { 1073 // The unsigned type has greater than or equal rank to the 1074 // signed type, so use the unsigned type 1075 if (RHSSigned) { 1076 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1077 return LHSType; 1078 } else if (!IsCompAssign) 1079 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1080 return RHSType; 1081 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1082 // The two types are different widths; if we are here, that 1083 // means the signed type is larger than the unsigned type, so 1084 // use the signed type. 1085 if (LHSSigned) { 1086 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1087 return LHSType; 1088 } else if (!IsCompAssign) 1089 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1090 return RHSType; 1091 } else { 1092 // The signed type is higher-ranked than the unsigned type, 1093 // but isn't actually any bigger (like unsigned int and long 1094 // on most 32-bit systems). Use the unsigned type corresponding 1095 // to the signed type. 1096 QualType result = 1097 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1098 RHS = (*doRHSCast)(S, RHS.take(), result); 1099 if (!IsCompAssign) 1100 LHS = (*doLHSCast)(S, LHS.take(), result); 1101 return result; 1102 } 1103} 1104 1105/// \brief Handle conversions with GCC complex int extension. Helper function 1106/// of UsualArithmeticConversions() 1107static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1108 ExprResult &RHS, QualType LHSType, 1109 QualType RHSType, 1110 bool IsCompAssign) { 1111 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1112 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1113 1114 if (LHSComplexInt && RHSComplexInt) { 1115 QualType LHSEltType = LHSComplexInt->getElementType(); 1116 QualType RHSEltType = RHSComplexInt->getElementType(); 1117 QualType ScalarType = 1118 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1119 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1120 1121 return S.Context.getComplexType(ScalarType); 1122 } 1123 1124 if (LHSComplexInt) { 1125 QualType LHSEltType = LHSComplexInt->getElementType(); 1126 QualType ScalarType = 1127 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1128 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1129 QualType ComplexType = S.Context.getComplexType(ScalarType); 1130 RHS = S.ImpCastExprToType(RHS.take(), ComplexType, 1131 CK_IntegralRealToComplex); 1132 1133 return ComplexType; 1134 } 1135 1136 assert(RHSComplexInt); 1137 1138 QualType RHSEltType = RHSComplexInt->getElementType(); 1139 QualType ScalarType = 1140 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1141 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1142 QualType ComplexType = S.Context.getComplexType(ScalarType); 1143 1144 if (!IsCompAssign) 1145 LHS = S.ImpCastExprToType(LHS.take(), ComplexType, 1146 CK_IntegralRealToComplex); 1147 return ComplexType; 1148} 1149 1150/// UsualArithmeticConversions - Performs various conversions that are common to 1151/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1152/// routine returns the first non-arithmetic type found. The client is 1153/// responsible for emitting appropriate error diagnostics. 1154QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1155 bool IsCompAssign) { 1156 if (!IsCompAssign) { 1157 LHS = UsualUnaryConversions(LHS.take()); 1158 if (LHS.isInvalid()) 1159 return QualType(); 1160 } 1161 1162 RHS = UsualUnaryConversions(RHS.take()); 1163 if (RHS.isInvalid()) 1164 return QualType(); 1165 1166 // For conversion purposes, we ignore any qualifiers. 1167 // For example, "const float" and "float" are equivalent. 1168 QualType LHSType = 1169 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1170 QualType RHSType = 1171 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1172 1173 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1174 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1175 LHSType = AtomicLHS->getValueType(); 1176 1177 // If both types are identical, no conversion is needed. 1178 if (LHSType == RHSType) 1179 return LHSType; 1180 1181 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1182 // The caller can deal with this (e.g. pointer + int). 1183 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1184 return QualType(); 1185 1186 // Apply unary and bitfield promotions to the LHS's type. 1187 QualType LHSUnpromotedType = LHSType; 1188 if (LHSType->isPromotableIntegerType()) 1189 LHSType = Context.getPromotedIntegerType(LHSType); 1190 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1191 if (!LHSBitfieldPromoteTy.isNull()) 1192 LHSType = LHSBitfieldPromoteTy; 1193 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1194 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast); 1195 1196 // If both types are identical, no conversion is needed. 1197 if (LHSType == RHSType) 1198 return LHSType; 1199 1200 // At this point, we have two different arithmetic types. 1201 1202 // Handle complex types first (C99 6.3.1.8p1). 1203 if (LHSType->isComplexType() || RHSType->isComplexType()) 1204 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1205 IsCompAssign); 1206 1207 // Now handle "real" floating types (i.e. float, double, long double). 1208 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1209 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1210 IsCompAssign); 1211 1212 // Handle GCC complex int extension. 1213 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1214 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1215 IsCompAssign); 1216 1217 // Finally, we have two differing integer types. 1218 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1219 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1220} 1221 1222 1223//===----------------------------------------------------------------------===// 1224// Semantic Analysis for various Expression Types 1225//===----------------------------------------------------------------------===// 1226 1227 1228ExprResult 1229Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1230 SourceLocation DefaultLoc, 1231 SourceLocation RParenLoc, 1232 Expr *ControllingExpr, 1233 ArrayRef<ParsedType> ArgTypes, 1234 ArrayRef<Expr *> ArgExprs) { 1235 unsigned NumAssocs = ArgTypes.size(); 1236 assert(NumAssocs == ArgExprs.size()); 1237 1238 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1239 for (unsigned i = 0; i < NumAssocs; ++i) { 1240 if (ArgTypes[i]) 1241 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1242 else 1243 Types[i] = 0; 1244 } 1245 1246 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1247 ControllingExpr, 1248 llvm::makeArrayRef(Types, NumAssocs), 1249 ArgExprs); 1250 delete [] Types; 1251 return ER; 1252} 1253 1254ExprResult 1255Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1256 SourceLocation DefaultLoc, 1257 SourceLocation RParenLoc, 1258 Expr *ControllingExpr, 1259 ArrayRef<TypeSourceInfo *> Types, 1260 ArrayRef<Expr *> Exprs) { 1261 unsigned NumAssocs = Types.size(); 1262 assert(NumAssocs == Exprs.size()); 1263 if (ControllingExpr->getType()->isPlaceholderType()) { 1264 ExprResult result = CheckPlaceholderExpr(ControllingExpr); 1265 if (result.isInvalid()) return ExprError(); 1266 ControllingExpr = result.take(); 1267 } 1268 1269 bool TypeErrorFound = false, 1270 IsResultDependent = ControllingExpr->isTypeDependent(), 1271 ContainsUnexpandedParameterPack 1272 = ControllingExpr->containsUnexpandedParameterPack(); 1273 1274 for (unsigned i = 0; i < NumAssocs; ++i) { 1275 if (Exprs[i]->containsUnexpandedParameterPack()) 1276 ContainsUnexpandedParameterPack = true; 1277 1278 if (Types[i]) { 1279 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1280 ContainsUnexpandedParameterPack = true; 1281 1282 if (Types[i]->getType()->isDependentType()) { 1283 IsResultDependent = true; 1284 } else { 1285 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1286 // complete object type other than a variably modified type." 1287 unsigned D = 0; 1288 if (Types[i]->getType()->isIncompleteType()) 1289 D = diag::err_assoc_type_incomplete; 1290 else if (!Types[i]->getType()->isObjectType()) 1291 D = diag::err_assoc_type_nonobject; 1292 else if (Types[i]->getType()->isVariablyModifiedType()) 1293 D = diag::err_assoc_type_variably_modified; 1294 1295 if (D != 0) { 1296 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1297 << Types[i]->getTypeLoc().getSourceRange() 1298 << Types[i]->getType(); 1299 TypeErrorFound = true; 1300 } 1301 1302 // C11 6.5.1.1p2 "No two generic associations in the same generic 1303 // selection shall specify compatible types." 1304 for (unsigned j = i+1; j < NumAssocs; ++j) 1305 if (Types[j] && !Types[j]->getType()->isDependentType() && 1306 Context.typesAreCompatible(Types[i]->getType(), 1307 Types[j]->getType())) { 1308 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1309 diag::err_assoc_compatible_types) 1310 << Types[j]->getTypeLoc().getSourceRange() 1311 << Types[j]->getType() 1312 << Types[i]->getType(); 1313 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1314 diag::note_compat_assoc) 1315 << Types[i]->getTypeLoc().getSourceRange() 1316 << Types[i]->getType(); 1317 TypeErrorFound = true; 1318 } 1319 } 1320 } 1321 } 1322 if (TypeErrorFound) 1323 return ExprError(); 1324 1325 // If we determined that the generic selection is result-dependent, don't 1326 // try to compute the result expression. 1327 if (IsResultDependent) 1328 return Owned(new (Context) GenericSelectionExpr( 1329 Context, KeyLoc, ControllingExpr, 1330 Types, Exprs, 1331 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack)); 1332 1333 SmallVector<unsigned, 1> CompatIndices; 1334 unsigned DefaultIndex = -1U; 1335 for (unsigned i = 0; i < NumAssocs; ++i) { 1336 if (!Types[i]) 1337 DefaultIndex = i; 1338 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1339 Types[i]->getType())) 1340 CompatIndices.push_back(i); 1341 } 1342 1343 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1344 // type compatible with at most one of the types named in its generic 1345 // association list." 1346 if (CompatIndices.size() > 1) { 1347 // We strip parens here because the controlling expression is typically 1348 // parenthesized in macro definitions. 1349 ControllingExpr = ControllingExpr->IgnoreParens(); 1350 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1351 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1352 << (unsigned) CompatIndices.size(); 1353 for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(), 1354 E = CompatIndices.end(); I != E; ++I) { 1355 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1356 diag::note_compat_assoc) 1357 << Types[*I]->getTypeLoc().getSourceRange() 1358 << Types[*I]->getType(); 1359 } 1360 return ExprError(); 1361 } 1362 1363 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1364 // its controlling expression shall have type compatible with exactly one of 1365 // the types named in its generic association list." 1366 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1367 // We strip parens here because the controlling expression is typically 1368 // parenthesized in macro definitions. 1369 ControllingExpr = ControllingExpr->IgnoreParens(); 1370 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1371 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1372 return ExprError(); 1373 } 1374 1375 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1376 // type name that is compatible with the type of the controlling expression, 1377 // then the result expression of the generic selection is the expression 1378 // in that generic association. Otherwise, the result expression of the 1379 // generic selection is the expression in the default generic association." 1380 unsigned ResultIndex = 1381 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1382 1383 return Owned(new (Context) GenericSelectionExpr( 1384 Context, KeyLoc, ControllingExpr, 1385 Types, Exprs, 1386 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack, 1387 ResultIndex)); 1388} 1389 1390/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1391/// location of the token and the offset of the ud-suffix within it. 1392static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1393 unsigned Offset) { 1394 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1395 S.getLangOpts()); 1396} 1397 1398/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1399/// the corresponding cooked (non-raw) literal operator, and build a call to it. 1400static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1401 IdentifierInfo *UDSuffix, 1402 SourceLocation UDSuffixLoc, 1403 ArrayRef<Expr*> Args, 1404 SourceLocation LitEndLoc) { 1405 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1406 1407 QualType ArgTy[2]; 1408 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1409 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1410 if (ArgTy[ArgIdx]->isArrayType()) 1411 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1412 } 1413 1414 DeclarationName OpName = 1415 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1416 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1417 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1418 1419 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1420 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1421 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error) 1422 return ExprError(); 1423 1424 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1425} 1426 1427/// ActOnStringLiteral - The specified tokens were lexed as pasted string 1428/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1429/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1430/// multiple tokens. However, the common case is that StringToks points to one 1431/// string. 1432/// 1433ExprResult 1434Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks, 1435 Scope *UDLScope) { 1436 assert(NumStringToks && "Must have at least one string!"); 1437 1438 StringLiteralParser Literal(StringToks, NumStringToks, PP); 1439 if (Literal.hadError) 1440 return ExprError(); 1441 1442 SmallVector<SourceLocation, 4> StringTokLocs; 1443 for (unsigned i = 0; i != NumStringToks; ++i) 1444 StringTokLocs.push_back(StringToks[i].getLocation()); 1445 1446 QualType StrTy = Context.CharTy; 1447 if (Literal.isWide()) 1448 StrTy = Context.getWideCharType(); 1449 else if (Literal.isUTF16()) 1450 StrTy = Context.Char16Ty; 1451 else if (Literal.isUTF32()) 1452 StrTy = Context.Char32Ty; 1453 else if (Literal.isPascal()) 1454 StrTy = Context.UnsignedCharTy; 1455 1456 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1457 if (Literal.isWide()) 1458 Kind = StringLiteral::Wide; 1459 else if (Literal.isUTF8()) 1460 Kind = StringLiteral::UTF8; 1461 else if (Literal.isUTF16()) 1462 Kind = StringLiteral::UTF16; 1463 else if (Literal.isUTF32()) 1464 Kind = StringLiteral::UTF32; 1465 1466 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1467 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1468 StrTy.addConst(); 1469 1470 // Get an array type for the string, according to C99 6.4.5. This includes 1471 // the nul terminator character as well as the string length for pascal 1472 // strings. 1473 StrTy = Context.getConstantArrayType(StrTy, 1474 llvm::APInt(32, Literal.GetNumStringChars()+1), 1475 ArrayType::Normal, 0); 1476 1477 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1478 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1479 Kind, Literal.Pascal, StrTy, 1480 &StringTokLocs[0], 1481 StringTokLocs.size()); 1482 if (Literal.getUDSuffix().empty()) 1483 return Owned(Lit); 1484 1485 // We're building a user-defined literal. 1486 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1487 SourceLocation UDSuffixLoc = 1488 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1489 Literal.getUDSuffixOffset()); 1490 1491 // Make sure we're allowed user-defined literals here. 1492 if (!UDLScope) 1493 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1494 1495 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1496 // operator "" X (str, len) 1497 QualType SizeType = Context.getSizeType(); 1498 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1499 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1500 StringTokLocs[0]); 1501 Expr *Args[] = { Lit, LenArg }; 1502 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 1503 Args, StringTokLocs.back()); 1504} 1505 1506ExprResult 1507Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1508 SourceLocation Loc, 1509 const CXXScopeSpec *SS) { 1510 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1511 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1512} 1513 1514/// BuildDeclRefExpr - Build an expression that references a 1515/// declaration that does not require a closure capture. 1516ExprResult 1517Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1518 const DeclarationNameInfo &NameInfo, 1519 const CXXScopeSpec *SS, NamedDecl *FoundD) { 1520 if (getLangOpts().CUDA) 1521 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1522 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1523 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller), 1524 CalleeTarget = IdentifyCUDATarget(Callee); 1525 if (CheckCUDATarget(CallerTarget, CalleeTarget)) { 1526 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1527 << CalleeTarget << D->getIdentifier() << CallerTarget; 1528 Diag(D->getLocation(), diag::note_previous_decl) 1529 << D->getIdentifier(); 1530 return ExprError(); 1531 } 1532 } 1533 1534 bool refersToEnclosingScope = 1535 (CurContext != D->getDeclContext() && 1536 D->getDeclContext()->isFunctionOrMethod()); 1537 1538 DeclRefExpr *E = DeclRefExpr::Create(Context, 1539 SS ? SS->getWithLocInContext(Context) 1540 : NestedNameSpecifierLoc(), 1541 SourceLocation(), 1542 D, refersToEnclosingScope, 1543 NameInfo, Ty, VK, FoundD); 1544 1545 MarkDeclRefReferenced(E); 1546 1547 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) && 1548 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) { 1549 DiagnosticsEngine::Level Level = 1550 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 1551 E->getLocStart()); 1552 if (Level != DiagnosticsEngine::Ignored) 1553 recordUseOfEvaluatedWeak(E); 1554 } 1555 1556 // Just in case we're building an illegal pointer-to-member. 1557 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1558 if (FD && FD->isBitField()) 1559 E->setObjectKind(OK_BitField); 1560 1561 return Owned(E); 1562} 1563 1564/// Decomposes the given name into a DeclarationNameInfo, its location, and 1565/// possibly a list of template arguments. 1566/// 1567/// If this produces template arguments, it is permitted to call 1568/// DecomposeTemplateName. 1569/// 1570/// This actually loses a lot of source location information for 1571/// non-standard name kinds; we should consider preserving that in 1572/// some way. 1573void 1574Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1575 TemplateArgumentListInfo &Buffer, 1576 DeclarationNameInfo &NameInfo, 1577 const TemplateArgumentListInfo *&TemplateArgs) { 1578 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1579 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1580 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1581 1582 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1583 Id.TemplateId->NumArgs); 1584 translateTemplateArguments(TemplateArgsPtr, Buffer); 1585 1586 TemplateName TName = Id.TemplateId->Template.get(); 1587 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1588 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1589 TemplateArgs = &Buffer; 1590 } else { 1591 NameInfo = GetNameFromUnqualifiedId(Id); 1592 TemplateArgs = 0; 1593 } 1594} 1595 1596/// Diagnose an empty lookup. 1597/// 1598/// \return false if new lookup candidates were found 1599bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1600 CorrectionCandidateCallback &CCC, 1601 TemplateArgumentListInfo *ExplicitTemplateArgs, 1602 llvm::ArrayRef<Expr *> Args) { 1603 DeclarationName Name = R.getLookupName(); 1604 1605 unsigned diagnostic = diag::err_undeclared_var_use; 1606 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1607 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1608 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1609 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1610 diagnostic = diag::err_undeclared_use; 1611 diagnostic_suggest = diag::err_undeclared_use_suggest; 1612 } 1613 1614 // If the original lookup was an unqualified lookup, fake an 1615 // unqualified lookup. This is useful when (for example) the 1616 // original lookup would not have found something because it was a 1617 // dependent name. 1618 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty()) 1619 ? CurContext : 0; 1620 while (DC) { 1621 if (isa<CXXRecordDecl>(DC)) { 1622 LookupQualifiedName(R, DC); 1623 1624 if (!R.empty()) { 1625 // Don't give errors about ambiguities in this lookup. 1626 R.suppressDiagnostics(); 1627 1628 // During a default argument instantiation the CurContext points 1629 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1630 // function parameter list, hence add an explicit check. 1631 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1632 ActiveTemplateInstantiations.back().Kind == 1633 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1634 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1635 bool isInstance = CurMethod && 1636 CurMethod->isInstance() && 1637 DC == CurMethod->getParent() && !isDefaultArgument; 1638 1639 1640 // Give a code modification hint to insert 'this->'. 1641 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1642 // Actually quite difficult! 1643 if (getLangOpts().MicrosoftMode) 1644 diagnostic = diag::warn_found_via_dependent_bases_lookup; 1645 if (isInstance) { 1646 Diag(R.getNameLoc(), diagnostic) << Name 1647 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1648 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 1649 CallsUndergoingInstantiation.back()->getCallee()); 1650 1651 CXXMethodDecl *DepMethod; 1652 if (CurMethod->isDependentContext()) 1653 DepMethod = CurMethod; 1654 else if (CurMethod->getTemplatedKind() == 1655 FunctionDecl::TK_FunctionTemplateSpecialization) 1656 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()-> 1657 getInstantiatedFromMemberTemplate()->getTemplatedDecl()); 1658 else 1659 DepMethod = cast<CXXMethodDecl>( 1660 CurMethod->getInstantiatedFromMemberFunction()); 1661 assert(DepMethod && "No template pattern found"); 1662 1663 QualType DepThisType = DepMethod->getThisType(Context); 1664 CheckCXXThisCapture(R.getNameLoc()); 1665 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 1666 R.getNameLoc(), DepThisType, false); 1667 TemplateArgumentListInfo TList; 1668 if (ULE->hasExplicitTemplateArgs()) 1669 ULE->copyTemplateArgumentsInto(TList); 1670 1671 CXXScopeSpec SS; 1672 SS.Adopt(ULE->getQualifierLoc()); 1673 CXXDependentScopeMemberExpr *DepExpr = 1674 CXXDependentScopeMemberExpr::Create( 1675 Context, DepThis, DepThisType, true, SourceLocation(), 1676 SS.getWithLocInContext(Context), 1677 ULE->getTemplateKeywordLoc(), 0, 1678 R.getLookupNameInfo(), 1679 ULE->hasExplicitTemplateArgs() ? &TList : 0); 1680 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 1681 } else { 1682 Diag(R.getNameLoc(), diagnostic) << Name; 1683 } 1684 1685 // Do we really want to note all of these? 1686 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1687 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1688 1689 // Return true if we are inside a default argument instantiation 1690 // and the found name refers to an instance member function, otherwise 1691 // the function calling DiagnoseEmptyLookup will try to create an 1692 // implicit member call and this is wrong for default argument. 1693 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1694 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1695 return true; 1696 } 1697 1698 // Tell the callee to try to recover. 1699 return false; 1700 } 1701 1702 R.clear(); 1703 } 1704 1705 // In Microsoft mode, if we are performing lookup from within a friend 1706 // function definition declared at class scope then we must set 1707 // DC to the lexical parent to be able to search into the parent 1708 // class. 1709 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) && 1710 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1711 DC->getLexicalParent()->isRecord()) 1712 DC = DC->getLexicalParent(); 1713 else 1714 DC = DC->getParent(); 1715 } 1716 1717 // We didn't find anything, so try to correct for a typo. 1718 TypoCorrection Corrected; 1719 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 1720 S, &SS, CCC))) { 1721 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1722 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts())); 1723 bool droppedSpecifier = 1724 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1725 R.setLookupName(Corrected.getCorrection()); 1726 1727 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 1728 if (Corrected.isOverloaded()) { 1729 OverloadCandidateSet OCS(R.getNameLoc()); 1730 OverloadCandidateSet::iterator Best; 1731 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1732 CDEnd = Corrected.end(); 1733 CD != CDEnd; ++CD) { 1734 if (FunctionTemplateDecl *FTD = 1735 dyn_cast<FunctionTemplateDecl>(*CD)) 1736 AddTemplateOverloadCandidate( 1737 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1738 Args, OCS); 1739 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1740 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1741 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1742 Args, OCS); 1743 } 1744 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1745 case OR_Success: 1746 ND = Best->Function; 1747 break; 1748 default: 1749 break; 1750 } 1751 } 1752 R.addDecl(ND); 1753 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 1754 if (SS.isEmpty()) 1755 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr 1756 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1757 else 1758 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1759 << Name << computeDeclContext(SS, false) << droppedSpecifier 1760 << CorrectedQuotedStr << SS.getRange() 1761 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(), 1762 CorrectedStr); 1763 1764 unsigned diag = isa<ImplicitParamDecl>(ND) 1765 ? diag::note_implicit_param_decl 1766 : diag::note_previous_decl; 1767 1768 Diag(ND->getLocation(), diag) 1769 << CorrectedQuotedStr; 1770 1771 // Tell the callee to try to recover. 1772 return false; 1773 } 1774 1775 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) { 1776 // FIXME: If we ended up with a typo for a type name or 1777 // Objective-C class name, we're in trouble because the parser 1778 // is in the wrong place to recover. Suggest the typo 1779 // correction, but don't make it a fix-it since we're not going 1780 // to recover well anyway. 1781 if (SS.isEmpty()) 1782 Diag(R.getNameLoc(), diagnostic_suggest) 1783 << Name << CorrectedQuotedStr; 1784 else 1785 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1786 << Name << computeDeclContext(SS, false) << droppedSpecifier 1787 << CorrectedQuotedStr << SS.getRange(); 1788 1789 // Don't try to recover; it won't work. 1790 return true; 1791 } 1792 } else { 1793 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1794 // because we aren't able to recover. 1795 if (SS.isEmpty()) 1796 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr; 1797 else 1798 Diag(R.getNameLoc(), diag::err_no_member_suggest) 1799 << Name << computeDeclContext(SS, false) << droppedSpecifier 1800 << CorrectedQuotedStr << SS.getRange(); 1801 return true; 1802 } 1803 } 1804 R.clear(); 1805 1806 // Emit a special diagnostic for failed member lookups. 1807 // FIXME: computing the declaration context might fail here (?) 1808 if (!SS.isEmpty()) { 1809 Diag(R.getNameLoc(), diag::err_no_member) 1810 << Name << computeDeclContext(SS, false) 1811 << SS.getRange(); 1812 return true; 1813 } 1814 1815 // Give up, we can't recover. 1816 Diag(R.getNameLoc(), diagnostic) << Name; 1817 return true; 1818} 1819 1820ExprResult Sema::ActOnIdExpression(Scope *S, 1821 CXXScopeSpec &SS, 1822 SourceLocation TemplateKWLoc, 1823 UnqualifiedId &Id, 1824 bool HasTrailingLParen, 1825 bool IsAddressOfOperand, 1826 CorrectionCandidateCallback *CCC, 1827 bool IsInlineAsmIdentifier) { 1828 assert(!(IsAddressOfOperand && HasTrailingLParen) && 1829 "cannot be direct & operand and have a trailing lparen"); 1830 1831 if (SS.isInvalid()) 1832 return ExprError(); 1833 1834 TemplateArgumentListInfo TemplateArgsBuffer; 1835 1836 // Decompose the UnqualifiedId into the following data. 1837 DeclarationNameInfo NameInfo; 1838 const TemplateArgumentListInfo *TemplateArgs; 1839 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 1840 1841 DeclarationName Name = NameInfo.getName(); 1842 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1843 SourceLocation NameLoc = NameInfo.getLoc(); 1844 1845 // C++ [temp.dep.expr]p3: 1846 // An id-expression is type-dependent if it contains: 1847 // -- an identifier that was declared with a dependent type, 1848 // (note: handled after lookup) 1849 // -- a template-id that is dependent, 1850 // (note: handled in BuildTemplateIdExpr) 1851 // -- a conversion-function-id that specifies a dependent type, 1852 // -- a nested-name-specifier that contains a class-name that 1853 // names a dependent type. 1854 // Determine whether this is a member of an unknown specialization; 1855 // we need to handle these differently. 1856 bool DependentID = false; 1857 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 1858 Name.getCXXNameType()->isDependentType()) { 1859 DependentID = true; 1860 } else if (SS.isSet()) { 1861 if (DeclContext *DC = computeDeclContext(SS, false)) { 1862 if (RequireCompleteDeclContext(SS, DC)) 1863 return ExprError(); 1864 } else { 1865 DependentID = true; 1866 } 1867 } 1868 1869 if (DependentID) 1870 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1871 IsAddressOfOperand, TemplateArgs); 1872 1873 // Perform the required lookup. 1874 LookupResult R(*this, NameInfo, 1875 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 1876 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 1877 if (TemplateArgs) { 1878 // Lookup the template name again to correctly establish the context in 1879 // which it was found. This is really unfortunate as we already did the 1880 // lookup to determine that it was a template name in the first place. If 1881 // this becomes a performance hit, we can work harder to preserve those 1882 // results until we get here but it's likely not worth it. 1883 bool MemberOfUnknownSpecialization; 1884 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 1885 MemberOfUnknownSpecialization); 1886 1887 if (MemberOfUnknownSpecialization || 1888 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 1889 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1890 IsAddressOfOperand, TemplateArgs); 1891 } else { 1892 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 1893 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 1894 1895 // If the result might be in a dependent base class, this is a dependent 1896 // id-expression. 1897 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 1898 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1899 IsAddressOfOperand, TemplateArgs); 1900 1901 // If this reference is in an Objective-C method, then we need to do 1902 // some special Objective-C lookup, too. 1903 if (IvarLookupFollowUp) { 1904 ExprResult E(LookupInObjCMethod(R, S, II, true)); 1905 if (E.isInvalid()) 1906 return ExprError(); 1907 1908 if (Expr *Ex = E.takeAs<Expr>()) 1909 return Owned(Ex); 1910 } 1911 } 1912 1913 if (R.isAmbiguous()) 1914 return ExprError(); 1915 1916 // Determine whether this name might be a candidate for 1917 // argument-dependent lookup. 1918 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 1919 1920 if (R.empty() && !ADL) { 1921 // Otherwise, this could be an implicitly declared function reference (legal 1922 // in C90, extension in C99, forbidden in C++). 1923 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 1924 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 1925 if (D) R.addDecl(D); 1926 } 1927 1928 // If this name wasn't predeclared and if this is not a function 1929 // call, diagnose the problem. 1930 if (R.empty()) { 1931 // In Microsoft mode, if we are inside a template class member function 1932 // whose parent class has dependent base classes, and we can't resolve 1933 // an identifier, then assume the identifier is type dependent. The 1934 // goal is to postpone name lookup to instantiation time to be able to 1935 // search into the type dependent base classes. 1936 if (getLangOpts().MicrosoftMode) { 1937 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext); 1938 if (MD && MD->getParent()->hasAnyDependentBases()) 1939 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1940 IsAddressOfOperand, TemplateArgs); 1941 } 1942 1943 // Don't diagnose an empty lookup for inline assmebly. 1944 if (IsInlineAsmIdentifier) 1945 return ExprError(); 1946 1947 CorrectionCandidateCallback DefaultValidator; 1948 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator)) 1949 return ExprError(); 1950 1951 assert(!R.empty() && 1952 "DiagnoseEmptyLookup returned false but added no results"); 1953 1954 // If we found an Objective-C instance variable, let 1955 // LookupInObjCMethod build the appropriate expression to 1956 // reference the ivar. 1957 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 1958 R.clear(); 1959 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 1960 // In a hopelessly buggy code, Objective-C instance variable 1961 // lookup fails and no expression will be built to reference it. 1962 if (!E.isInvalid() && !E.get()) 1963 return ExprError(); 1964 return E; 1965 } 1966 } 1967 } 1968 1969 // This is guaranteed from this point on. 1970 assert(!R.empty() || ADL); 1971 1972 // Check whether this might be a C++ implicit instance member access. 1973 // C++ [class.mfct.non-static]p3: 1974 // When an id-expression that is not part of a class member access 1975 // syntax and not used to form a pointer to member is used in the 1976 // body of a non-static member function of class X, if name lookup 1977 // resolves the name in the id-expression to a non-static non-type 1978 // member of some class C, the id-expression is transformed into a 1979 // class member access expression using (*this) as the 1980 // postfix-expression to the left of the . operator. 1981 // 1982 // But we don't actually need to do this for '&' operands if R 1983 // resolved to a function or overloaded function set, because the 1984 // expression is ill-formed if it actually works out to be a 1985 // non-static member function: 1986 // 1987 // C++ [expr.ref]p4: 1988 // Otherwise, if E1.E2 refers to a non-static member function. . . 1989 // [t]he expression can be used only as the left-hand operand of a 1990 // member function call. 1991 // 1992 // There are other safeguards against such uses, but it's important 1993 // to get this right here so that we don't end up making a 1994 // spuriously dependent expression if we're inside a dependent 1995 // instance method. 1996 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 1997 bool MightBeImplicitMember; 1998 if (!IsAddressOfOperand) 1999 MightBeImplicitMember = true; 2000 else if (!SS.isEmpty()) 2001 MightBeImplicitMember = false; 2002 else if (R.isOverloadedResult()) 2003 MightBeImplicitMember = false; 2004 else if (R.isUnresolvableResult()) 2005 MightBeImplicitMember = true; 2006 else 2007 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2008 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2009 isa<MSPropertyDecl>(R.getFoundDecl()); 2010 2011 if (MightBeImplicitMember) 2012 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2013 R, TemplateArgs); 2014 } 2015 2016 if (TemplateArgs || TemplateKWLoc.isValid()) 2017 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2018 2019 return BuildDeclarationNameExpr(SS, R, ADL); 2020} 2021 2022/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2023/// declaration name, generally during template instantiation. 2024/// There's a large number of things which don't need to be done along 2025/// this path. 2026ExprResult 2027Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 2028 const DeclarationNameInfo &NameInfo, 2029 bool IsAddressOfOperand) { 2030 DeclContext *DC = computeDeclContext(SS, false); 2031 if (!DC) 2032 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2033 NameInfo, /*TemplateArgs=*/0); 2034 2035 if (RequireCompleteDeclContext(SS, DC)) 2036 return ExprError(); 2037 2038 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2039 LookupQualifiedName(R, DC); 2040 2041 if (R.isAmbiguous()) 2042 return ExprError(); 2043 2044 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2045 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2046 NameInfo, /*TemplateArgs=*/0); 2047 2048 if (R.empty()) { 2049 Diag(NameInfo.getLoc(), diag::err_no_member) 2050 << NameInfo.getName() << DC << SS.getRange(); 2051 return ExprError(); 2052 } 2053 2054 // Defend against this resolving to an implicit member access. We usually 2055 // won't get here if this might be a legitimate a class member (we end up in 2056 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2057 // a pointer-to-member or in an unevaluated context in C++11. 2058 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2059 return BuildPossibleImplicitMemberExpr(SS, 2060 /*TemplateKWLoc=*/SourceLocation(), 2061 R, /*TemplateArgs=*/0); 2062 2063 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2064} 2065 2066/// LookupInObjCMethod - The parser has read a name in, and Sema has 2067/// detected that we're currently inside an ObjC method. Perform some 2068/// additional lookup. 2069/// 2070/// Ideally, most of this would be done by lookup, but there's 2071/// actually quite a lot of extra work involved. 2072/// 2073/// Returns a null sentinel to indicate trivial success. 2074ExprResult 2075Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2076 IdentifierInfo *II, bool AllowBuiltinCreation) { 2077 SourceLocation Loc = Lookup.getNameLoc(); 2078 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2079 2080 // Check for error condition which is already reported. 2081 if (!CurMethod) 2082 return ExprError(); 2083 2084 // There are two cases to handle here. 1) scoped lookup could have failed, 2085 // in which case we should look for an ivar. 2) scoped lookup could have 2086 // found a decl, but that decl is outside the current instance method (i.e. 2087 // a global variable). In these two cases, we do a lookup for an ivar with 2088 // this name, if the lookup sucedes, we replace it our current decl. 2089 2090 // If we're in a class method, we don't normally want to look for 2091 // ivars. But if we don't find anything else, and there's an 2092 // ivar, that's an error. 2093 bool IsClassMethod = CurMethod->isClassMethod(); 2094 2095 bool LookForIvars; 2096 if (Lookup.empty()) 2097 LookForIvars = true; 2098 else if (IsClassMethod) 2099 LookForIvars = false; 2100 else 2101 LookForIvars = (Lookup.isSingleResult() && 2102 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2103 ObjCInterfaceDecl *IFace = 0; 2104 if (LookForIvars) { 2105 IFace = CurMethod->getClassInterface(); 2106 ObjCInterfaceDecl *ClassDeclared; 2107 ObjCIvarDecl *IV = 0; 2108 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2109 // Diagnose using an ivar in a class method. 2110 if (IsClassMethod) 2111 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2112 << IV->getDeclName()); 2113 2114 // If we're referencing an invalid decl, just return this as a silent 2115 // error node. The error diagnostic was already emitted on the decl. 2116 if (IV->isInvalidDecl()) 2117 return ExprError(); 2118 2119 // Check if referencing a field with __attribute__((deprecated)). 2120 if (DiagnoseUseOfDecl(IV, Loc)) 2121 return ExprError(); 2122 2123 // Diagnose the use of an ivar outside of the declaring class. 2124 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2125 !declaresSameEntity(ClassDeclared, IFace) && 2126 !getLangOpts().DebuggerSupport) 2127 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2128 2129 // FIXME: This should use a new expr for a direct reference, don't 2130 // turn this into Self->ivar, just return a BareIVarExpr or something. 2131 IdentifierInfo &II = Context.Idents.get("self"); 2132 UnqualifiedId SelfName; 2133 SelfName.setIdentifier(&II, SourceLocation()); 2134 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2135 CXXScopeSpec SelfScopeSpec; 2136 SourceLocation TemplateKWLoc; 2137 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2138 SelfName, false, false); 2139 if (SelfExpr.isInvalid()) 2140 return ExprError(); 2141 2142 SelfExpr = DefaultLvalueConversion(SelfExpr.take()); 2143 if (SelfExpr.isInvalid()) 2144 return ExprError(); 2145 2146 MarkAnyDeclReferenced(Loc, IV, true); 2147 2148 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2149 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2150 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2151 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2152 2153 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(), 2154 Loc, IV->getLocation(), 2155 SelfExpr.take(), 2156 true, true); 2157 2158 if (getLangOpts().ObjCAutoRefCount) { 2159 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2160 DiagnosticsEngine::Level Level = 2161 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc); 2162 if (Level != DiagnosticsEngine::Ignored) 2163 recordUseOfEvaluatedWeak(Result); 2164 } 2165 if (CurContext->isClosure()) 2166 Diag(Loc, diag::warn_implicitly_retains_self) 2167 << FixItHint::CreateInsertion(Loc, "self->"); 2168 } 2169 2170 return Owned(Result); 2171 } 2172 } else if (CurMethod->isInstanceMethod()) { 2173 // We should warn if a local variable hides an ivar. 2174 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2175 ObjCInterfaceDecl *ClassDeclared; 2176 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2177 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2178 declaresSameEntity(IFace, ClassDeclared)) 2179 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2180 } 2181 } 2182 } else if (Lookup.isSingleResult() && 2183 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2184 // If accessing a stand-alone ivar in a class method, this is an error. 2185 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2186 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2187 << IV->getDeclName()); 2188 } 2189 2190 if (Lookup.empty() && II && AllowBuiltinCreation) { 2191 // FIXME. Consolidate this with similar code in LookupName. 2192 if (unsigned BuiltinID = II->getBuiltinID()) { 2193 if (!(getLangOpts().CPlusPlus && 2194 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2195 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2196 S, Lookup.isForRedeclaration(), 2197 Lookup.getNameLoc()); 2198 if (D) Lookup.addDecl(D); 2199 } 2200 } 2201 } 2202 // Sentinel value saying that we didn't do anything special. 2203 return Owned((Expr*) 0); 2204} 2205 2206/// \brief Cast a base object to a member's actual type. 2207/// 2208/// Logically this happens in three phases: 2209/// 2210/// * First we cast from the base type to the naming class. 2211/// The naming class is the class into which we were looking 2212/// when we found the member; it's the qualifier type if a 2213/// qualifier was provided, and otherwise it's the base type. 2214/// 2215/// * Next we cast from the naming class to the declaring class. 2216/// If the member we found was brought into a class's scope by 2217/// a using declaration, this is that class; otherwise it's 2218/// the class declaring the member. 2219/// 2220/// * Finally we cast from the declaring class to the "true" 2221/// declaring class of the member. This conversion does not 2222/// obey access control. 2223ExprResult 2224Sema::PerformObjectMemberConversion(Expr *From, 2225 NestedNameSpecifier *Qualifier, 2226 NamedDecl *FoundDecl, 2227 NamedDecl *Member) { 2228 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2229 if (!RD) 2230 return Owned(From); 2231 2232 QualType DestRecordType; 2233 QualType DestType; 2234 QualType FromRecordType; 2235 QualType FromType = From->getType(); 2236 bool PointerConversions = false; 2237 if (isa<FieldDecl>(Member)) { 2238 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2239 2240 if (FromType->getAs<PointerType>()) { 2241 DestType = Context.getPointerType(DestRecordType); 2242 FromRecordType = FromType->getPointeeType(); 2243 PointerConversions = true; 2244 } else { 2245 DestType = DestRecordType; 2246 FromRecordType = FromType; 2247 } 2248 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2249 if (Method->isStatic()) 2250 return Owned(From); 2251 2252 DestType = Method->getThisType(Context); 2253 DestRecordType = DestType->getPointeeType(); 2254 2255 if (FromType->getAs<PointerType>()) { 2256 FromRecordType = FromType->getPointeeType(); 2257 PointerConversions = true; 2258 } else { 2259 FromRecordType = FromType; 2260 DestType = DestRecordType; 2261 } 2262 } else { 2263 // No conversion necessary. 2264 return Owned(From); 2265 } 2266 2267 if (DestType->isDependentType() || FromType->isDependentType()) 2268 return Owned(From); 2269 2270 // If the unqualified types are the same, no conversion is necessary. 2271 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2272 return Owned(From); 2273 2274 SourceRange FromRange = From->getSourceRange(); 2275 SourceLocation FromLoc = FromRange.getBegin(); 2276 2277 ExprValueKind VK = From->getValueKind(); 2278 2279 // C++ [class.member.lookup]p8: 2280 // [...] Ambiguities can often be resolved by qualifying a name with its 2281 // class name. 2282 // 2283 // If the member was a qualified name and the qualified referred to a 2284 // specific base subobject type, we'll cast to that intermediate type 2285 // first and then to the object in which the member is declared. That allows 2286 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2287 // 2288 // class Base { public: int x; }; 2289 // class Derived1 : public Base { }; 2290 // class Derived2 : public Base { }; 2291 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2292 // 2293 // void VeryDerived::f() { 2294 // x = 17; // error: ambiguous base subobjects 2295 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2296 // } 2297 if (Qualifier) { 2298 QualType QType = QualType(Qualifier->getAsType(), 0); 2299 assert(!QType.isNull() && "lookup done with dependent qualifier?"); 2300 assert(QType->isRecordType() && "lookup done with non-record type"); 2301 2302 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2303 2304 // In C++98, the qualifier type doesn't actually have to be a base 2305 // type of the object type, in which case we just ignore it. 2306 // Otherwise build the appropriate casts. 2307 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2308 CXXCastPath BasePath; 2309 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2310 FromLoc, FromRange, &BasePath)) 2311 return ExprError(); 2312 2313 if (PointerConversions) 2314 QType = Context.getPointerType(QType); 2315 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2316 VK, &BasePath).take(); 2317 2318 FromType = QType; 2319 FromRecordType = QRecordType; 2320 2321 // If the qualifier type was the same as the destination type, 2322 // we're done. 2323 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2324 return Owned(From); 2325 } 2326 } 2327 2328 bool IgnoreAccess = false; 2329 2330 // If we actually found the member through a using declaration, cast 2331 // down to the using declaration's type. 2332 // 2333 // Pointer equality is fine here because only one declaration of a 2334 // class ever has member declarations. 2335 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2336 assert(isa<UsingShadowDecl>(FoundDecl)); 2337 QualType URecordType = Context.getTypeDeclType( 2338 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2339 2340 // We only need to do this if the naming-class to declaring-class 2341 // conversion is non-trivial. 2342 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2343 assert(IsDerivedFrom(FromRecordType, URecordType)); 2344 CXXCastPath BasePath; 2345 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2346 FromLoc, FromRange, &BasePath)) 2347 return ExprError(); 2348 2349 QualType UType = URecordType; 2350 if (PointerConversions) 2351 UType = Context.getPointerType(UType); 2352 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2353 VK, &BasePath).take(); 2354 FromType = UType; 2355 FromRecordType = URecordType; 2356 } 2357 2358 // We don't do access control for the conversion from the 2359 // declaring class to the true declaring class. 2360 IgnoreAccess = true; 2361 } 2362 2363 CXXCastPath BasePath; 2364 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2365 FromLoc, FromRange, &BasePath, 2366 IgnoreAccess)) 2367 return ExprError(); 2368 2369 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2370 VK, &BasePath); 2371} 2372 2373bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2374 const LookupResult &R, 2375 bool HasTrailingLParen) { 2376 // Only when used directly as the postfix-expression of a call. 2377 if (!HasTrailingLParen) 2378 return false; 2379 2380 // Never if a scope specifier was provided. 2381 if (SS.isSet()) 2382 return false; 2383 2384 // Only in C++ or ObjC++. 2385 if (!getLangOpts().CPlusPlus) 2386 return false; 2387 2388 // Turn off ADL when we find certain kinds of declarations during 2389 // normal lookup: 2390 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2391 NamedDecl *D = *I; 2392 2393 // C++0x [basic.lookup.argdep]p3: 2394 // -- a declaration of a class member 2395 // Since using decls preserve this property, we check this on the 2396 // original decl. 2397 if (D->isCXXClassMember()) 2398 return false; 2399 2400 // C++0x [basic.lookup.argdep]p3: 2401 // -- a block-scope function declaration that is not a 2402 // using-declaration 2403 // NOTE: we also trigger this for function templates (in fact, we 2404 // don't check the decl type at all, since all other decl types 2405 // turn off ADL anyway). 2406 if (isa<UsingShadowDecl>(D)) 2407 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2408 else if (D->getDeclContext()->isFunctionOrMethod()) 2409 return false; 2410 2411 // C++0x [basic.lookup.argdep]p3: 2412 // -- a declaration that is neither a function or a function 2413 // template 2414 // And also for builtin functions. 2415 if (isa<FunctionDecl>(D)) { 2416 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2417 2418 // But also builtin functions. 2419 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2420 return false; 2421 } else if (!isa<FunctionTemplateDecl>(D)) 2422 return false; 2423 } 2424 2425 return true; 2426} 2427 2428 2429/// Diagnoses obvious problems with the use of the given declaration 2430/// as an expression. This is only actually called for lookups that 2431/// were not overloaded, and it doesn't promise that the declaration 2432/// will in fact be used. 2433static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2434 if (isa<TypedefNameDecl>(D)) { 2435 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2436 return true; 2437 } 2438 2439 if (isa<ObjCInterfaceDecl>(D)) { 2440 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2441 return true; 2442 } 2443 2444 if (isa<NamespaceDecl>(D)) { 2445 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2446 return true; 2447 } 2448 2449 return false; 2450} 2451 2452ExprResult 2453Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2454 LookupResult &R, 2455 bool NeedsADL) { 2456 // If this is a single, fully-resolved result and we don't need ADL, 2457 // just build an ordinary singleton decl ref. 2458 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2459 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2460 R.getRepresentativeDecl()); 2461 2462 // We only need to check the declaration if there's exactly one 2463 // result, because in the overloaded case the results can only be 2464 // functions and function templates. 2465 if (R.isSingleResult() && 2466 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2467 return ExprError(); 2468 2469 // Otherwise, just build an unresolved lookup expression. Suppress 2470 // any lookup-related diagnostics; we'll hash these out later, when 2471 // we've picked a target. 2472 R.suppressDiagnostics(); 2473 2474 UnresolvedLookupExpr *ULE 2475 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2476 SS.getWithLocInContext(Context), 2477 R.getLookupNameInfo(), 2478 NeedsADL, R.isOverloadedResult(), 2479 R.begin(), R.end()); 2480 2481 return Owned(ULE); 2482} 2483 2484/// \brief Complete semantic analysis for a reference to the given declaration. 2485ExprResult 2486Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2487 const DeclarationNameInfo &NameInfo, 2488 NamedDecl *D, NamedDecl *FoundD) { 2489 assert(D && "Cannot refer to a NULL declaration"); 2490 assert(!isa<FunctionTemplateDecl>(D) && 2491 "Cannot refer unambiguously to a function template"); 2492 2493 SourceLocation Loc = NameInfo.getLoc(); 2494 if (CheckDeclInExpr(*this, Loc, D)) 2495 return ExprError(); 2496 2497 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2498 // Specifically diagnose references to class templates that are missing 2499 // a template argument list. 2500 Diag(Loc, diag::err_template_decl_ref) 2501 << Template << SS.getRange(); 2502 Diag(Template->getLocation(), diag::note_template_decl_here); 2503 return ExprError(); 2504 } 2505 2506 // Make sure that we're referring to a value. 2507 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2508 if (!VD) { 2509 Diag(Loc, diag::err_ref_non_value) 2510 << D << SS.getRange(); 2511 Diag(D->getLocation(), diag::note_declared_at); 2512 return ExprError(); 2513 } 2514 2515 // Check whether this declaration can be used. Note that we suppress 2516 // this check when we're going to perform argument-dependent lookup 2517 // on this function name, because this might not be the function 2518 // that overload resolution actually selects. 2519 if (DiagnoseUseOfDecl(VD, Loc)) 2520 return ExprError(); 2521 2522 // Only create DeclRefExpr's for valid Decl's. 2523 if (VD->isInvalidDecl()) 2524 return ExprError(); 2525 2526 // Handle members of anonymous structs and unions. If we got here, 2527 // and the reference is to a class member indirect field, then this 2528 // must be the subject of a pointer-to-member expression. 2529 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2530 if (!indirectField->isCXXClassMember()) 2531 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2532 indirectField); 2533 2534 { 2535 QualType type = VD->getType(); 2536 ExprValueKind valueKind = VK_RValue; 2537 2538 switch (D->getKind()) { 2539 // Ignore all the non-ValueDecl kinds. 2540#define ABSTRACT_DECL(kind) 2541#define VALUE(type, base) 2542#define DECL(type, base) \ 2543 case Decl::type: 2544#include "clang/AST/DeclNodes.inc" 2545 llvm_unreachable("invalid value decl kind"); 2546 2547 // These shouldn't make it here. 2548 case Decl::ObjCAtDefsField: 2549 case Decl::ObjCIvar: 2550 llvm_unreachable("forming non-member reference to ivar?"); 2551 2552 // Enum constants are always r-values and never references. 2553 // Unresolved using declarations are dependent. 2554 case Decl::EnumConstant: 2555 case Decl::UnresolvedUsingValue: 2556 valueKind = VK_RValue; 2557 break; 2558 2559 // Fields and indirect fields that got here must be for 2560 // pointer-to-member expressions; we just call them l-values for 2561 // internal consistency, because this subexpression doesn't really 2562 // exist in the high-level semantics. 2563 case Decl::Field: 2564 case Decl::IndirectField: 2565 assert(getLangOpts().CPlusPlus && 2566 "building reference to field in C?"); 2567 2568 // These can't have reference type in well-formed programs, but 2569 // for internal consistency we do this anyway. 2570 type = type.getNonReferenceType(); 2571 valueKind = VK_LValue; 2572 break; 2573 2574 // Non-type template parameters are either l-values or r-values 2575 // depending on the type. 2576 case Decl::NonTypeTemplateParm: { 2577 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2578 type = reftype->getPointeeType(); 2579 valueKind = VK_LValue; // even if the parameter is an r-value reference 2580 break; 2581 } 2582 2583 // For non-references, we need to strip qualifiers just in case 2584 // the template parameter was declared as 'const int' or whatever. 2585 valueKind = VK_RValue; 2586 type = type.getUnqualifiedType(); 2587 break; 2588 } 2589 2590 case Decl::Var: 2591 // In C, "extern void blah;" is valid and is an r-value. 2592 if (!getLangOpts().CPlusPlus && 2593 !type.hasQualifiers() && 2594 type->isVoidType()) { 2595 valueKind = VK_RValue; 2596 break; 2597 } 2598 // fallthrough 2599 2600 case Decl::ImplicitParam: 2601 case Decl::ParmVar: { 2602 // These are always l-values. 2603 valueKind = VK_LValue; 2604 type = type.getNonReferenceType(); 2605 2606 // FIXME: Does the addition of const really only apply in 2607 // potentially-evaluated contexts? Since the variable isn't actually 2608 // captured in an unevaluated context, it seems that the answer is no. 2609 if (!isUnevaluatedContext()) { 2610 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2611 if (!CapturedType.isNull()) 2612 type = CapturedType; 2613 } 2614 2615 break; 2616 } 2617 2618 case Decl::Function: { 2619 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2620 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2621 type = Context.BuiltinFnTy; 2622 valueKind = VK_RValue; 2623 break; 2624 } 2625 } 2626 2627 const FunctionType *fty = type->castAs<FunctionType>(); 2628 2629 // If we're referring to a function with an __unknown_anytype 2630 // result type, make the entire expression __unknown_anytype. 2631 if (fty->getResultType() == Context.UnknownAnyTy) { 2632 type = Context.UnknownAnyTy; 2633 valueKind = VK_RValue; 2634 break; 2635 } 2636 2637 // Functions are l-values in C++. 2638 if (getLangOpts().CPlusPlus) { 2639 valueKind = VK_LValue; 2640 break; 2641 } 2642 2643 // C99 DR 316 says that, if a function type comes from a 2644 // function definition (without a prototype), that type is only 2645 // used for checking compatibility. Therefore, when referencing 2646 // the function, we pretend that we don't have the full function 2647 // type. 2648 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2649 isa<FunctionProtoType>(fty)) 2650 type = Context.getFunctionNoProtoType(fty->getResultType(), 2651 fty->getExtInfo()); 2652 2653 // Functions are r-values in C. 2654 valueKind = VK_RValue; 2655 break; 2656 } 2657 2658 case Decl::MSProperty: 2659 valueKind = VK_LValue; 2660 break; 2661 2662 case Decl::CXXMethod: 2663 // If we're referring to a method with an __unknown_anytype 2664 // result type, make the entire expression __unknown_anytype. 2665 // This should only be possible with a type written directly. 2666 if (const FunctionProtoType *proto 2667 = dyn_cast<FunctionProtoType>(VD->getType())) 2668 if (proto->getResultType() == Context.UnknownAnyTy) { 2669 type = Context.UnknownAnyTy; 2670 valueKind = VK_RValue; 2671 break; 2672 } 2673 2674 // C++ methods are l-values if static, r-values if non-static. 2675 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2676 valueKind = VK_LValue; 2677 break; 2678 } 2679 // fallthrough 2680 2681 case Decl::CXXConversion: 2682 case Decl::CXXDestructor: 2683 case Decl::CXXConstructor: 2684 valueKind = VK_RValue; 2685 break; 2686 } 2687 2688 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD); 2689 } 2690} 2691 2692ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 2693 PredefinedExpr::IdentType IT; 2694 2695 switch (Kind) { 2696 default: llvm_unreachable("Unknown simple primary expr!"); 2697 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 2698 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 2699 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 2700 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 2701 } 2702 2703 // Pre-defined identifiers are of type char[x], where x is the length of the 2704 // string. 2705 2706 Decl *currentDecl = getCurFunctionOrMethodDecl(); 2707 // Blocks and lambdas can occur at global scope. Don't emit a warning. 2708 if (!currentDecl) { 2709 if (const BlockScopeInfo *BSI = getCurBlock()) 2710 currentDecl = BSI->TheDecl; 2711 else if (const LambdaScopeInfo *LSI = getCurLambda()) 2712 currentDecl = LSI->CallOperator; 2713 } 2714 2715 if (!currentDecl) { 2716 Diag(Loc, diag::ext_predef_outside_function); 2717 currentDecl = Context.getTranslationUnitDecl(); 2718 } 2719 2720 QualType ResTy; 2721 if (cast<DeclContext>(currentDecl)->isDependentContext()) { 2722 ResTy = Context.DependentTy; 2723 } else { 2724 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 2725 2726 llvm::APInt LengthI(32, Length + 1); 2727 if (IT == PredefinedExpr::LFunction) 2728 ResTy = Context.WideCharTy.withConst(); 2729 else 2730 ResTy = Context.CharTy.withConst(); 2731 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 2732 } 2733 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 2734} 2735 2736ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 2737 SmallString<16> CharBuffer; 2738 bool Invalid = false; 2739 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 2740 if (Invalid) 2741 return ExprError(); 2742 2743 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 2744 PP, Tok.getKind()); 2745 if (Literal.hadError()) 2746 return ExprError(); 2747 2748 QualType Ty; 2749 if (Literal.isWide()) 2750 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 2751 else if (Literal.isUTF16()) 2752 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 2753 else if (Literal.isUTF32()) 2754 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 2755 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 2756 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 2757 else 2758 Ty = Context.CharTy; // 'x' -> char in C++ 2759 2760 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 2761 if (Literal.isWide()) 2762 Kind = CharacterLiteral::Wide; 2763 else if (Literal.isUTF16()) 2764 Kind = CharacterLiteral::UTF16; 2765 else if (Literal.isUTF32()) 2766 Kind = CharacterLiteral::UTF32; 2767 2768 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 2769 Tok.getLocation()); 2770 2771 if (Literal.getUDSuffix().empty()) 2772 return Owned(Lit); 2773 2774 // We're building a user-defined literal. 2775 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2776 SourceLocation UDSuffixLoc = 2777 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2778 2779 // Make sure we're allowed user-defined literals here. 2780 if (!UDLScope) 2781 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 2782 2783 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 2784 // operator "" X (ch) 2785 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 2786 Lit, Tok.getLocation()); 2787} 2788 2789ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 2790 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2791 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 2792 Context.IntTy, Loc)); 2793} 2794 2795static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 2796 QualType Ty, SourceLocation Loc) { 2797 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 2798 2799 using llvm::APFloat; 2800 APFloat Val(Format); 2801 2802 APFloat::opStatus result = Literal.GetFloatValue(Val); 2803 2804 // Overflow is always an error, but underflow is only an error if 2805 // we underflowed to zero (APFloat reports denormals as underflow). 2806 if ((result & APFloat::opOverflow) || 2807 ((result & APFloat::opUnderflow) && Val.isZero())) { 2808 unsigned diagnostic; 2809 SmallString<20> buffer; 2810 if (result & APFloat::opOverflow) { 2811 diagnostic = diag::warn_float_overflow; 2812 APFloat::getLargest(Format).toString(buffer); 2813 } else { 2814 diagnostic = diag::warn_float_underflow; 2815 APFloat::getSmallest(Format).toString(buffer); 2816 } 2817 2818 S.Diag(Loc, diagnostic) 2819 << Ty 2820 << StringRef(buffer.data(), buffer.size()); 2821 } 2822 2823 bool isExact = (result == APFloat::opOK); 2824 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 2825} 2826 2827ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 2828 // Fast path for a single digit (which is quite common). A single digit 2829 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 2830 if (Tok.getLength() == 1) { 2831 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 2832 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 2833 } 2834 2835 SmallString<128> SpellingBuffer; 2836 // NumericLiteralParser wants to overread by one character. Add padding to 2837 // the buffer in case the token is copied to the buffer. If getSpelling() 2838 // returns a StringRef to the memory buffer, it should have a null char at 2839 // the EOF, so it is also safe. 2840 SpellingBuffer.resize(Tok.getLength() + 1); 2841 2842 // Get the spelling of the token, which eliminates trigraphs, etc. 2843 bool Invalid = false; 2844 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 2845 if (Invalid) 2846 return ExprError(); 2847 2848 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 2849 if (Literal.hadError) 2850 return ExprError(); 2851 2852 if (Literal.hasUDSuffix()) { 2853 // We're building a user-defined literal. 2854 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2855 SourceLocation UDSuffixLoc = 2856 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2857 2858 // Make sure we're allowed user-defined literals here. 2859 if (!UDLScope) 2860 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 2861 2862 QualType CookedTy; 2863 if (Literal.isFloatingLiteral()) { 2864 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 2865 // long double, the literal is treated as a call of the form 2866 // operator "" X (f L) 2867 CookedTy = Context.LongDoubleTy; 2868 } else { 2869 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 2870 // unsigned long long, the literal is treated as a call of the form 2871 // operator "" X (n ULL) 2872 CookedTy = Context.UnsignedLongLongTy; 2873 } 2874 2875 DeclarationName OpName = 2876 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 2877 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 2878 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 2879 2880 // Perform literal operator lookup to determine if we're building a raw 2881 // literal or a cooked one. 2882 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 2883 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 2884 /*AllowRawAndTemplate*/true)) { 2885 case LOLR_Error: 2886 return ExprError(); 2887 2888 case LOLR_Cooked: { 2889 Expr *Lit; 2890 if (Literal.isFloatingLiteral()) { 2891 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 2892 } else { 2893 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 2894 if (Literal.GetIntegerValue(ResultVal)) 2895 Diag(Tok.getLocation(), diag::warn_integer_too_large); 2896 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 2897 Tok.getLocation()); 2898 } 2899 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, 2900 Tok.getLocation()); 2901 } 2902 2903 case LOLR_Raw: { 2904 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 2905 // literal is treated as a call of the form 2906 // operator "" X ("n") 2907 SourceLocation TokLoc = Tok.getLocation(); 2908 unsigned Length = Literal.getUDSuffixOffset(); 2909 QualType StrTy = Context.getConstantArrayType( 2910 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 2911 ArrayType::Normal, 0); 2912 Expr *Lit = StringLiteral::Create( 2913 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 2914 /*Pascal*/false, StrTy, &TokLoc, 1); 2915 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 2916 } 2917 2918 case LOLR_Template: 2919 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 2920 // template), L is treated as a call fo the form 2921 // operator "" X <'c1', 'c2', ... 'ck'>() 2922 // where n is the source character sequence c1 c2 ... ck. 2923 TemplateArgumentListInfo ExplicitArgs; 2924 unsigned CharBits = Context.getIntWidth(Context.CharTy); 2925 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 2926 llvm::APSInt Value(CharBits, CharIsUnsigned); 2927 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 2928 Value = TokSpelling[I]; 2929 TemplateArgument Arg(Context, Value, Context.CharTy); 2930 TemplateArgumentLocInfo ArgInfo; 2931 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 2932 } 2933 return BuildLiteralOperatorCall(R, OpNameInfo, None, Tok.getLocation(), 2934 &ExplicitArgs); 2935 } 2936 2937 llvm_unreachable("unexpected literal operator lookup result"); 2938 } 2939 2940 Expr *Res; 2941 2942 if (Literal.isFloatingLiteral()) { 2943 QualType Ty; 2944 if (Literal.isFloat) 2945 Ty = Context.FloatTy; 2946 else if (!Literal.isLong) 2947 Ty = Context.DoubleTy; 2948 else 2949 Ty = Context.LongDoubleTy; 2950 2951 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 2952 2953 if (Ty == Context.DoubleTy) { 2954 if (getLangOpts().SinglePrecisionConstants) { 2955 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 2956 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) { 2957 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 2958 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 2959 } 2960 } 2961 } else if (!Literal.isIntegerLiteral()) { 2962 return ExprError(); 2963 } else { 2964 QualType Ty; 2965 2966 // 'long long' is a C99 or C++11 feature. 2967 if (!getLangOpts().C99 && Literal.isLongLong) { 2968 if (getLangOpts().CPlusPlus) 2969 Diag(Tok.getLocation(), 2970 getLangOpts().CPlusPlus11 ? 2971 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 2972 else 2973 Diag(Tok.getLocation(), diag::ext_c99_longlong); 2974 } 2975 2976 // Get the value in the widest-possible width. 2977 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 2978 // The microsoft literal suffix extensions support 128-bit literals, which 2979 // may be wider than [u]intmax_t. 2980 // FIXME: Actually, they don't. We seem to have accidentally invented the 2981 // i128 suffix. 2982 if (Literal.isMicrosoftInteger && MaxWidth < 128 && 2983 PP.getTargetInfo().hasInt128Type()) 2984 MaxWidth = 128; 2985 llvm::APInt ResultVal(MaxWidth, 0); 2986 2987 if (Literal.GetIntegerValue(ResultVal)) { 2988 // If this value didn't fit into uintmax_t, warn and force to ull. 2989 Diag(Tok.getLocation(), diag::warn_integer_too_large); 2990 Ty = Context.UnsignedLongLongTy; 2991 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 2992 "long long is not intmax_t?"); 2993 } else { 2994 // If this value fits into a ULL, try to figure out what else it fits into 2995 // according to the rules of C99 6.4.4.1p5. 2996 2997 // Octal, Hexadecimal, and integers with a U suffix are allowed to 2998 // be an unsigned int. 2999 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3000 3001 // Check from smallest to largest, picking the smallest type we can. 3002 unsigned Width = 0; 3003 if (!Literal.isLong && !Literal.isLongLong) { 3004 // Are int/unsigned possibilities? 3005 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3006 3007 // Does it fit in a unsigned int? 3008 if (ResultVal.isIntN(IntSize)) { 3009 // Does it fit in a signed int? 3010 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3011 Ty = Context.IntTy; 3012 else if (AllowUnsigned) 3013 Ty = Context.UnsignedIntTy; 3014 Width = IntSize; 3015 } 3016 } 3017 3018 // Are long/unsigned long possibilities? 3019 if (Ty.isNull() && !Literal.isLongLong) { 3020 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3021 3022 // Does it fit in a unsigned long? 3023 if (ResultVal.isIntN(LongSize)) { 3024 // Does it fit in a signed long? 3025 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3026 Ty = Context.LongTy; 3027 else if (AllowUnsigned) 3028 Ty = Context.UnsignedLongTy; 3029 Width = LongSize; 3030 } 3031 } 3032 3033 // Check long long if needed. 3034 if (Ty.isNull()) { 3035 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3036 3037 // Does it fit in a unsigned long long? 3038 if (ResultVal.isIntN(LongLongSize)) { 3039 // Does it fit in a signed long long? 3040 // To be compatible with MSVC, hex integer literals ending with the 3041 // LL or i64 suffix are always signed in Microsoft mode. 3042 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3043 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3044 Ty = Context.LongLongTy; 3045 else if (AllowUnsigned) 3046 Ty = Context.UnsignedLongLongTy; 3047 Width = LongLongSize; 3048 } 3049 } 3050 3051 // If it doesn't fit in unsigned long long, and we're using Microsoft 3052 // extensions, then its a 128-bit integer literal. 3053 if (Ty.isNull() && Literal.isMicrosoftInteger && 3054 PP.getTargetInfo().hasInt128Type()) { 3055 if (Literal.isUnsigned) 3056 Ty = Context.UnsignedInt128Ty; 3057 else 3058 Ty = Context.Int128Ty; 3059 Width = 128; 3060 } 3061 3062 // If we still couldn't decide a type, we probably have something that 3063 // does not fit in a signed long long, but has no U suffix. 3064 if (Ty.isNull()) { 3065 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed); 3066 Ty = Context.UnsignedLongLongTy; 3067 Width = Context.getTargetInfo().getLongLongWidth(); 3068 } 3069 3070 if (ResultVal.getBitWidth() != Width) 3071 ResultVal = ResultVal.trunc(Width); 3072 } 3073 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3074 } 3075 3076 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3077 if (Literal.isImaginary) 3078 Res = new (Context) ImaginaryLiteral(Res, 3079 Context.getComplexType(Res->getType())); 3080 3081 return Owned(Res); 3082} 3083 3084ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3085 assert((E != 0) && "ActOnParenExpr() missing expr"); 3086 return Owned(new (Context) ParenExpr(L, R, E)); 3087} 3088 3089static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3090 SourceLocation Loc, 3091 SourceRange ArgRange) { 3092 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3093 // scalar or vector data type argument..." 3094 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3095 // type (C99 6.2.5p18) or void. 3096 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3097 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3098 << T << ArgRange; 3099 return true; 3100 } 3101 3102 assert((T->isVoidType() || !T->isIncompleteType()) && 3103 "Scalar types should always be complete"); 3104 return false; 3105} 3106 3107static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3108 SourceLocation Loc, 3109 SourceRange ArgRange, 3110 UnaryExprOrTypeTrait TraitKind) { 3111 // C99 6.5.3.4p1: 3112 if (T->isFunctionType() && 3113 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3114 // sizeof(function)/alignof(function) is allowed as an extension. 3115 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3116 << TraitKind << ArgRange; 3117 return false; 3118 } 3119 3120 // Allow sizeof(void)/alignof(void) as an extension. 3121 if (T->isVoidType()) { 3122 S.Diag(Loc, diag::ext_sizeof_alignof_void_type) << TraitKind << ArgRange; 3123 return false; 3124 } 3125 3126 return true; 3127} 3128 3129static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3130 SourceLocation Loc, 3131 SourceRange ArgRange, 3132 UnaryExprOrTypeTrait TraitKind) { 3133 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3134 // runtime doesn't allow it. 3135 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3136 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3137 << T << (TraitKind == UETT_SizeOf) 3138 << ArgRange; 3139 return true; 3140 } 3141 3142 return false; 3143} 3144 3145/// \brief Check whether E is a pointer from a decayed array type (the decayed 3146/// pointer type is equal to T) and emit a warning if it is. 3147static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3148 Expr *E) { 3149 // Don't warn if the operation changed the type. 3150 if (T != E->getType()) 3151 return; 3152 3153 // Now look for array decays. 3154 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3155 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3156 return; 3157 3158 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3159 << ICE->getType() 3160 << ICE->getSubExpr()->getType(); 3161} 3162 3163/// \brief Check the constrains on expression operands to unary type expression 3164/// and type traits. 3165/// 3166/// Completes any types necessary and validates the constraints on the operand 3167/// expression. The logic mostly mirrors the type-based overload, but may modify 3168/// the expression as it completes the type for that expression through template 3169/// instantiation, etc. 3170bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3171 UnaryExprOrTypeTrait ExprKind) { 3172 QualType ExprTy = E->getType(); 3173 assert(!ExprTy->isReferenceType()); 3174 3175 if (ExprKind == UETT_VecStep) 3176 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3177 E->getSourceRange()); 3178 3179 // Whitelist some types as extensions 3180 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3181 E->getSourceRange(), ExprKind)) 3182 return false; 3183 3184 if (RequireCompleteExprType(E, 3185 diag::err_sizeof_alignof_incomplete_type, 3186 ExprKind, E->getSourceRange())) 3187 return true; 3188 3189 // Completing the expression's type may have changed it. 3190 ExprTy = E->getType(); 3191 assert(!ExprTy->isReferenceType()); 3192 3193 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3194 E->getSourceRange(), ExprKind)) 3195 return true; 3196 3197 if (ExprKind == UETT_SizeOf) { 3198 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3199 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3200 QualType OType = PVD->getOriginalType(); 3201 QualType Type = PVD->getType(); 3202 if (Type->isPointerType() && OType->isArrayType()) { 3203 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3204 << Type << OType; 3205 Diag(PVD->getLocation(), diag::note_declared_at); 3206 } 3207 } 3208 } 3209 3210 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3211 // decays into a pointer and returns an unintended result. This is most 3212 // likely a typo for "sizeof(array) op x". 3213 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3214 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3215 BO->getLHS()); 3216 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3217 BO->getRHS()); 3218 } 3219 } 3220 3221 return false; 3222} 3223 3224/// \brief Check the constraints on operands to unary expression and type 3225/// traits. 3226/// 3227/// This will complete any types necessary, and validate the various constraints 3228/// on those operands. 3229/// 3230/// The UsualUnaryConversions() function is *not* called by this routine. 3231/// C99 6.3.2.1p[2-4] all state: 3232/// Except when it is the operand of the sizeof operator ... 3233/// 3234/// C++ [expr.sizeof]p4 3235/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3236/// standard conversions are not applied to the operand of sizeof. 3237/// 3238/// This policy is followed for all of the unary trait expressions. 3239bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3240 SourceLocation OpLoc, 3241 SourceRange ExprRange, 3242 UnaryExprOrTypeTrait ExprKind) { 3243 if (ExprType->isDependentType()) 3244 return false; 3245 3246 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 3247 // the result is the size of the referenced type." 3248 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 3249 // result shall be the alignment of the referenced type." 3250 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3251 ExprType = Ref->getPointeeType(); 3252 3253 if (ExprKind == UETT_VecStep) 3254 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3255 3256 // Whitelist some types as extensions 3257 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3258 ExprKind)) 3259 return false; 3260 3261 if (RequireCompleteType(OpLoc, ExprType, 3262 diag::err_sizeof_alignof_incomplete_type, 3263 ExprKind, ExprRange)) 3264 return true; 3265 3266 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3267 ExprKind)) 3268 return true; 3269 3270 return false; 3271} 3272 3273static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3274 E = E->IgnoreParens(); 3275 3276 // Cannot know anything else if the expression is dependent. 3277 if (E->isTypeDependent()) 3278 return false; 3279 3280 if (E->getObjectKind() == OK_BitField) { 3281 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) 3282 << 1 << E->getSourceRange(); 3283 return true; 3284 } 3285 3286 ValueDecl *D = 0; 3287 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3288 D = DRE->getDecl(); 3289 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3290 D = ME->getMemberDecl(); 3291 } 3292 3293 // If it's a field, require the containing struct to have a 3294 // complete definition so that we can compute the layout. 3295 // 3296 // This requires a very particular set of circumstances. For a 3297 // field to be contained within an incomplete type, we must in the 3298 // process of parsing that type. To have an expression refer to a 3299 // field, it must be an id-expression or a member-expression, but 3300 // the latter are always ill-formed when the base type is 3301 // incomplete, including only being partially complete. An 3302 // id-expression can never refer to a field in C because fields 3303 // are not in the ordinary namespace. In C++, an id-expression 3304 // can implicitly be a member access, but only if there's an 3305 // implicit 'this' value, and all such contexts are subject to 3306 // delayed parsing --- except for trailing return types in C++11. 3307 // And if an id-expression referring to a field occurs in a 3308 // context that lacks a 'this' value, it's ill-formed --- except, 3309 // agian, in C++11, where such references are allowed in an 3310 // unevaluated context. So C++11 introduces some new complexity. 3311 // 3312 // For the record, since __alignof__ on expressions is a GCC 3313 // extension, GCC seems to permit this but always gives the 3314 // nonsensical answer 0. 3315 // 3316 // We don't really need the layout here --- we could instead just 3317 // directly check for all the appropriate alignment-lowing 3318 // attributes --- but that would require duplicating a lot of 3319 // logic that just isn't worth duplicating for such a marginal 3320 // use-case. 3321 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3322 // Fast path this check, since we at least know the record has a 3323 // definition if we can find a member of it. 3324 if (!FD->getParent()->isCompleteDefinition()) { 3325 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3326 << E->getSourceRange(); 3327 return true; 3328 } 3329 3330 // Otherwise, if it's a field, and the field doesn't have 3331 // reference type, then it must have a complete type (or be a 3332 // flexible array member, which we explicitly want to 3333 // white-list anyway), which makes the following checks trivial. 3334 if (!FD->getType()->isReferenceType()) 3335 return false; 3336 } 3337 3338 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3339} 3340 3341bool Sema::CheckVecStepExpr(Expr *E) { 3342 E = E->IgnoreParens(); 3343 3344 // Cannot know anything else if the expression is dependent. 3345 if (E->isTypeDependent()) 3346 return false; 3347 3348 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3349} 3350 3351/// \brief Build a sizeof or alignof expression given a type operand. 3352ExprResult 3353Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3354 SourceLocation OpLoc, 3355 UnaryExprOrTypeTrait ExprKind, 3356 SourceRange R) { 3357 if (!TInfo) 3358 return ExprError(); 3359 3360 QualType T = TInfo->getType(); 3361 3362 if (!T->isDependentType() && 3363 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3364 return ExprError(); 3365 3366 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3367 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo, 3368 Context.getSizeType(), 3369 OpLoc, R.getEnd())); 3370} 3371 3372/// \brief Build a sizeof or alignof expression given an expression 3373/// operand. 3374ExprResult 3375Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3376 UnaryExprOrTypeTrait ExprKind) { 3377 ExprResult PE = CheckPlaceholderExpr(E); 3378 if (PE.isInvalid()) 3379 return ExprError(); 3380 3381 E = PE.get(); 3382 3383 // Verify that the operand is valid. 3384 bool isInvalid = false; 3385 if (E->isTypeDependent()) { 3386 // Delay type-checking for type-dependent expressions. 3387 } else if (ExprKind == UETT_AlignOf) { 3388 isInvalid = CheckAlignOfExpr(*this, E); 3389 } else if (ExprKind == UETT_VecStep) { 3390 isInvalid = CheckVecStepExpr(E); 3391 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3392 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0; 3393 isInvalid = true; 3394 } else { 3395 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3396 } 3397 3398 if (isInvalid) 3399 return ExprError(); 3400 3401 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3402 PE = TransformToPotentiallyEvaluated(E); 3403 if (PE.isInvalid()) return ExprError(); 3404 E = PE.take(); 3405 } 3406 3407 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3408 return Owned(new (Context) UnaryExprOrTypeTraitExpr( 3409 ExprKind, E, Context.getSizeType(), OpLoc, 3410 E->getSourceRange().getEnd())); 3411} 3412 3413/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3414/// expr and the same for @c alignof and @c __alignof 3415/// Note that the ArgRange is invalid if isType is false. 3416ExprResult 3417Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3418 UnaryExprOrTypeTrait ExprKind, bool IsType, 3419 void *TyOrEx, const SourceRange &ArgRange) { 3420 // If error parsing type, ignore. 3421 if (TyOrEx == 0) return ExprError(); 3422 3423 if (IsType) { 3424 TypeSourceInfo *TInfo; 3425 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3426 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3427 } 3428 3429 Expr *ArgEx = (Expr *)TyOrEx; 3430 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3431 return Result; 3432} 3433 3434static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3435 bool IsReal) { 3436 if (V.get()->isTypeDependent()) 3437 return S.Context.DependentTy; 3438 3439 // _Real and _Imag are only l-values for normal l-values. 3440 if (V.get()->getObjectKind() != OK_Ordinary) { 3441 V = S.DefaultLvalueConversion(V.take()); 3442 if (V.isInvalid()) 3443 return QualType(); 3444 } 3445 3446 // These operators return the element type of a complex type. 3447 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3448 return CT->getElementType(); 3449 3450 // Otherwise they pass through real integer and floating point types here. 3451 if (V.get()->getType()->isArithmeticType()) 3452 return V.get()->getType(); 3453 3454 // Test for placeholders. 3455 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3456 if (PR.isInvalid()) return QualType(); 3457 if (PR.get() != V.get()) { 3458 V = PR; 3459 return CheckRealImagOperand(S, V, Loc, IsReal); 3460 } 3461 3462 // Reject anything else. 3463 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3464 << (IsReal ? "__real" : "__imag"); 3465 return QualType(); 3466} 3467 3468 3469 3470ExprResult 3471Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3472 tok::TokenKind Kind, Expr *Input) { 3473 UnaryOperatorKind Opc; 3474 switch (Kind) { 3475 default: llvm_unreachable("Unknown unary op!"); 3476 case tok::plusplus: Opc = UO_PostInc; break; 3477 case tok::minusminus: Opc = UO_PostDec; break; 3478 } 3479 3480 // Since this might is a postfix expression, get rid of ParenListExprs. 3481 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3482 if (Result.isInvalid()) return ExprError(); 3483 Input = Result.take(); 3484 3485 return BuildUnaryOp(S, OpLoc, Opc, Input); 3486} 3487 3488/// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 3489/// 3490/// \return true on error 3491static bool checkArithmeticOnObjCPointer(Sema &S, 3492 SourceLocation opLoc, 3493 Expr *op) { 3494 assert(op->getType()->isObjCObjectPointerType()); 3495 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic()) 3496 return false; 3497 3498 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 3499 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 3500 << op->getSourceRange(); 3501 return true; 3502} 3503 3504ExprResult 3505Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 3506 Expr *idx, SourceLocation rbLoc) { 3507 // Since this might be a postfix expression, get rid of ParenListExprs. 3508 if (isa<ParenListExpr>(base)) { 3509 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 3510 if (result.isInvalid()) return ExprError(); 3511 base = result.take(); 3512 } 3513 3514 // Handle any non-overload placeholder types in the base and index 3515 // expressions. We can't handle overloads here because the other 3516 // operand might be an overloadable type, in which case the overload 3517 // resolution for the operator overload should get the first crack 3518 // at the overload. 3519 if (base->getType()->isNonOverloadPlaceholderType()) { 3520 ExprResult result = CheckPlaceholderExpr(base); 3521 if (result.isInvalid()) return ExprError(); 3522 base = result.take(); 3523 } 3524 if (idx->getType()->isNonOverloadPlaceholderType()) { 3525 ExprResult result = CheckPlaceholderExpr(idx); 3526 if (result.isInvalid()) return ExprError(); 3527 idx = result.take(); 3528 } 3529 3530 // Build an unanalyzed expression if either operand is type-dependent. 3531 if (getLangOpts().CPlusPlus && 3532 (base->isTypeDependent() || idx->isTypeDependent())) { 3533 return Owned(new (Context) ArraySubscriptExpr(base, idx, 3534 Context.DependentTy, 3535 VK_LValue, OK_Ordinary, 3536 rbLoc)); 3537 } 3538 3539 // Use C++ overloaded-operator rules if either operand has record 3540 // type. The spec says to do this if either type is *overloadable*, 3541 // but enum types can't declare subscript operators or conversion 3542 // operators, so there's nothing interesting for overload resolution 3543 // to do if there aren't any record types involved. 3544 // 3545 // ObjC pointers have their own subscripting logic that is not tied 3546 // to overload resolution and so should not take this path. 3547 if (getLangOpts().CPlusPlus && 3548 (base->getType()->isRecordType() || 3549 (!base->getType()->isObjCObjectPointerType() && 3550 idx->getType()->isRecordType()))) { 3551 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 3552 } 3553 3554 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 3555} 3556 3557ExprResult 3558Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 3559 Expr *Idx, SourceLocation RLoc) { 3560 Expr *LHSExp = Base; 3561 Expr *RHSExp = Idx; 3562 3563 // Perform default conversions. 3564 if (!LHSExp->getType()->getAs<VectorType>()) { 3565 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 3566 if (Result.isInvalid()) 3567 return ExprError(); 3568 LHSExp = Result.take(); 3569 } 3570 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 3571 if (Result.isInvalid()) 3572 return ExprError(); 3573 RHSExp = Result.take(); 3574 3575 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 3576 ExprValueKind VK = VK_LValue; 3577 ExprObjectKind OK = OK_Ordinary; 3578 3579 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 3580 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 3581 // in the subscript position. As a result, we need to derive the array base 3582 // and index from the expression types. 3583 Expr *BaseExpr, *IndexExpr; 3584 QualType ResultType; 3585 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 3586 BaseExpr = LHSExp; 3587 IndexExpr = RHSExp; 3588 ResultType = Context.DependentTy; 3589 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 3590 BaseExpr = LHSExp; 3591 IndexExpr = RHSExp; 3592 ResultType = PTy->getPointeeType(); 3593 } else if (const ObjCObjectPointerType *PTy = 3594 LHSTy->getAs<ObjCObjectPointerType>()) { 3595 BaseExpr = LHSExp; 3596 IndexExpr = RHSExp; 3597 3598 // Use custom logic if this should be the pseudo-object subscript 3599 // expression. 3600 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic()) 3601 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0); 3602 3603 ResultType = PTy->getPointeeType(); 3604 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) { 3605 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3606 << ResultType << BaseExpr->getSourceRange(); 3607 return ExprError(); 3608 } 3609 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 3610 // Handle the uncommon case of "123[Ptr]". 3611 BaseExpr = RHSExp; 3612 IndexExpr = LHSExp; 3613 ResultType = PTy->getPointeeType(); 3614 } else if (const ObjCObjectPointerType *PTy = 3615 RHSTy->getAs<ObjCObjectPointerType>()) { 3616 // Handle the uncommon case of "123[Ptr]". 3617 BaseExpr = RHSExp; 3618 IndexExpr = LHSExp; 3619 ResultType = PTy->getPointeeType(); 3620 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) { 3621 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3622 << ResultType << BaseExpr->getSourceRange(); 3623 return ExprError(); 3624 } 3625 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 3626 BaseExpr = LHSExp; // vectors: V[123] 3627 IndexExpr = RHSExp; 3628 VK = LHSExp->getValueKind(); 3629 if (VK != VK_RValue) 3630 OK = OK_VectorComponent; 3631 3632 // FIXME: need to deal with const... 3633 ResultType = VTy->getElementType(); 3634 } else if (LHSTy->isArrayType()) { 3635 // If we see an array that wasn't promoted by 3636 // DefaultFunctionArrayLvalueConversion, it must be an array that 3637 // wasn't promoted because of the C90 rule that doesn't 3638 // allow promoting non-lvalue arrays. Warn, then 3639 // force the promotion here. 3640 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3641 LHSExp->getSourceRange(); 3642 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 3643 CK_ArrayToPointerDecay).take(); 3644 LHSTy = LHSExp->getType(); 3645 3646 BaseExpr = LHSExp; 3647 IndexExpr = RHSExp; 3648 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 3649 } else if (RHSTy->isArrayType()) { 3650 // Same as previous, except for 123[f().a] case 3651 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3652 RHSExp->getSourceRange(); 3653 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 3654 CK_ArrayToPointerDecay).take(); 3655 RHSTy = RHSExp->getType(); 3656 3657 BaseExpr = RHSExp; 3658 IndexExpr = LHSExp; 3659 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 3660 } else { 3661 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 3662 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 3663 } 3664 // C99 6.5.2.1p1 3665 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 3666 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 3667 << IndexExpr->getSourceRange()); 3668 3669 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 3670 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 3671 && !IndexExpr->isTypeDependent()) 3672 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 3673 3674 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 3675 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 3676 // type. Note that Functions are not objects, and that (in C99 parlance) 3677 // incomplete types are not object types. 3678 if (ResultType->isFunctionType()) { 3679 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 3680 << ResultType << BaseExpr->getSourceRange(); 3681 return ExprError(); 3682 } 3683 3684 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 3685 // GNU extension: subscripting on pointer to void 3686 Diag(LLoc, diag::ext_gnu_subscript_void_type) 3687 << BaseExpr->getSourceRange(); 3688 3689 // C forbids expressions of unqualified void type from being l-values. 3690 // See IsCForbiddenLValueType. 3691 if (!ResultType.hasQualifiers()) VK = VK_RValue; 3692 } else if (!ResultType->isDependentType() && 3693 RequireCompleteType(LLoc, ResultType, 3694 diag::err_subscript_incomplete_type, BaseExpr)) 3695 return ExprError(); 3696 3697 assert(VK == VK_RValue || LangOpts.CPlusPlus || 3698 !ResultType.isCForbiddenLValueType()); 3699 3700 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 3701 ResultType, VK, OK, RLoc)); 3702} 3703 3704ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3705 FunctionDecl *FD, 3706 ParmVarDecl *Param) { 3707 if (Param->hasUnparsedDefaultArg()) { 3708 Diag(CallLoc, 3709 diag::err_use_of_default_argument_to_function_declared_later) << 3710 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 3711 Diag(UnparsedDefaultArgLocs[Param], 3712 diag::note_default_argument_declared_here); 3713 return ExprError(); 3714 } 3715 3716 if (Param->hasUninstantiatedDefaultArg()) { 3717 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 3718 3719 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 3720 Param); 3721 3722 // Instantiate the expression. 3723 MultiLevelTemplateArgumentList MutiLevelArgList 3724 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true); 3725 3726 InstantiatingTemplate Inst(*this, CallLoc, Param, 3727 MutiLevelArgList.getInnermost()); 3728 if (Inst) 3729 return ExprError(); 3730 3731 ExprResult Result; 3732 { 3733 // C++ [dcl.fct.default]p5: 3734 // The names in the [default argument] expression are bound, and 3735 // the semantic constraints are checked, at the point where the 3736 // default argument expression appears. 3737 ContextRAII SavedContext(*this, FD); 3738 LocalInstantiationScope Local(*this); 3739 Result = SubstExpr(UninstExpr, MutiLevelArgList); 3740 } 3741 if (Result.isInvalid()) 3742 return ExprError(); 3743 3744 // Check the expression as an initializer for the parameter. 3745 InitializedEntity Entity 3746 = InitializedEntity::InitializeParameter(Context, Param); 3747 InitializationKind Kind 3748 = InitializationKind::CreateCopy(Param->getLocation(), 3749 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 3750 Expr *ResultE = Result.takeAs<Expr>(); 3751 3752 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 3753 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 3754 if (Result.isInvalid()) 3755 return ExprError(); 3756 3757 Expr *Arg = Result.takeAs<Expr>(); 3758 CheckCompletedExpr(Arg, Param->getOuterLocStart()); 3759 // Build the default argument expression. 3760 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg)); 3761 } 3762 3763 // If the default expression creates temporaries, we need to 3764 // push them to the current stack of expression temporaries so they'll 3765 // be properly destroyed. 3766 // FIXME: We should really be rebuilding the default argument with new 3767 // bound temporaries; see the comment in PR5810. 3768 // We don't need to do that with block decls, though, because 3769 // blocks in default argument expression can never capture anything. 3770 if (isa<ExprWithCleanups>(Param->getInit())) { 3771 // Set the "needs cleanups" bit regardless of whether there are 3772 // any explicit objects. 3773 ExprNeedsCleanups = true; 3774 3775 // Append all the objects to the cleanup list. Right now, this 3776 // should always be a no-op, because blocks in default argument 3777 // expressions should never be able to capture anything. 3778 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 3779 "default argument expression has capturing blocks?"); 3780 } 3781 3782 // We already type-checked the argument, so we know it works. 3783 // Just mark all of the declarations in this potentially-evaluated expression 3784 // as being "referenced". 3785 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 3786 /*SkipLocalVariables=*/true); 3787 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param)); 3788} 3789 3790 3791Sema::VariadicCallType 3792Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 3793 Expr *Fn) { 3794 if (Proto && Proto->isVariadic()) { 3795 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 3796 return VariadicConstructor; 3797 else if (Fn && Fn->getType()->isBlockPointerType()) 3798 return VariadicBlock; 3799 else if (FDecl) { 3800 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 3801 if (Method->isInstance()) 3802 return VariadicMethod; 3803 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 3804 return VariadicMethod; 3805 return VariadicFunction; 3806 } 3807 return VariadicDoesNotApply; 3808} 3809 3810/// ConvertArgumentsForCall - Converts the arguments specified in 3811/// Args/NumArgs to the parameter types of the function FDecl with 3812/// function prototype Proto. Call is the call expression itself, and 3813/// Fn is the function expression. For a C++ member function, this 3814/// routine does not attempt to convert the object argument. Returns 3815/// true if the call is ill-formed. 3816bool 3817Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 3818 FunctionDecl *FDecl, 3819 const FunctionProtoType *Proto, 3820 ArrayRef<Expr *> Args, 3821 SourceLocation RParenLoc, 3822 bool IsExecConfig) { 3823 // Bail out early if calling a builtin with custom typechecking. 3824 // We don't need to do this in the 3825 if (FDecl) 3826 if (unsigned ID = FDecl->getBuiltinID()) 3827 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 3828 return false; 3829 3830 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 3831 // assignment, to the types of the corresponding parameter, ... 3832 unsigned NumArgsInProto = Proto->getNumArgs(); 3833 bool Invalid = false; 3834 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto; 3835 unsigned FnKind = Fn->getType()->isBlockPointerType() 3836 ? 1 /* block */ 3837 : (IsExecConfig ? 3 /* kernel function (exec config) */ 3838 : 0 /* function */); 3839 3840 // If too few arguments are available (and we don't have default 3841 // arguments for the remaining parameters), don't make the call. 3842 if (Args.size() < NumArgsInProto) { 3843 if (Args.size() < MinArgs) { 3844 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 3845 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic() 3846 ? diag::err_typecheck_call_too_few_args_one 3847 : diag::err_typecheck_call_too_few_args_at_least_one) 3848 << FnKind 3849 << FDecl->getParamDecl(0) << Fn->getSourceRange(); 3850 else 3851 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic() 3852 ? diag::err_typecheck_call_too_few_args 3853 : diag::err_typecheck_call_too_few_args_at_least) 3854 << FnKind 3855 << MinArgs << static_cast<unsigned>(Args.size()) 3856 << Fn->getSourceRange(); 3857 3858 // Emit the location of the prototype. 3859 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 3860 Diag(FDecl->getLocStart(), diag::note_callee_decl) 3861 << FDecl; 3862 3863 return true; 3864 } 3865 Call->setNumArgs(Context, NumArgsInProto); 3866 } 3867 3868 // If too many are passed and not variadic, error on the extras and drop 3869 // them. 3870 if (Args.size() > NumArgsInProto) { 3871 if (!Proto->isVariadic()) { 3872 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 3873 Diag(Args[NumArgsInProto]->getLocStart(), 3874 MinArgs == NumArgsInProto 3875 ? diag::err_typecheck_call_too_many_args_one 3876 : diag::err_typecheck_call_too_many_args_at_most_one) 3877 << FnKind 3878 << FDecl->getParamDecl(0) << static_cast<unsigned>(Args.size()) 3879 << Fn->getSourceRange() 3880 << SourceRange(Args[NumArgsInProto]->getLocStart(), 3881 Args.back()->getLocEnd()); 3882 else 3883 Diag(Args[NumArgsInProto]->getLocStart(), 3884 MinArgs == NumArgsInProto 3885 ? diag::err_typecheck_call_too_many_args 3886 : diag::err_typecheck_call_too_many_args_at_most) 3887 << FnKind 3888 << NumArgsInProto << static_cast<unsigned>(Args.size()) 3889 << Fn->getSourceRange() 3890 << SourceRange(Args[NumArgsInProto]->getLocStart(), 3891 Args.back()->getLocEnd()); 3892 3893 // Emit the location of the prototype. 3894 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 3895 Diag(FDecl->getLocStart(), diag::note_callee_decl) 3896 << FDecl; 3897 3898 // This deletes the extra arguments. 3899 Call->setNumArgs(Context, NumArgsInProto); 3900 return true; 3901 } 3902 } 3903 SmallVector<Expr *, 8> AllArgs; 3904 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 3905 3906 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 3907 Proto, 0, Args, AllArgs, CallType); 3908 if (Invalid) 3909 return true; 3910 unsigned TotalNumArgs = AllArgs.size(); 3911 for (unsigned i = 0; i < TotalNumArgs; ++i) 3912 Call->setArg(i, AllArgs[i]); 3913 3914 return false; 3915} 3916 3917bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, 3918 FunctionDecl *FDecl, 3919 const FunctionProtoType *Proto, 3920 unsigned FirstProtoArg, 3921 ArrayRef<Expr *> Args, 3922 SmallVector<Expr *, 8> &AllArgs, 3923 VariadicCallType CallType, 3924 bool AllowExplicit, 3925 bool IsListInitialization) { 3926 unsigned NumArgsInProto = Proto->getNumArgs(); 3927 unsigned NumArgsToCheck = Args.size(); 3928 bool Invalid = false; 3929 if (Args.size() != NumArgsInProto) 3930 // Use default arguments for missing arguments 3931 NumArgsToCheck = NumArgsInProto; 3932 unsigned ArgIx = 0; 3933 // Continue to check argument types (even if we have too few/many args). 3934 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) { 3935 QualType ProtoArgType = Proto->getArgType(i); 3936 3937 Expr *Arg; 3938 ParmVarDecl *Param; 3939 if (ArgIx < Args.size()) { 3940 Arg = Args[ArgIx++]; 3941 3942 if (RequireCompleteType(Arg->getLocStart(), 3943 ProtoArgType, 3944 diag::err_call_incomplete_argument, Arg)) 3945 return true; 3946 3947 // Pass the argument 3948 Param = 0; 3949 if (FDecl && i < FDecl->getNumParams()) 3950 Param = FDecl->getParamDecl(i); 3951 3952 // Strip the unbridged-cast placeholder expression off, if applicable. 3953 if (Arg->getType() == Context.ARCUnbridgedCastTy && 3954 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 3955 (!Param || !Param->hasAttr<CFConsumedAttr>())) 3956 Arg = stripARCUnbridgedCast(Arg); 3957 3958 InitializedEntity Entity = Param ? 3959 InitializedEntity::InitializeParameter(Context, Param, ProtoArgType) 3960 : InitializedEntity::InitializeParameter(Context, ProtoArgType, 3961 Proto->isArgConsumed(i)); 3962 ExprResult ArgE = PerformCopyInitialization(Entity, 3963 SourceLocation(), 3964 Owned(Arg), 3965 IsListInitialization, 3966 AllowExplicit); 3967 if (ArgE.isInvalid()) 3968 return true; 3969 3970 Arg = ArgE.takeAs<Expr>(); 3971 } else { 3972 assert(FDecl && "can't use default arguments without a known callee"); 3973 Param = FDecl->getParamDecl(i); 3974 3975 ExprResult ArgExpr = 3976 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 3977 if (ArgExpr.isInvalid()) 3978 return true; 3979 3980 Arg = ArgExpr.takeAs<Expr>(); 3981 } 3982 3983 // Check for array bounds violations for each argument to the call. This 3984 // check only triggers warnings when the argument isn't a more complex Expr 3985 // with its own checking, such as a BinaryOperator. 3986 CheckArrayAccess(Arg); 3987 3988 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 3989 CheckStaticArrayArgument(CallLoc, Param, Arg); 3990 3991 AllArgs.push_back(Arg); 3992 } 3993 3994 // If this is a variadic call, handle args passed through "...". 3995 if (CallType != VariadicDoesNotApply) { 3996 // Assume that extern "C" functions with variadic arguments that 3997 // return __unknown_anytype aren't *really* variadic. 3998 if (Proto->getResultType() == Context.UnknownAnyTy && 3999 FDecl && FDecl->isExternC()) { 4000 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4001 QualType paramType; // ignored 4002 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType); 4003 Invalid |= arg.isInvalid(); 4004 AllArgs.push_back(arg.take()); 4005 } 4006 4007 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4008 } else { 4009 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4010 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 4011 FDecl); 4012 Invalid |= Arg.isInvalid(); 4013 AllArgs.push_back(Arg.take()); 4014 } 4015 } 4016 4017 // Check for array bounds violations. 4018 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) 4019 CheckArrayAccess(Args[i]); 4020 } 4021 return Invalid; 4022} 4023 4024static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4025 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4026 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4027 TL = DTL.getOriginalLoc(); 4028 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4029 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4030 << ATL.getLocalSourceRange(); 4031} 4032 4033/// CheckStaticArrayArgument - If the given argument corresponds to a static 4034/// array parameter, check that it is non-null, and that if it is formed by 4035/// array-to-pointer decay, the underlying array is sufficiently large. 4036/// 4037/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4038/// array type derivation, then for each call to the function, the value of the 4039/// corresponding actual argument shall provide access to the first element of 4040/// an array with at least as many elements as specified by the size expression. 4041void 4042Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4043 ParmVarDecl *Param, 4044 const Expr *ArgExpr) { 4045 // Static array parameters are not supported in C++. 4046 if (!Param || getLangOpts().CPlusPlus) 4047 return; 4048 4049 QualType OrigTy = Param->getOriginalType(); 4050 4051 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4052 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4053 return; 4054 4055 if (ArgExpr->isNullPointerConstant(Context, 4056 Expr::NPC_NeverValueDependent)) { 4057 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4058 DiagnoseCalleeStaticArrayParam(*this, Param); 4059 return; 4060 } 4061 4062 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4063 if (!CAT) 4064 return; 4065 4066 const ConstantArrayType *ArgCAT = 4067 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4068 if (!ArgCAT) 4069 return; 4070 4071 if (ArgCAT->getSize().ult(CAT->getSize())) { 4072 Diag(CallLoc, diag::warn_static_array_too_small) 4073 << ArgExpr->getSourceRange() 4074 << (unsigned) ArgCAT->getSize().getZExtValue() 4075 << (unsigned) CAT->getSize().getZExtValue(); 4076 DiagnoseCalleeStaticArrayParam(*this, Param); 4077 } 4078} 4079 4080/// Given a function expression of unknown-any type, try to rebuild it 4081/// to have a function type. 4082static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4083 4084/// Is the given type a placeholder that we need to lower out 4085/// immediately during argument processing? 4086static bool isPlaceholderToRemoveAsArg(QualType type) { 4087 // Placeholders are never sugared. 4088 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4089 if (!placeholder) return false; 4090 4091 switch (placeholder->getKind()) { 4092 // Ignore all the non-placeholder types. 4093#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4094#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4095#include "clang/AST/BuiltinTypes.def" 4096 return false; 4097 4098 // We cannot lower out overload sets; they might validly be resolved 4099 // by the call machinery. 4100 case BuiltinType::Overload: 4101 return false; 4102 4103 // Unbridged casts in ARC can be handled in some call positions and 4104 // should be left in place. 4105 case BuiltinType::ARCUnbridgedCast: 4106 return false; 4107 4108 // Pseudo-objects should be converted as soon as possible. 4109 case BuiltinType::PseudoObject: 4110 return true; 4111 4112 // The debugger mode could theoretically but currently does not try 4113 // to resolve unknown-typed arguments based on known parameter types. 4114 case BuiltinType::UnknownAny: 4115 return true; 4116 4117 // These are always invalid as call arguments and should be reported. 4118 case BuiltinType::BoundMember: 4119 case BuiltinType::BuiltinFn: 4120 return true; 4121 } 4122 llvm_unreachable("bad builtin type kind"); 4123} 4124 4125/// Check an argument list for placeholders that we won't try to 4126/// handle later. 4127static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 4128 // Apply this processing to all the arguments at once instead of 4129 // dying at the first failure. 4130 bool hasInvalid = false; 4131 for (size_t i = 0, e = args.size(); i != e; i++) { 4132 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 4133 ExprResult result = S.CheckPlaceholderExpr(args[i]); 4134 if (result.isInvalid()) hasInvalid = true; 4135 else args[i] = result.take(); 4136 } 4137 } 4138 return hasInvalid; 4139} 4140 4141/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 4142/// This provides the location of the left/right parens and a list of comma 4143/// locations. 4144ExprResult 4145Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 4146 MultiExprArg ArgExprs, SourceLocation RParenLoc, 4147 Expr *ExecConfig, bool IsExecConfig) { 4148 // Since this might be a postfix expression, get rid of ParenListExprs. 4149 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 4150 if (Result.isInvalid()) return ExprError(); 4151 Fn = Result.take(); 4152 4153 if (checkArgsForPlaceholders(*this, ArgExprs)) 4154 return ExprError(); 4155 4156 if (getLangOpts().CPlusPlus) { 4157 // If this is a pseudo-destructor expression, build the call immediately. 4158 if (isa<CXXPseudoDestructorExpr>(Fn)) { 4159 if (!ArgExprs.empty()) { 4160 // Pseudo-destructor calls should not have any arguments. 4161 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 4162 << FixItHint::CreateRemoval( 4163 SourceRange(ArgExprs[0]->getLocStart(), 4164 ArgExprs.back()->getLocEnd())); 4165 } 4166 4167 return Owned(new (Context) CallExpr(Context, Fn, None, 4168 Context.VoidTy, VK_RValue, 4169 RParenLoc)); 4170 } 4171 if (Fn->getType() == Context.PseudoObjectTy) { 4172 ExprResult result = CheckPlaceholderExpr(Fn); 4173 if (result.isInvalid()) return ExprError(); 4174 Fn = result.take(); 4175 } 4176 4177 // Determine whether this is a dependent call inside a C++ template, 4178 // in which case we won't do any semantic analysis now. 4179 // FIXME: Will need to cache the results of name lookup (including ADL) in 4180 // Fn. 4181 bool Dependent = false; 4182 if (Fn->isTypeDependent()) 4183 Dependent = true; 4184 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 4185 Dependent = true; 4186 4187 if (Dependent) { 4188 if (ExecConfig) { 4189 return Owned(new (Context) CUDAKernelCallExpr( 4190 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 4191 Context.DependentTy, VK_RValue, RParenLoc)); 4192 } else { 4193 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs, 4194 Context.DependentTy, VK_RValue, 4195 RParenLoc)); 4196 } 4197 } 4198 4199 // Determine whether this is a call to an object (C++ [over.call.object]). 4200 if (Fn->getType()->isRecordType()) 4201 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, 4202 ArgExprs, RParenLoc)); 4203 4204 if (Fn->getType() == Context.UnknownAnyTy) { 4205 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4206 if (result.isInvalid()) return ExprError(); 4207 Fn = result.take(); 4208 } 4209 4210 if (Fn->getType() == Context.BoundMemberTy) { 4211 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 4212 } 4213 } 4214 4215 // Check for overloaded calls. This can happen even in C due to extensions. 4216 if (Fn->getType() == Context.OverloadTy) { 4217 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 4218 4219 // We aren't supposed to apply this logic for if there's an '&' involved. 4220 if (!find.HasFormOfMemberPointer) { 4221 OverloadExpr *ovl = find.Expression; 4222 if (isa<UnresolvedLookupExpr>(ovl)) { 4223 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 4224 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 4225 RParenLoc, ExecConfig); 4226 } else { 4227 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, 4228 RParenLoc); 4229 } 4230 } 4231 } 4232 4233 // If we're directly calling a function, get the appropriate declaration. 4234 if (Fn->getType() == Context.UnknownAnyTy) { 4235 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4236 if (result.isInvalid()) return ExprError(); 4237 Fn = result.take(); 4238 } 4239 4240 Expr *NakedFn = Fn->IgnoreParens(); 4241 4242 NamedDecl *NDecl = 0; 4243 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 4244 if (UnOp->getOpcode() == UO_AddrOf) 4245 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 4246 4247 if (isa<DeclRefExpr>(NakedFn)) 4248 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 4249 else if (isa<MemberExpr>(NakedFn)) 4250 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 4251 4252 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 4253 ExecConfig, IsExecConfig); 4254} 4255 4256ExprResult 4257Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 4258 MultiExprArg ExecConfig, SourceLocation GGGLoc) { 4259 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl(); 4260 if (!ConfigDecl) 4261 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use) 4262 << "cudaConfigureCall"); 4263 QualType ConfigQTy = ConfigDecl->getType(); 4264 4265 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr( 4266 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc); 4267 MarkFunctionReferenced(LLLLoc, ConfigDecl); 4268 4269 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0, 4270 /*IsExecConfig=*/true); 4271} 4272 4273/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 4274/// 4275/// __builtin_astype( value, dst type ) 4276/// 4277ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 4278 SourceLocation BuiltinLoc, 4279 SourceLocation RParenLoc) { 4280 ExprValueKind VK = VK_RValue; 4281 ExprObjectKind OK = OK_Ordinary; 4282 QualType DstTy = GetTypeFromParser(ParsedDestTy); 4283 QualType SrcTy = E->getType(); 4284 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 4285 return ExprError(Diag(BuiltinLoc, 4286 diag::err_invalid_astype_of_different_size) 4287 << DstTy 4288 << SrcTy 4289 << E->getSourceRange()); 4290 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, 4291 RParenLoc)); 4292} 4293 4294/// BuildResolvedCallExpr - Build a call to a resolved expression, 4295/// i.e. an expression not of \p OverloadTy. The expression should 4296/// unary-convert to an expression of function-pointer or 4297/// block-pointer type. 4298/// 4299/// \param NDecl the declaration being called, if available 4300ExprResult 4301Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 4302 SourceLocation LParenLoc, 4303 ArrayRef<Expr *> Args, 4304 SourceLocation RParenLoc, 4305 Expr *Config, bool IsExecConfig) { 4306 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 4307 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 4308 4309 // Promote the function operand. 4310 // We special-case function promotion here because we only allow promoting 4311 // builtin functions to function pointers in the callee of a call. 4312 ExprResult Result; 4313 if (BuiltinID && 4314 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 4315 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 4316 CK_BuiltinFnToFnPtr).take(); 4317 } else { 4318 Result = UsualUnaryConversions(Fn); 4319 } 4320 if (Result.isInvalid()) 4321 return ExprError(); 4322 Fn = Result.take(); 4323 4324 // Make the call expr early, before semantic checks. This guarantees cleanup 4325 // of arguments and function on error. 4326 CallExpr *TheCall; 4327 if (Config) 4328 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 4329 cast<CallExpr>(Config), Args, 4330 Context.BoolTy, VK_RValue, 4331 RParenLoc); 4332 else 4333 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 4334 VK_RValue, RParenLoc); 4335 4336 // Bail out early if calling a builtin with custom typechecking. 4337 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 4338 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4339 4340 retry: 4341 const FunctionType *FuncT; 4342 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 4343 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 4344 // have type pointer to function". 4345 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 4346 if (FuncT == 0) 4347 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4348 << Fn->getType() << Fn->getSourceRange()); 4349 } else if (const BlockPointerType *BPT = 4350 Fn->getType()->getAs<BlockPointerType>()) { 4351 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 4352 } else { 4353 // Handle calls to expressions of unknown-any type. 4354 if (Fn->getType() == Context.UnknownAnyTy) { 4355 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 4356 if (rewrite.isInvalid()) return ExprError(); 4357 Fn = rewrite.take(); 4358 TheCall->setCallee(Fn); 4359 goto retry; 4360 } 4361 4362 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4363 << Fn->getType() << Fn->getSourceRange()); 4364 } 4365 4366 if (getLangOpts().CUDA) { 4367 if (Config) { 4368 // CUDA: Kernel calls must be to global functions 4369 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 4370 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 4371 << FDecl->getName() << Fn->getSourceRange()); 4372 4373 // CUDA: Kernel function must have 'void' return type 4374 if (!FuncT->getResultType()->isVoidType()) 4375 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 4376 << Fn->getType() << Fn->getSourceRange()); 4377 } else { 4378 // CUDA: Calls to global functions must be configured 4379 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 4380 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 4381 << FDecl->getName() << Fn->getSourceRange()); 4382 } 4383 } 4384 4385 // Check for a valid return type 4386 if (CheckCallReturnType(FuncT->getResultType(), 4387 Fn->getLocStart(), TheCall, 4388 FDecl)) 4389 return ExprError(); 4390 4391 // We know the result type of the call, set it. 4392 TheCall->setType(FuncT->getCallResultType(Context)); 4393 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType())); 4394 4395 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 4396 if (Proto) { 4397 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 4398 IsExecConfig)) 4399 return ExprError(); 4400 } else { 4401 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 4402 4403 if (FDecl) { 4404 // Check if we have too few/too many template arguments, based 4405 // on our knowledge of the function definition. 4406 const FunctionDecl *Def = 0; 4407 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 4408 Proto = Def->getType()->getAs<FunctionProtoType>(); 4409 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 4410 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 4411 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 4412 } 4413 4414 // If the function we're calling isn't a function prototype, but we have 4415 // a function prototype from a prior declaratiom, use that prototype. 4416 if (!FDecl->hasPrototype()) 4417 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 4418 } 4419 4420 // Promote the arguments (C99 6.5.2.2p6). 4421 for (unsigned i = 0, e = Args.size(); i != e; i++) { 4422 Expr *Arg = Args[i]; 4423 4424 if (Proto && i < Proto->getNumArgs()) { 4425 InitializedEntity Entity 4426 = InitializedEntity::InitializeParameter(Context, 4427 Proto->getArgType(i), 4428 Proto->isArgConsumed(i)); 4429 ExprResult ArgE = PerformCopyInitialization(Entity, 4430 SourceLocation(), 4431 Owned(Arg)); 4432 if (ArgE.isInvalid()) 4433 return true; 4434 4435 Arg = ArgE.takeAs<Expr>(); 4436 4437 } else { 4438 ExprResult ArgE = DefaultArgumentPromotion(Arg); 4439 4440 if (ArgE.isInvalid()) 4441 return true; 4442 4443 Arg = ArgE.takeAs<Expr>(); 4444 } 4445 4446 if (RequireCompleteType(Arg->getLocStart(), 4447 Arg->getType(), 4448 diag::err_call_incomplete_argument, Arg)) 4449 return ExprError(); 4450 4451 TheCall->setArg(i, Arg); 4452 } 4453 } 4454 4455 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4456 if (!Method->isStatic()) 4457 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 4458 << Fn->getSourceRange()); 4459 4460 // Check for sentinels 4461 if (NDecl) 4462 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 4463 4464 // Do special checking on direct calls to functions. 4465 if (FDecl) { 4466 if (CheckFunctionCall(FDecl, TheCall, Proto)) 4467 return ExprError(); 4468 4469 if (BuiltinID) 4470 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4471 } else if (NDecl) { 4472 if (CheckPointerCall(NDecl, TheCall, Proto)) 4473 return ExprError(); 4474 } else { 4475 if (CheckOtherCall(TheCall, Proto)) 4476 return ExprError(); 4477 } 4478 4479 return MaybeBindToTemporary(TheCall); 4480} 4481 4482ExprResult 4483Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 4484 SourceLocation RParenLoc, Expr *InitExpr) { 4485 assert(Ty && "ActOnCompoundLiteral(): missing type"); 4486 // FIXME: put back this assert when initializers are worked out. 4487 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 4488 4489 TypeSourceInfo *TInfo; 4490 QualType literalType = GetTypeFromParser(Ty, &TInfo); 4491 if (!TInfo) 4492 TInfo = Context.getTrivialTypeSourceInfo(literalType); 4493 4494 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 4495} 4496 4497ExprResult 4498Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 4499 SourceLocation RParenLoc, Expr *LiteralExpr) { 4500 QualType literalType = TInfo->getType(); 4501 4502 if (literalType->isArrayType()) { 4503 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 4504 diag::err_illegal_decl_array_incomplete_type, 4505 SourceRange(LParenLoc, 4506 LiteralExpr->getSourceRange().getEnd()))) 4507 return ExprError(); 4508 if (literalType->isVariableArrayType()) 4509 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 4510 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 4511 } else if (!literalType->isDependentType() && 4512 RequireCompleteType(LParenLoc, literalType, 4513 diag::err_typecheck_decl_incomplete_type, 4514 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 4515 return ExprError(); 4516 4517 InitializedEntity Entity 4518 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 4519 InitializationKind Kind 4520 = InitializationKind::CreateCStyleCast(LParenLoc, 4521 SourceRange(LParenLoc, RParenLoc), 4522 /*InitList=*/true); 4523 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 4524 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 4525 &literalType); 4526 if (Result.isInvalid()) 4527 return ExprError(); 4528 LiteralExpr = Result.get(); 4529 4530 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 4531 if (isFileScope) { // 6.5.2.5p3 4532 if (CheckForConstantInitializer(LiteralExpr, literalType)) 4533 return ExprError(); 4534 } 4535 4536 // In C, compound literals are l-values for some reason. 4537 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 4538 4539 return MaybeBindToTemporary( 4540 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 4541 VK, LiteralExpr, isFileScope)); 4542} 4543 4544ExprResult 4545Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 4546 SourceLocation RBraceLoc) { 4547 // Immediately handle non-overload placeholders. Overloads can be 4548 // resolved contextually, but everything else here can't. 4549 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 4550 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 4551 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 4552 4553 // Ignore failures; dropping the entire initializer list because 4554 // of one failure would be terrible for indexing/etc. 4555 if (result.isInvalid()) continue; 4556 4557 InitArgList[I] = result.take(); 4558 } 4559 } 4560 4561 // Semantic analysis for initializers is done by ActOnDeclarator() and 4562 // CheckInitializer() - it requires knowledge of the object being intialized. 4563 4564 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 4565 RBraceLoc); 4566 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 4567 return Owned(E); 4568} 4569 4570/// Do an explicit extend of the given block pointer if we're in ARC. 4571static void maybeExtendBlockObject(Sema &S, ExprResult &E) { 4572 assert(E.get()->getType()->isBlockPointerType()); 4573 assert(E.get()->isRValue()); 4574 4575 // Only do this in an r-value context. 4576 if (!S.getLangOpts().ObjCAutoRefCount) return; 4577 4578 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), 4579 CK_ARCExtendBlockObject, E.get(), 4580 /*base path*/ 0, VK_RValue); 4581 S.ExprNeedsCleanups = true; 4582} 4583 4584/// Prepare a conversion of the given expression to an ObjC object 4585/// pointer type. 4586CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 4587 QualType type = E.get()->getType(); 4588 if (type->isObjCObjectPointerType()) { 4589 return CK_BitCast; 4590 } else if (type->isBlockPointerType()) { 4591 maybeExtendBlockObject(*this, E); 4592 return CK_BlockPointerToObjCPointerCast; 4593 } else { 4594 assert(type->isPointerType()); 4595 return CK_CPointerToObjCPointerCast; 4596 } 4597} 4598 4599/// Prepares for a scalar cast, performing all the necessary stages 4600/// except the final cast and returning the kind required. 4601CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 4602 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 4603 // Also, callers should have filtered out the invalid cases with 4604 // pointers. Everything else should be possible. 4605 4606 QualType SrcTy = Src.get()->getType(); 4607 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 4608 return CK_NoOp; 4609 4610 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 4611 case Type::STK_MemberPointer: 4612 llvm_unreachable("member pointer type in C"); 4613 4614 case Type::STK_CPointer: 4615 case Type::STK_BlockPointer: 4616 case Type::STK_ObjCObjectPointer: 4617 switch (DestTy->getScalarTypeKind()) { 4618 case Type::STK_CPointer: 4619 return CK_BitCast; 4620 case Type::STK_BlockPointer: 4621 return (SrcKind == Type::STK_BlockPointer 4622 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 4623 case Type::STK_ObjCObjectPointer: 4624 if (SrcKind == Type::STK_ObjCObjectPointer) 4625 return CK_BitCast; 4626 if (SrcKind == Type::STK_CPointer) 4627 return CK_CPointerToObjCPointerCast; 4628 maybeExtendBlockObject(*this, Src); 4629 return CK_BlockPointerToObjCPointerCast; 4630 case Type::STK_Bool: 4631 return CK_PointerToBoolean; 4632 case Type::STK_Integral: 4633 return CK_PointerToIntegral; 4634 case Type::STK_Floating: 4635 case Type::STK_FloatingComplex: 4636 case Type::STK_IntegralComplex: 4637 case Type::STK_MemberPointer: 4638 llvm_unreachable("illegal cast from pointer"); 4639 } 4640 llvm_unreachable("Should have returned before this"); 4641 4642 case Type::STK_Bool: // casting from bool is like casting from an integer 4643 case Type::STK_Integral: 4644 switch (DestTy->getScalarTypeKind()) { 4645 case Type::STK_CPointer: 4646 case Type::STK_ObjCObjectPointer: 4647 case Type::STK_BlockPointer: 4648 if (Src.get()->isNullPointerConstant(Context, 4649 Expr::NPC_ValueDependentIsNull)) 4650 return CK_NullToPointer; 4651 return CK_IntegralToPointer; 4652 case Type::STK_Bool: 4653 return CK_IntegralToBoolean; 4654 case Type::STK_Integral: 4655 return CK_IntegralCast; 4656 case Type::STK_Floating: 4657 return CK_IntegralToFloating; 4658 case Type::STK_IntegralComplex: 4659 Src = ImpCastExprToType(Src.take(), 4660 DestTy->castAs<ComplexType>()->getElementType(), 4661 CK_IntegralCast); 4662 return CK_IntegralRealToComplex; 4663 case Type::STK_FloatingComplex: 4664 Src = ImpCastExprToType(Src.take(), 4665 DestTy->castAs<ComplexType>()->getElementType(), 4666 CK_IntegralToFloating); 4667 return CK_FloatingRealToComplex; 4668 case Type::STK_MemberPointer: 4669 llvm_unreachable("member pointer type in C"); 4670 } 4671 llvm_unreachable("Should have returned before this"); 4672 4673 case Type::STK_Floating: 4674 switch (DestTy->getScalarTypeKind()) { 4675 case Type::STK_Floating: 4676 return CK_FloatingCast; 4677 case Type::STK_Bool: 4678 return CK_FloatingToBoolean; 4679 case Type::STK_Integral: 4680 return CK_FloatingToIntegral; 4681 case Type::STK_FloatingComplex: 4682 Src = ImpCastExprToType(Src.take(), 4683 DestTy->castAs<ComplexType>()->getElementType(), 4684 CK_FloatingCast); 4685 return CK_FloatingRealToComplex; 4686 case Type::STK_IntegralComplex: 4687 Src = ImpCastExprToType(Src.take(), 4688 DestTy->castAs<ComplexType>()->getElementType(), 4689 CK_FloatingToIntegral); 4690 return CK_IntegralRealToComplex; 4691 case Type::STK_CPointer: 4692 case Type::STK_ObjCObjectPointer: 4693 case Type::STK_BlockPointer: 4694 llvm_unreachable("valid float->pointer cast?"); 4695 case Type::STK_MemberPointer: 4696 llvm_unreachable("member pointer type in C"); 4697 } 4698 llvm_unreachable("Should have returned before this"); 4699 4700 case Type::STK_FloatingComplex: 4701 switch (DestTy->getScalarTypeKind()) { 4702 case Type::STK_FloatingComplex: 4703 return CK_FloatingComplexCast; 4704 case Type::STK_IntegralComplex: 4705 return CK_FloatingComplexToIntegralComplex; 4706 case Type::STK_Floating: { 4707 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4708 if (Context.hasSameType(ET, DestTy)) 4709 return CK_FloatingComplexToReal; 4710 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal); 4711 return CK_FloatingCast; 4712 } 4713 case Type::STK_Bool: 4714 return CK_FloatingComplexToBoolean; 4715 case Type::STK_Integral: 4716 Src = ImpCastExprToType(Src.take(), 4717 SrcTy->castAs<ComplexType>()->getElementType(), 4718 CK_FloatingComplexToReal); 4719 return CK_FloatingToIntegral; 4720 case Type::STK_CPointer: 4721 case Type::STK_ObjCObjectPointer: 4722 case Type::STK_BlockPointer: 4723 llvm_unreachable("valid complex float->pointer cast?"); 4724 case Type::STK_MemberPointer: 4725 llvm_unreachable("member pointer type in C"); 4726 } 4727 llvm_unreachable("Should have returned before this"); 4728 4729 case Type::STK_IntegralComplex: 4730 switch (DestTy->getScalarTypeKind()) { 4731 case Type::STK_FloatingComplex: 4732 return CK_IntegralComplexToFloatingComplex; 4733 case Type::STK_IntegralComplex: 4734 return CK_IntegralComplexCast; 4735 case Type::STK_Integral: { 4736 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4737 if (Context.hasSameType(ET, DestTy)) 4738 return CK_IntegralComplexToReal; 4739 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal); 4740 return CK_IntegralCast; 4741 } 4742 case Type::STK_Bool: 4743 return CK_IntegralComplexToBoolean; 4744 case Type::STK_Floating: 4745 Src = ImpCastExprToType(Src.take(), 4746 SrcTy->castAs<ComplexType>()->getElementType(), 4747 CK_IntegralComplexToReal); 4748 return CK_IntegralToFloating; 4749 case Type::STK_CPointer: 4750 case Type::STK_ObjCObjectPointer: 4751 case Type::STK_BlockPointer: 4752 llvm_unreachable("valid complex int->pointer cast?"); 4753 case Type::STK_MemberPointer: 4754 llvm_unreachable("member pointer type in C"); 4755 } 4756 llvm_unreachable("Should have returned before this"); 4757 } 4758 4759 llvm_unreachable("Unhandled scalar cast"); 4760} 4761 4762bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 4763 CastKind &Kind) { 4764 assert(VectorTy->isVectorType() && "Not a vector type!"); 4765 4766 if (Ty->isVectorType() || Ty->isIntegerType()) { 4767 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty)) 4768 return Diag(R.getBegin(), 4769 Ty->isVectorType() ? 4770 diag::err_invalid_conversion_between_vectors : 4771 diag::err_invalid_conversion_between_vector_and_integer) 4772 << VectorTy << Ty << R; 4773 } else 4774 return Diag(R.getBegin(), 4775 diag::err_invalid_conversion_between_vector_and_scalar) 4776 << VectorTy << Ty << R; 4777 4778 Kind = CK_BitCast; 4779 return false; 4780} 4781 4782ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 4783 Expr *CastExpr, CastKind &Kind) { 4784 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 4785 4786 QualType SrcTy = CastExpr->getType(); 4787 4788 // If SrcTy is a VectorType, the total size must match to explicitly cast to 4789 // an ExtVectorType. 4790 // In OpenCL, casts between vectors of different types are not allowed. 4791 // (See OpenCL 6.2). 4792 if (SrcTy->isVectorType()) { 4793 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy) 4794 || (getLangOpts().OpenCL && 4795 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 4796 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 4797 << DestTy << SrcTy << R; 4798 return ExprError(); 4799 } 4800 Kind = CK_BitCast; 4801 return Owned(CastExpr); 4802 } 4803 4804 // All non-pointer scalars can be cast to ExtVector type. The appropriate 4805 // conversion will take place first from scalar to elt type, and then 4806 // splat from elt type to vector. 4807 if (SrcTy->isPointerType()) 4808 return Diag(R.getBegin(), 4809 diag::err_invalid_conversion_between_vector_and_scalar) 4810 << DestTy << SrcTy << R; 4811 4812 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 4813 ExprResult CastExprRes = Owned(CastExpr); 4814 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 4815 if (CastExprRes.isInvalid()) 4816 return ExprError(); 4817 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take(); 4818 4819 Kind = CK_VectorSplat; 4820 return Owned(CastExpr); 4821} 4822 4823ExprResult 4824Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 4825 Declarator &D, ParsedType &Ty, 4826 SourceLocation RParenLoc, Expr *CastExpr) { 4827 assert(!D.isInvalidType() && (CastExpr != 0) && 4828 "ActOnCastExpr(): missing type or expr"); 4829 4830 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 4831 if (D.isInvalidType()) 4832 return ExprError(); 4833 4834 if (getLangOpts().CPlusPlus) { 4835 // Check that there are no default arguments (C++ only). 4836 CheckExtraCXXDefaultArguments(D); 4837 } 4838 4839 checkUnusedDeclAttributes(D); 4840 4841 QualType castType = castTInfo->getType(); 4842 Ty = CreateParsedType(castType, castTInfo); 4843 4844 bool isVectorLiteral = false; 4845 4846 // Check for an altivec or OpenCL literal, 4847 // i.e. all the elements are integer constants. 4848 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 4849 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 4850 if ((getLangOpts().AltiVec || getLangOpts().OpenCL) 4851 && castType->isVectorType() && (PE || PLE)) { 4852 if (PLE && PLE->getNumExprs() == 0) { 4853 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 4854 return ExprError(); 4855 } 4856 if (PE || PLE->getNumExprs() == 1) { 4857 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 4858 if (!E->getType()->isVectorType()) 4859 isVectorLiteral = true; 4860 } 4861 else 4862 isVectorLiteral = true; 4863 } 4864 4865 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 4866 // then handle it as such. 4867 if (isVectorLiteral) 4868 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 4869 4870 // If the Expr being casted is a ParenListExpr, handle it specially. 4871 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 4872 // sequence of BinOp comma operators. 4873 if (isa<ParenListExpr>(CastExpr)) { 4874 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 4875 if (Result.isInvalid()) return ExprError(); 4876 CastExpr = Result.take(); 4877 } 4878 4879 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 4880} 4881 4882ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 4883 SourceLocation RParenLoc, Expr *E, 4884 TypeSourceInfo *TInfo) { 4885 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 4886 "Expected paren or paren list expression"); 4887 4888 Expr **exprs; 4889 unsigned numExprs; 4890 Expr *subExpr; 4891 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 4892 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 4893 LiteralLParenLoc = PE->getLParenLoc(); 4894 LiteralRParenLoc = PE->getRParenLoc(); 4895 exprs = PE->getExprs(); 4896 numExprs = PE->getNumExprs(); 4897 } else { // isa<ParenExpr> by assertion at function entrance 4898 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 4899 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 4900 subExpr = cast<ParenExpr>(E)->getSubExpr(); 4901 exprs = &subExpr; 4902 numExprs = 1; 4903 } 4904 4905 QualType Ty = TInfo->getType(); 4906 assert(Ty->isVectorType() && "Expected vector type"); 4907 4908 SmallVector<Expr *, 8> initExprs; 4909 const VectorType *VTy = Ty->getAs<VectorType>(); 4910 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 4911 4912 // '(...)' form of vector initialization in AltiVec: the number of 4913 // initializers must be one or must match the size of the vector. 4914 // If a single value is specified in the initializer then it will be 4915 // replicated to all the components of the vector 4916 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 4917 // The number of initializers must be one or must match the size of the 4918 // vector. If a single value is specified in the initializer then it will 4919 // be replicated to all the components of the vector 4920 if (numExprs == 1) { 4921 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 4922 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 4923 if (Literal.isInvalid()) 4924 return ExprError(); 4925 Literal = ImpCastExprToType(Literal.take(), ElemTy, 4926 PrepareScalarCast(Literal, ElemTy)); 4927 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 4928 } 4929 else if (numExprs < numElems) { 4930 Diag(E->getExprLoc(), 4931 diag::err_incorrect_number_of_vector_initializers); 4932 return ExprError(); 4933 } 4934 else 4935 initExprs.append(exprs, exprs + numExprs); 4936 } 4937 else { 4938 // For OpenCL, when the number of initializers is a single value, 4939 // it will be replicated to all components of the vector. 4940 if (getLangOpts().OpenCL && 4941 VTy->getVectorKind() == VectorType::GenericVector && 4942 numExprs == 1) { 4943 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 4944 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 4945 if (Literal.isInvalid()) 4946 return ExprError(); 4947 Literal = ImpCastExprToType(Literal.take(), ElemTy, 4948 PrepareScalarCast(Literal, ElemTy)); 4949 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 4950 } 4951 4952 initExprs.append(exprs, exprs + numExprs); 4953 } 4954 // FIXME: This means that pretty-printing the final AST will produce curly 4955 // braces instead of the original commas. 4956 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 4957 initExprs, LiteralRParenLoc); 4958 initE->setType(Ty); 4959 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 4960} 4961 4962/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 4963/// the ParenListExpr into a sequence of comma binary operators. 4964ExprResult 4965Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 4966 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 4967 if (!E) 4968 return Owned(OrigExpr); 4969 4970 ExprResult Result(E->getExpr(0)); 4971 4972 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 4973 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 4974 E->getExpr(i)); 4975 4976 if (Result.isInvalid()) return ExprError(); 4977 4978 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 4979} 4980 4981ExprResult Sema::ActOnParenListExpr(SourceLocation L, 4982 SourceLocation R, 4983 MultiExprArg Val) { 4984 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 4985 return Owned(expr); 4986} 4987 4988/// \brief Emit a specialized diagnostic when one expression is a null pointer 4989/// constant and the other is not a pointer. Returns true if a diagnostic is 4990/// emitted. 4991bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 4992 SourceLocation QuestionLoc) { 4993 Expr *NullExpr = LHSExpr; 4994 Expr *NonPointerExpr = RHSExpr; 4995 Expr::NullPointerConstantKind NullKind = 4996 NullExpr->isNullPointerConstant(Context, 4997 Expr::NPC_ValueDependentIsNotNull); 4998 4999 if (NullKind == Expr::NPCK_NotNull) { 5000 NullExpr = RHSExpr; 5001 NonPointerExpr = LHSExpr; 5002 NullKind = 5003 NullExpr->isNullPointerConstant(Context, 5004 Expr::NPC_ValueDependentIsNotNull); 5005 } 5006 5007 if (NullKind == Expr::NPCK_NotNull) 5008 return false; 5009 5010 if (NullKind == Expr::NPCK_ZeroExpression) 5011 return false; 5012 5013 if (NullKind == Expr::NPCK_ZeroLiteral) { 5014 // In this case, check to make sure that we got here from a "NULL" 5015 // string in the source code. 5016 NullExpr = NullExpr->IgnoreParenImpCasts(); 5017 SourceLocation loc = NullExpr->getExprLoc(); 5018 if (!findMacroSpelling(loc, "NULL")) 5019 return false; 5020 } 5021 5022 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 5023 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 5024 << NonPointerExpr->getType() << DiagType 5025 << NonPointerExpr->getSourceRange(); 5026 return true; 5027} 5028 5029/// \brief Return false if the condition expression is valid, true otherwise. 5030static bool checkCondition(Sema &S, Expr *Cond) { 5031 QualType CondTy = Cond->getType(); 5032 5033 // C99 6.5.15p2 5034 if (CondTy->isScalarType()) return false; 5035 5036 // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar. 5037 if (S.getLangOpts().OpenCL && CondTy->isVectorType()) 5038 return false; 5039 5040 // Emit the proper error message. 5041 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ? 5042 diag::err_typecheck_cond_expect_scalar : 5043 diag::err_typecheck_cond_expect_scalar_or_vector) 5044 << CondTy; 5045 return true; 5046} 5047 5048/// \brief Return false if the two expressions can be converted to a vector, 5049/// true otherwise 5050static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS, 5051 ExprResult &RHS, 5052 QualType CondTy) { 5053 // Both operands should be of scalar type. 5054 if (!LHS.get()->getType()->isScalarType()) { 5055 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5056 << CondTy; 5057 return true; 5058 } 5059 if (!RHS.get()->getType()->isScalarType()) { 5060 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5061 << CondTy; 5062 return true; 5063 } 5064 5065 // Implicity convert these scalars to the type of the condition. 5066 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast); 5067 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast); 5068 return false; 5069} 5070 5071/// \brief Handle when one or both operands are void type. 5072static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 5073 ExprResult &RHS) { 5074 Expr *LHSExpr = LHS.get(); 5075 Expr *RHSExpr = RHS.get(); 5076 5077 if (!LHSExpr->getType()->isVoidType()) 5078 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5079 << RHSExpr->getSourceRange(); 5080 if (!RHSExpr->getType()->isVoidType()) 5081 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5082 << LHSExpr->getSourceRange(); 5083 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid); 5084 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid); 5085 return S.Context.VoidTy; 5086} 5087 5088/// \brief Return false if the NullExpr can be promoted to PointerTy, 5089/// true otherwise. 5090static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 5091 QualType PointerTy) { 5092 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 5093 !NullExpr.get()->isNullPointerConstant(S.Context, 5094 Expr::NPC_ValueDependentIsNull)) 5095 return true; 5096 5097 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer); 5098 return false; 5099} 5100 5101/// \brief Checks compatibility between two pointers and return the resulting 5102/// type. 5103static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 5104 ExprResult &RHS, 5105 SourceLocation Loc) { 5106 QualType LHSTy = LHS.get()->getType(); 5107 QualType RHSTy = RHS.get()->getType(); 5108 5109 if (S.Context.hasSameType(LHSTy, RHSTy)) { 5110 // Two identical pointers types are always compatible. 5111 return LHSTy; 5112 } 5113 5114 QualType lhptee, rhptee; 5115 5116 // Get the pointee types. 5117 bool IsBlockPointer = false; 5118 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 5119 lhptee = LHSBTy->getPointeeType(); 5120 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 5121 IsBlockPointer = true; 5122 } else { 5123 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 5124 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 5125 } 5126 5127 // C99 6.5.15p6: If both operands are pointers to compatible types or to 5128 // differently qualified versions of compatible types, the result type is 5129 // a pointer to an appropriately qualified version of the composite 5130 // type. 5131 5132 // Only CVR-qualifiers exist in the standard, and the differently-qualified 5133 // clause doesn't make sense for our extensions. E.g. address space 2 should 5134 // be incompatible with address space 3: they may live on different devices or 5135 // anything. 5136 Qualifiers lhQual = lhptee.getQualifiers(); 5137 Qualifiers rhQual = rhptee.getQualifiers(); 5138 5139 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 5140 lhQual.removeCVRQualifiers(); 5141 rhQual.removeCVRQualifiers(); 5142 5143 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 5144 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 5145 5146 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 5147 5148 if (CompositeTy.isNull()) { 5149 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers) 5150 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5151 << RHS.get()->getSourceRange(); 5152 // In this situation, we assume void* type. No especially good 5153 // reason, but this is what gcc does, and we do have to pick 5154 // to get a consistent AST. 5155 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 5156 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5157 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5158 return incompatTy; 5159 } 5160 5161 // The pointer types are compatible. 5162 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 5163 if (IsBlockPointer) 5164 ResultTy = S.Context.getBlockPointerType(ResultTy); 5165 else 5166 ResultTy = S.Context.getPointerType(ResultTy); 5167 5168 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast); 5169 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast); 5170 return ResultTy; 5171} 5172 5173/// \brief Return the resulting type when the operands are both block pointers. 5174static QualType checkConditionalBlockPointerCompatibility(Sema &S, 5175 ExprResult &LHS, 5176 ExprResult &RHS, 5177 SourceLocation Loc) { 5178 QualType LHSTy = LHS.get()->getType(); 5179 QualType RHSTy = RHS.get()->getType(); 5180 5181 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 5182 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 5183 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 5184 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5185 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5186 return destType; 5187 } 5188 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 5189 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5190 << RHS.get()->getSourceRange(); 5191 return QualType(); 5192 } 5193 5194 // We have 2 block pointer types. 5195 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5196} 5197 5198/// \brief Return the resulting type when the operands are both pointers. 5199static QualType 5200checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 5201 ExprResult &RHS, 5202 SourceLocation Loc) { 5203 // get the pointer types 5204 QualType LHSTy = LHS.get()->getType(); 5205 QualType RHSTy = RHS.get()->getType(); 5206 5207 // get the "pointed to" types 5208 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5209 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5210 5211 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 5212 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 5213 // Figure out necessary qualifiers (C99 6.5.15p6) 5214 QualType destPointee 5215 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5216 QualType destType = S.Context.getPointerType(destPointee); 5217 // Add qualifiers if necessary. 5218 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5219 // Promote to void*. 5220 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5221 return destType; 5222 } 5223 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 5224 QualType destPointee 5225 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5226 QualType destType = S.Context.getPointerType(destPointee); 5227 // Add qualifiers if necessary. 5228 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5229 // Promote to void*. 5230 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5231 return destType; 5232 } 5233 5234 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5235} 5236 5237/// \brief Return false if the first expression is not an integer and the second 5238/// expression is not a pointer, true otherwise. 5239static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 5240 Expr* PointerExpr, SourceLocation Loc, 5241 bool IsIntFirstExpr) { 5242 if (!PointerExpr->getType()->isPointerType() || 5243 !Int.get()->getType()->isIntegerType()) 5244 return false; 5245 5246 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 5247 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 5248 5249 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch) 5250 << Expr1->getType() << Expr2->getType() 5251 << Expr1->getSourceRange() << Expr2->getSourceRange(); 5252 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(), 5253 CK_IntegralToPointer); 5254 return true; 5255} 5256 5257/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 5258/// In that case, LHS = cond. 5259/// C99 6.5.15 5260QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 5261 ExprResult &RHS, ExprValueKind &VK, 5262 ExprObjectKind &OK, 5263 SourceLocation QuestionLoc) { 5264 5265 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 5266 if (!LHSResult.isUsable()) return QualType(); 5267 LHS = LHSResult; 5268 5269 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 5270 if (!RHSResult.isUsable()) return QualType(); 5271 RHS = RHSResult; 5272 5273 // C++ is sufficiently different to merit its own checker. 5274 if (getLangOpts().CPlusPlus) 5275 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 5276 5277 VK = VK_RValue; 5278 OK = OK_Ordinary; 5279 5280 Cond = UsualUnaryConversions(Cond.take()); 5281 if (Cond.isInvalid()) 5282 return QualType(); 5283 LHS = UsualUnaryConversions(LHS.take()); 5284 if (LHS.isInvalid()) 5285 return QualType(); 5286 RHS = UsualUnaryConversions(RHS.take()); 5287 if (RHS.isInvalid()) 5288 return QualType(); 5289 5290 QualType CondTy = Cond.get()->getType(); 5291 QualType LHSTy = LHS.get()->getType(); 5292 QualType RHSTy = RHS.get()->getType(); 5293 5294 // first, check the condition. 5295 if (checkCondition(*this, Cond.get())) 5296 return QualType(); 5297 5298 // Now check the two expressions. 5299 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 5300 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false); 5301 5302 // If the condition is a vector, and both operands are scalar, 5303 // attempt to implicity convert them to the vector type to act like the 5304 // built in select. (OpenCL v1.1 s6.3.i) 5305 if (getLangOpts().OpenCL && CondTy->isVectorType()) 5306 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy)) 5307 return QualType(); 5308 5309 // If both operands have arithmetic type, do the usual arithmetic conversions 5310 // to find a common type: C99 6.5.15p3,5. 5311 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 5312 UsualArithmeticConversions(LHS, RHS); 5313 if (LHS.isInvalid() || RHS.isInvalid()) 5314 return QualType(); 5315 return LHS.get()->getType(); 5316 } 5317 5318 // If both operands are the same structure or union type, the result is that 5319 // type. 5320 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 5321 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 5322 if (LHSRT->getDecl() == RHSRT->getDecl()) 5323 // "If both the operands have structure or union type, the result has 5324 // that type." This implies that CV qualifiers are dropped. 5325 return LHSTy.getUnqualifiedType(); 5326 // FIXME: Type of conditional expression must be complete in C mode. 5327 } 5328 5329 // C99 6.5.15p5: "If both operands have void type, the result has void type." 5330 // The following || allows only one side to be void (a GCC-ism). 5331 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 5332 return checkConditionalVoidType(*this, LHS, RHS); 5333 } 5334 5335 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 5336 // the type of the other operand." 5337 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 5338 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 5339 5340 // All objective-c pointer type analysis is done here. 5341 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 5342 QuestionLoc); 5343 if (LHS.isInvalid() || RHS.isInvalid()) 5344 return QualType(); 5345 if (!compositeType.isNull()) 5346 return compositeType; 5347 5348 5349 // Handle block pointer types. 5350 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 5351 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 5352 QuestionLoc); 5353 5354 // Check constraints for C object pointers types (C99 6.5.15p3,6). 5355 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 5356 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 5357 QuestionLoc); 5358 5359 // GCC compatibility: soften pointer/integer mismatch. Note that 5360 // null pointers have been filtered out by this point. 5361 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 5362 /*isIntFirstExpr=*/true)) 5363 return RHSTy; 5364 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 5365 /*isIntFirstExpr=*/false)) 5366 return LHSTy; 5367 5368 // Emit a better diagnostic if one of the expressions is a null pointer 5369 // constant and the other is not a pointer type. In this case, the user most 5370 // likely forgot to take the address of the other expression. 5371 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 5372 return QualType(); 5373 5374 // Otherwise, the operands are not compatible. 5375 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 5376 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5377 << RHS.get()->getSourceRange(); 5378 return QualType(); 5379} 5380 5381/// FindCompositeObjCPointerType - Helper method to find composite type of 5382/// two objective-c pointer types of the two input expressions. 5383QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 5384 SourceLocation QuestionLoc) { 5385 QualType LHSTy = LHS.get()->getType(); 5386 QualType RHSTy = RHS.get()->getType(); 5387 5388 // Handle things like Class and struct objc_class*. Here we case the result 5389 // to the pseudo-builtin, because that will be implicitly cast back to the 5390 // redefinition type if an attempt is made to access its fields. 5391 if (LHSTy->isObjCClassType() && 5392 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 5393 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5394 return LHSTy; 5395 } 5396 if (RHSTy->isObjCClassType() && 5397 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 5398 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5399 return RHSTy; 5400 } 5401 // And the same for struct objc_object* / id 5402 if (LHSTy->isObjCIdType() && 5403 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 5404 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5405 return LHSTy; 5406 } 5407 if (RHSTy->isObjCIdType() && 5408 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 5409 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5410 return RHSTy; 5411 } 5412 // And the same for struct objc_selector* / SEL 5413 if (Context.isObjCSelType(LHSTy) && 5414 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 5415 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast); 5416 return LHSTy; 5417 } 5418 if (Context.isObjCSelType(RHSTy) && 5419 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 5420 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast); 5421 return RHSTy; 5422 } 5423 // Check constraints for Objective-C object pointers types. 5424 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 5425 5426 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 5427 // Two identical object pointer types are always compatible. 5428 return LHSTy; 5429 } 5430 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 5431 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 5432 QualType compositeType = LHSTy; 5433 5434 // If both operands are interfaces and either operand can be 5435 // assigned to the other, use that type as the composite 5436 // type. This allows 5437 // xxx ? (A*) a : (B*) b 5438 // where B is a subclass of A. 5439 // 5440 // Additionally, as for assignment, if either type is 'id' 5441 // allow silent coercion. Finally, if the types are 5442 // incompatible then make sure to use 'id' as the composite 5443 // type so the result is acceptable for sending messages to. 5444 5445 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 5446 // It could return the composite type. 5447 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 5448 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 5449 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 5450 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 5451 } else if ((LHSTy->isObjCQualifiedIdType() || 5452 RHSTy->isObjCQualifiedIdType()) && 5453 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 5454 // Need to handle "id<xx>" explicitly. 5455 // GCC allows qualified id and any Objective-C type to devolve to 5456 // id. Currently localizing to here until clear this should be 5457 // part of ObjCQualifiedIdTypesAreCompatible. 5458 compositeType = Context.getObjCIdType(); 5459 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 5460 compositeType = Context.getObjCIdType(); 5461 } else if (!(compositeType = 5462 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 5463 ; 5464 else { 5465 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 5466 << LHSTy << RHSTy 5467 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5468 QualType incompatTy = Context.getObjCIdType(); 5469 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5470 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5471 return incompatTy; 5472 } 5473 // The object pointer types are compatible. 5474 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast); 5475 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast); 5476 return compositeType; 5477 } 5478 // Check Objective-C object pointer types and 'void *' 5479 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 5480 if (getLangOpts().ObjCAutoRefCount) { 5481 // ARC forbids the implicit conversion of object pointers to 'void *', 5482 // so these types are not compatible. 5483 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5484 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5485 LHS = RHS = true; 5486 return QualType(); 5487 } 5488 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5489 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5490 QualType destPointee 5491 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5492 QualType destType = Context.getPointerType(destPointee); 5493 // Add qualifiers if necessary. 5494 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5495 // Promote to void*. 5496 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5497 return destType; 5498 } 5499 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 5500 if (getLangOpts().ObjCAutoRefCount) { 5501 // ARC forbids the implicit conversion of object pointers to 'void *', 5502 // so these types are not compatible. 5503 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5504 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5505 LHS = RHS = true; 5506 return QualType(); 5507 } 5508 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5509 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5510 QualType destPointee 5511 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5512 QualType destType = Context.getPointerType(destPointee); 5513 // Add qualifiers if necessary. 5514 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5515 // Promote to void*. 5516 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5517 return destType; 5518 } 5519 return QualType(); 5520} 5521 5522/// SuggestParentheses - Emit a note with a fixit hint that wraps 5523/// ParenRange in parentheses. 5524static void SuggestParentheses(Sema &Self, SourceLocation Loc, 5525 const PartialDiagnostic &Note, 5526 SourceRange ParenRange) { 5527 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 5528 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 5529 EndLoc.isValid()) { 5530 Self.Diag(Loc, Note) 5531 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 5532 << FixItHint::CreateInsertion(EndLoc, ")"); 5533 } else { 5534 // We can't display the parentheses, so just show the bare note. 5535 Self.Diag(Loc, Note) << ParenRange; 5536 } 5537} 5538 5539static bool IsArithmeticOp(BinaryOperatorKind Opc) { 5540 return Opc >= BO_Mul && Opc <= BO_Shr; 5541} 5542 5543/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 5544/// expression, either using a built-in or overloaded operator, 5545/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 5546/// expression. 5547static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 5548 Expr **RHSExprs) { 5549 // Don't strip parenthesis: we should not warn if E is in parenthesis. 5550 E = E->IgnoreImpCasts(); 5551 E = E->IgnoreConversionOperator(); 5552 E = E->IgnoreImpCasts(); 5553 5554 // Built-in binary operator. 5555 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 5556 if (IsArithmeticOp(OP->getOpcode())) { 5557 *Opcode = OP->getOpcode(); 5558 *RHSExprs = OP->getRHS(); 5559 return true; 5560 } 5561 } 5562 5563 // Overloaded operator. 5564 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 5565 if (Call->getNumArgs() != 2) 5566 return false; 5567 5568 // Make sure this is really a binary operator that is safe to pass into 5569 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 5570 OverloadedOperatorKind OO = Call->getOperator(); 5571 if (OO < OO_Plus || OO > OO_Arrow || 5572 OO == OO_PlusPlus || OO == OO_MinusMinus) 5573 return false; 5574 5575 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 5576 if (IsArithmeticOp(OpKind)) { 5577 *Opcode = OpKind; 5578 *RHSExprs = Call->getArg(1); 5579 return true; 5580 } 5581 } 5582 5583 return false; 5584} 5585 5586static bool IsLogicOp(BinaryOperatorKind Opc) { 5587 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 5588} 5589 5590/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 5591/// or is a logical expression such as (x==y) which has int type, but is 5592/// commonly interpreted as boolean. 5593static bool ExprLooksBoolean(Expr *E) { 5594 E = E->IgnoreParenImpCasts(); 5595 5596 if (E->getType()->isBooleanType()) 5597 return true; 5598 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 5599 return IsLogicOp(OP->getOpcode()); 5600 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 5601 return OP->getOpcode() == UO_LNot; 5602 5603 return false; 5604} 5605 5606/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 5607/// and binary operator are mixed in a way that suggests the programmer assumed 5608/// the conditional operator has higher precedence, for example: 5609/// "int x = a + someBinaryCondition ? 1 : 2". 5610static void DiagnoseConditionalPrecedence(Sema &Self, 5611 SourceLocation OpLoc, 5612 Expr *Condition, 5613 Expr *LHSExpr, 5614 Expr *RHSExpr) { 5615 BinaryOperatorKind CondOpcode; 5616 Expr *CondRHS; 5617 5618 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 5619 return; 5620 if (!ExprLooksBoolean(CondRHS)) 5621 return; 5622 5623 // The condition is an arithmetic binary expression, with a right- 5624 // hand side that looks boolean, so warn. 5625 5626 Self.Diag(OpLoc, diag::warn_precedence_conditional) 5627 << Condition->getSourceRange() 5628 << BinaryOperator::getOpcodeStr(CondOpcode); 5629 5630 SuggestParentheses(Self, OpLoc, 5631 Self.PDiag(diag::note_precedence_silence) 5632 << BinaryOperator::getOpcodeStr(CondOpcode), 5633 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 5634 5635 SuggestParentheses(Self, OpLoc, 5636 Self.PDiag(diag::note_precedence_conditional_first), 5637 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 5638} 5639 5640/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 5641/// in the case of a the GNU conditional expr extension. 5642ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 5643 SourceLocation ColonLoc, 5644 Expr *CondExpr, Expr *LHSExpr, 5645 Expr *RHSExpr) { 5646 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 5647 // was the condition. 5648 OpaqueValueExpr *opaqueValue = 0; 5649 Expr *commonExpr = 0; 5650 if (LHSExpr == 0) { 5651 commonExpr = CondExpr; 5652 // Lower out placeholder types first. This is important so that we don't 5653 // try to capture a placeholder. This happens in few cases in C++; such 5654 // as Objective-C++'s dictionary subscripting syntax. 5655 if (commonExpr->hasPlaceholderType()) { 5656 ExprResult result = CheckPlaceholderExpr(commonExpr); 5657 if (!result.isUsable()) return ExprError(); 5658 commonExpr = result.take(); 5659 } 5660 // We usually want to apply unary conversions *before* saving, except 5661 // in the special case of a C++ l-value conditional. 5662 if (!(getLangOpts().CPlusPlus 5663 && !commonExpr->isTypeDependent() 5664 && commonExpr->getValueKind() == RHSExpr->getValueKind() 5665 && commonExpr->isGLValue() 5666 && commonExpr->isOrdinaryOrBitFieldObject() 5667 && RHSExpr->isOrdinaryOrBitFieldObject() 5668 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 5669 ExprResult commonRes = UsualUnaryConversions(commonExpr); 5670 if (commonRes.isInvalid()) 5671 return ExprError(); 5672 commonExpr = commonRes.take(); 5673 } 5674 5675 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 5676 commonExpr->getType(), 5677 commonExpr->getValueKind(), 5678 commonExpr->getObjectKind(), 5679 commonExpr); 5680 LHSExpr = CondExpr = opaqueValue; 5681 } 5682 5683 ExprValueKind VK = VK_RValue; 5684 ExprObjectKind OK = OK_Ordinary; 5685 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 5686 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 5687 VK, OK, QuestionLoc); 5688 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 5689 RHS.isInvalid()) 5690 return ExprError(); 5691 5692 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 5693 RHS.get()); 5694 5695 if (!commonExpr) 5696 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc, 5697 LHS.take(), ColonLoc, 5698 RHS.take(), result, VK, OK)); 5699 5700 return Owned(new (Context) 5701 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(), 5702 RHS.take(), QuestionLoc, ColonLoc, result, VK, 5703 OK)); 5704} 5705 5706// checkPointerTypesForAssignment - This is a very tricky routine (despite 5707// being closely modeled after the C99 spec:-). The odd characteristic of this 5708// routine is it effectively iqnores the qualifiers on the top level pointee. 5709// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 5710// FIXME: add a couple examples in this comment. 5711static Sema::AssignConvertType 5712checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 5713 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 5714 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 5715 5716 // get the "pointed to" type (ignoring qualifiers at the top level) 5717 const Type *lhptee, *rhptee; 5718 Qualifiers lhq, rhq; 5719 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split(); 5720 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split(); 5721 5722 Sema::AssignConvertType ConvTy = Sema::Compatible; 5723 5724 // C99 6.5.16.1p1: This following citation is common to constraints 5725 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 5726 // qualifiers of the type *pointed to* by the right; 5727 Qualifiers lq; 5728 5729 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 5730 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 5731 lhq.compatiblyIncludesObjCLifetime(rhq)) { 5732 // Ignore lifetime for further calculation. 5733 lhq.removeObjCLifetime(); 5734 rhq.removeObjCLifetime(); 5735 } 5736 5737 if (!lhq.compatiblyIncludes(rhq)) { 5738 // Treat address-space mismatches as fatal. TODO: address subspaces 5739 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 5740 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5741 5742 // It's okay to add or remove GC or lifetime qualifiers when converting to 5743 // and from void*. 5744 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 5745 .compatiblyIncludes( 5746 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 5747 && (lhptee->isVoidType() || rhptee->isVoidType())) 5748 ; // keep old 5749 5750 // Treat lifetime mismatches as fatal. 5751 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 5752 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 5753 5754 // For GCC compatibility, other qualifier mismatches are treated 5755 // as still compatible in C. 5756 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 5757 } 5758 5759 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 5760 // incomplete type and the other is a pointer to a qualified or unqualified 5761 // version of void... 5762 if (lhptee->isVoidType()) { 5763 if (rhptee->isIncompleteOrObjectType()) 5764 return ConvTy; 5765 5766 // As an extension, we allow cast to/from void* to function pointer. 5767 assert(rhptee->isFunctionType()); 5768 return Sema::FunctionVoidPointer; 5769 } 5770 5771 if (rhptee->isVoidType()) { 5772 if (lhptee->isIncompleteOrObjectType()) 5773 return ConvTy; 5774 5775 // As an extension, we allow cast to/from void* to function pointer. 5776 assert(lhptee->isFunctionType()); 5777 return Sema::FunctionVoidPointer; 5778 } 5779 5780 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 5781 // unqualified versions of compatible types, ... 5782 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 5783 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 5784 // Check if the pointee types are compatible ignoring the sign. 5785 // We explicitly check for char so that we catch "char" vs 5786 // "unsigned char" on systems where "char" is unsigned. 5787 if (lhptee->isCharType()) 5788 ltrans = S.Context.UnsignedCharTy; 5789 else if (lhptee->hasSignedIntegerRepresentation()) 5790 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 5791 5792 if (rhptee->isCharType()) 5793 rtrans = S.Context.UnsignedCharTy; 5794 else if (rhptee->hasSignedIntegerRepresentation()) 5795 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 5796 5797 if (ltrans == rtrans) { 5798 // Types are compatible ignoring the sign. Qualifier incompatibility 5799 // takes priority over sign incompatibility because the sign 5800 // warning can be disabled. 5801 if (ConvTy != Sema::Compatible) 5802 return ConvTy; 5803 5804 return Sema::IncompatiblePointerSign; 5805 } 5806 5807 // If we are a multi-level pointer, it's possible that our issue is simply 5808 // one of qualification - e.g. char ** -> const char ** is not allowed. If 5809 // the eventual target type is the same and the pointers have the same 5810 // level of indirection, this must be the issue. 5811 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 5812 do { 5813 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 5814 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 5815 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 5816 5817 if (lhptee == rhptee) 5818 return Sema::IncompatibleNestedPointerQualifiers; 5819 } 5820 5821 // General pointer incompatibility takes priority over qualifiers. 5822 return Sema::IncompatiblePointer; 5823 } 5824 if (!S.getLangOpts().CPlusPlus && 5825 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 5826 return Sema::IncompatiblePointer; 5827 return ConvTy; 5828} 5829 5830/// checkBlockPointerTypesForAssignment - This routine determines whether two 5831/// block pointer types are compatible or whether a block and normal pointer 5832/// are compatible. It is more restrict than comparing two function pointer 5833// types. 5834static Sema::AssignConvertType 5835checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 5836 QualType RHSType) { 5837 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 5838 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 5839 5840 QualType lhptee, rhptee; 5841 5842 // get the "pointed to" type (ignoring qualifiers at the top level) 5843 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 5844 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 5845 5846 // In C++, the types have to match exactly. 5847 if (S.getLangOpts().CPlusPlus) 5848 return Sema::IncompatibleBlockPointer; 5849 5850 Sema::AssignConvertType ConvTy = Sema::Compatible; 5851 5852 // For blocks we enforce that qualifiers are identical. 5853 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 5854 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 5855 5856 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 5857 return Sema::IncompatibleBlockPointer; 5858 5859 return ConvTy; 5860} 5861 5862/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 5863/// for assignment compatibility. 5864static Sema::AssignConvertType 5865checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 5866 QualType RHSType) { 5867 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 5868 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 5869 5870 if (LHSType->isObjCBuiltinType()) { 5871 // Class is not compatible with ObjC object pointers. 5872 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 5873 !RHSType->isObjCQualifiedClassType()) 5874 return Sema::IncompatiblePointer; 5875 return Sema::Compatible; 5876 } 5877 if (RHSType->isObjCBuiltinType()) { 5878 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 5879 !LHSType->isObjCQualifiedClassType()) 5880 return Sema::IncompatiblePointer; 5881 return Sema::Compatible; 5882 } 5883 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 5884 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 5885 5886 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 5887 // make an exception for id<P> 5888 !LHSType->isObjCQualifiedIdType()) 5889 return Sema::CompatiblePointerDiscardsQualifiers; 5890 5891 if (S.Context.typesAreCompatible(LHSType, RHSType)) 5892 return Sema::Compatible; 5893 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 5894 return Sema::IncompatibleObjCQualifiedId; 5895 return Sema::IncompatiblePointer; 5896} 5897 5898Sema::AssignConvertType 5899Sema::CheckAssignmentConstraints(SourceLocation Loc, 5900 QualType LHSType, QualType RHSType) { 5901 // Fake up an opaque expression. We don't actually care about what 5902 // cast operations are required, so if CheckAssignmentConstraints 5903 // adds casts to this they'll be wasted, but fortunately that doesn't 5904 // usually happen on valid code. 5905 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 5906 ExprResult RHSPtr = &RHSExpr; 5907 CastKind K = CK_Invalid; 5908 5909 return CheckAssignmentConstraints(LHSType, RHSPtr, K); 5910} 5911 5912/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 5913/// has code to accommodate several GCC extensions when type checking 5914/// pointers. Here are some objectionable examples that GCC considers warnings: 5915/// 5916/// int a, *pint; 5917/// short *pshort; 5918/// struct foo *pfoo; 5919/// 5920/// pint = pshort; // warning: assignment from incompatible pointer type 5921/// a = pint; // warning: assignment makes integer from pointer without a cast 5922/// pint = a; // warning: assignment makes pointer from integer without a cast 5923/// pint = pfoo; // warning: assignment from incompatible pointer type 5924/// 5925/// As a result, the code for dealing with pointers is more complex than the 5926/// C99 spec dictates. 5927/// 5928/// Sets 'Kind' for any result kind except Incompatible. 5929Sema::AssignConvertType 5930Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 5931 CastKind &Kind) { 5932 QualType RHSType = RHS.get()->getType(); 5933 QualType OrigLHSType = LHSType; 5934 5935 // Get canonical types. We're not formatting these types, just comparing 5936 // them. 5937 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 5938 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 5939 5940 // Common case: no conversion required. 5941 if (LHSType == RHSType) { 5942 Kind = CK_NoOp; 5943 return Compatible; 5944 } 5945 5946 // If we have an atomic type, try a non-atomic assignment, then just add an 5947 // atomic qualification step. 5948 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 5949 Sema::AssignConvertType result = 5950 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 5951 if (result != Compatible) 5952 return result; 5953 if (Kind != CK_NoOp) 5954 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind); 5955 Kind = CK_NonAtomicToAtomic; 5956 return Compatible; 5957 } 5958 5959 // If the left-hand side is a reference type, then we are in a 5960 // (rare!) case where we've allowed the use of references in C, 5961 // e.g., as a parameter type in a built-in function. In this case, 5962 // just make sure that the type referenced is compatible with the 5963 // right-hand side type. The caller is responsible for adjusting 5964 // LHSType so that the resulting expression does not have reference 5965 // type. 5966 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 5967 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 5968 Kind = CK_LValueBitCast; 5969 return Compatible; 5970 } 5971 return Incompatible; 5972 } 5973 5974 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 5975 // to the same ExtVector type. 5976 if (LHSType->isExtVectorType()) { 5977 if (RHSType->isExtVectorType()) 5978 return Incompatible; 5979 if (RHSType->isArithmeticType()) { 5980 // CK_VectorSplat does T -> vector T, so first cast to the 5981 // element type. 5982 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 5983 if (elType != RHSType) { 5984 Kind = PrepareScalarCast(RHS, elType); 5985 RHS = ImpCastExprToType(RHS.take(), elType, Kind); 5986 } 5987 Kind = CK_VectorSplat; 5988 return Compatible; 5989 } 5990 } 5991 5992 // Conversions to or from vector type. 5993 if (LHSType->isVectorType() || RHSType->isVectorType()) { 5994 if (LHSType->isVectorType() && RHSType->isVectorType()) { 5995 // Allow assignments of an AltiVec vector type to an equivalent GCC 5996 // vector type and vice versa 5997 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 5998 Kind = CK_BitCast; 5999 return Compatible; 6000 } 6001 6002 // If we are allowing lax vector conversions, and LHS and RHS are both 6003 // vectors, the total size only needs to be the same. This is a bitcast; 6004 // no bits are changed but the result type is different. 6005 if (getLangOpts().LaxVectorConversions && 6006 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) { 6007 Kind = CK_BitCast; 6008 return IncompatibleVectors; 6009 } 6010 } 6011 return Incompatible; 6012 } 6013 6014 // Arithmetic conversions. 6015 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 6016 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 6017 Kind = PrepareScalarCast(RHS, LHSType); 6018 return Compatible; 6019 } 6020 6021 // Conversions to normal pointers. 6022 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 6023 // U* -> T* 6024 if (isa<PointerType>(RHSType)) { 6025 Kind = CK_BitCast; 6026 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 6027 } 6028 6029 // int -> T* 6030 if (RHSType->isIntegerType()) { 6031 Kind = CK_IntegralToPointer; // FIXME: null? 6032 return IntToPointer; 6033 } 6034 6035 // C pointers are not compatible with ObjC object pointers, 6036 // with two exceptions: 6037 if (isa<ObjCObjectPointerType>(RHSType)) { 6038 // - conversions to void* 6039 if (LHSPointer->getPointeeType()->isVoidType()) { 6040 Kind = CK_BitCast; 6041 return Compatible; 6042 } 6043 6044 // - conversions from 'Class' to the redefinition type 6045 if (RHSType->isObjCClassType() && 6046 Context.hasSameType(LHSType, 6047 Context.getObjCClassRedefinitionType())) { 6048 Kind = CK_BitCast; 6049 return Compatible; 6050 } 6051 6052 Kind = CK_BitCast; 6053 return IncompatiblePointer; 6054 } 6055 6056 // U^ -> void* 6057 if (RHSType->getAs<BlockPointerType>()) { 6058 if (LHSPointer->getPointeeType()->isVoidType()) { 6059 Kind = CK_BitCast; 6060 return Compatible; 6061 } 6062 } 6063 6064 return Incompatible; 6065 } 6066 6067 // Conversions to block pointers. 6068 if (isa<BlockPointerType>(LHSType)) { 6069 // U^ -> T^ 6070 if (RHSType->isBlockPointerType()) { 6071 Kind = CK_BitCast; 6072 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 6073 } 6074 6075 // int or null -> T^ 6076 if (RHSType->isIntegerType()) { 6077 Kind = CK_IntegralToPointer; // FIXME: null 6078 return IntToBlockPointer; 6079 } 6080 6081 // id -> T^ 6082 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 6083 Kind = CK_AnyPointerToBlockPointerCast; 6084 return Compatible; 6085 } 6086 6087 // void* -> T^ 6088 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 6089 if (RHSPT->getPointeeType()->isVoidType()) { 6090 Kind = CK_AnyPointerToBlockPointerCast; 6091 return Compatible; 6092 } 6093 6094 return Incompatible; 6095 } 6096 6097 // Conversions to Objective-C pointers. 6098 if (isa<ObjCObjectPointerType>(LHSType)) { 6099 // A* -> B* 6100 if (RHSType->isObjCObjectPointerType()) { 6101 Kind = CK_BitCast; 6102 Sema::AssignConvertType result = 6103 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 6104 if (getLangOpts().ObjCAutoRefCount && 6105 result == Compatible && 6106 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 6107 result = IncompatibleObjCWeakRef; 6108 return result; 6109 } 6110 6111 // int or null -> A* 6112 if (RHSType->isIntegerType()) { 6113 Kind = CK_IntegralToPointer; // FIXME: null 6114 return IntToPointer; 6115 } 6116 6117 // In general, C pointers are not compatible with ObjC object pointers, 6118 // with two exceptions: 6119 if (isa<PointerType>(RHSType)) { 6120 Kind = CK_CPointerToObjCPointerCast; 6121 6122 // - conversions from 'void*' 6123 if (RHSType->isVoidPointerType()) { 6124 return Compatible; 6125 } 6126 6127 // - conversions to 'Class' from its redefinition type 6128 if (LHSType->isObjCClassType() && 6129 Context.hasSameType(RHSType, 6130 Context.getObjCClassRedefinitionType())) { 6131 return Compatible; 6132 } 6133 6134 return IncompatiblePointer; 6135 } 6136 6137 // T^ -> A* 6138 if (RHSType->isBlockPointerType()) { 6139 maybeExtendBlockObject(*this, RHS); 6140 Kind = CK_BlockPointerToObjCPointerCast; 6141 return Compatible; 6142 } 6143 6144 return Incompatible; 6145 } 6146 6147 // Conversions from pointers that are not covered by the above. 6148 if (isa<PointerType>(RHSType)) { 6149 // T* -> _Bool 6150 if (LHSType == Context.BoolTy) { 6151 Kind = CK_PointerToBoolean; 6152 return Compatible; 6153 } 6154 6155 // T* -> int 6156 if (LHSType->isIntegerType()) { 6157 Kind = CK_PointerToIntegral; 6158 return PointerToInt; 6159 } 6160 6161 return Incompatible; 6162 } 6163 6164 // Conversions from Objective-C pointers that are not covered by the above. 6165 if (isa<ObjCObjectPointerType>(RHSType)) { 6166 // T* -> _Bool 6167 if (LHSType == Context.BoolTy) { 6168 Kind = CK_PointerToBoolean; 6169 return Compatible; 6170 } 6171 6172 // T* -> int 6173 if (LHSType->isIntegerType()) { 6174 Kind = CK_PointerToIntegral; 6175 return PointerToInt; 6176 } 6177 6178 return Incompatible; 6179 } 6180 6181 // struct A -> struct B 6182 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 6183 if (Context.typesAreCompatible(LHSType, RHSType)) { 6184 Kind = CK_NoOp; 6185 return Compatible; 6186 } 6187 } 6188 6189 return Incompatible; 6190} 6191 6192/// \brief Constructs a transparent union from an expression that is 6193/// used to initialize the transparent union. 6194static void ConstructTransparentUnion(Sema &S, ASTContext &C, 6195 ExprResult &EResult, QualType UnionType, 6196 FieldDecl *Field) { 6197 // Build an initializer list that designates the appropriate member 6198 // of the transparent union. 6199 Expr *E = EResult.take(); 6200 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 6201 E, SourceLocation()); 6202 Initializer->setType(UnionType); 6203 Initializer->setInitializedFieldInUnion(Field); 6204 6205 // Build a compound literal constructing a value of the transparent 6206 // union type from this initializer list. 6207 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 6208 EResult = S.Owned( 6209 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 6210 VK_RValue, Initializer, false)); 6211} 6212 6213Sema::AssignConvertType 6214Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 6215 ExprResult &RHS) { 6216 QualType RHSType = RHS.get()->getType(); 6217 6218 // If the ArgType is a Union type, we want to handle a potential 6219 // transparent_union GCC extension. 6220 const RecordType *UT = ArgType->getAsUnionType(); 6221 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 6222 return Incompatible; 6223 6224 // The field to initialize within the transparent union. 6225 RecordDecl *UD = UT->getDecl(); 6226 FieldDecl *InitField = 0; 6227 // It's compatible if the expression matches any of the fields. 6228 for (RecordDecl::field_iterator it = UD->field_begin(), 6229 itend = UD->field_end(); 6230 it != itend; ++it) { 6231 if (it->getType()->isPointerType()) { 6232 // If the transparent union contains a pointer type, we allow: 6233 // 1) void pointer 6234 // 2) null pointer constant 6235 if (RHSType->isPointerType()) 6236 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 6237 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast); 6238 InitField = *it; 6239 break; 6240 } 6241 6242 if (RHS.get()->isNullPointerConstant(Context, 6243 Expr::NPC_ValueDependentIsNull)) { 6244 RHS = ImpCastExprToType(RHS.take(), it->getType(), 6245 CK_NullToPointer); 6246 InitField = *it; 6247 break; 6248 } 6249 } 6250 6251 CastKind Kind = CK_Invalid; 6252 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 6253 == Compatible) { 6254 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind); 6255 InitField = *it; 6256 break; 6257 } 6258 } 6259 6260 if (!InitField) 6261 return Incompatible; 6262 6263 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 6264 return Compatible; 6265} 6266 6267Sema::AssignConvertType 6268Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6269 bool Diagnose) { 6270 if (getLangOpts().CPlusPlus) { 6271 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 6272 // C++ 5.17p3: If the left operand is not of class type, the 6273 // expression is implicitly converted (C++ 4) to the 6274 // cv-unqualified type of the left operand. 6275 ExprResult Res; 6276 if (Diagnose) { 6277 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6278 AA_Assigning); 6279 } else { 6280 ImplicitConversionSequence ICS = 6281 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6282 /*SuppressUserConversions=*/false, 6283 /*AllowExplicit=*/false, 6284 /*InOverloadResolution=*/false, 6285 /*CStyle=*/false, 6286 /*AllowObjCWritebackConversion=*/false); 6287 if (ICS.isFailure()) 6288 return Incompatible; 6289 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6290 ICS, AA_Assigning); 6291 } 6292 if (Res.isInvalid()) 6293 return Incompatible; 6294 Sema::AssignConvertType result = Compatible; 6295 if (getLangOpts().ObjCAutoRefCount && 6296 !CheckObjCARCUnavailableWeakConversion(LHSType, 6297 RHS.get()->getType())) 6298 result = IncompatibleObjCWeakRef; 6299 RHS = Res; 6300 return result; 6301 } 6302 6303 // FIXME: Currently, we fall through and treat C++ classes like C 6304 // structures. 6305 // FIXME: We also fall through for atomics; not sure what should 6306 // happen there, though. 6307 } 6308 6309 // C99 6.5.16.1p1: the left operand is a pointer and the right is 6310 // a null pointer constant. 6311 if ((LHSType->isPointerType() || 6312 LHSType->isObjCObjectPointerType() || 6313 LHSType->isBlockPointerType()) 6314 && RHS.get()->isNullPointerConstant(Context, 6315 Expr::NPC_ValueDependentIsNull)) { 6316 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 6317 return Compatible; 6318 } 6319 6320 // This check seems unnatural, however it is necessary to ensure the proper 6321 // conversion of functions/arrays. If the conversion were done for all 6322 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 6323 // expressions that suppress this implicit conversion (&, sizeof). 6324 // 6325 // Suppress this for references: C++ 8.5.3p5. 6326 if (!LHSType->isReferenceType()) { 6327 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6328 if (RHS.isInvalid()) 6329 return Incompatible; 6330 } 6331 6332 CastKind Kind = CK_Invalid; 6333 Sema::AssignConvertType result = 6334 CheckAssignmentConstraints(LHSType, RHS, Kind); 6335 6336 // C99 6.5.16.1p2: The value of the right operand is converted to the 6337 // type of the assignment expression. 6338 // CheckAssignmentConstraints allows the left-hand side to be a reference, 6339 // so that we can use references in built-in functions even in C. 6340 // The getNonReferenceType() call makes sure that the resulting expression 6341 // does not have reference type. 6342 if (result != Incompatible && RHS.get()->getType() != LHSType) 6343 RHS = ImpCastExprToType(RHS.take(), 6344 LHSType.getNonLValueExprType(Context), Kind); 6345 return result; 6346} 6347 6348QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 6349 ExprResult &RHS) { 6350 Diag(Loc, diag::err_typecheck_invalid_operands) 6351 << LHS.get()->getType() << RHS.get()->getType() 6352 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6353 return QualType(); 6354} 6355 6356QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 6357 SourceLocation Loc, bool IsCompAssign) { 6358 if (!IsCompAssign) { 6359 LHS = DefaultFunctionArrayLvalueConversion(LHS.take()); 6360 if (LHS.isInvalid()) 6361 return QualType(); 6362 } 6363 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6364 if (RHS.isInvalid()) 6365 return QualType(); 6366 6367 // For conversion purposes, we ignore any qualifiers. 6368 // For example, "const float" and "float" are equivalent. 6369 QualType LHSType = 6370 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6371 QualType RHSType = 6372 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6373 6374 // If the vector types are identical, return. 6375 if (LHSType == RHSType) 6376 return LHSType; 6377 6378 // Handle the case of equivalent AltiVec and GCC vector types 6379 if (LHSType->isVectorType() && RHSType->isVectorType() && 6380 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6381 if (LHSType->isExtVectorType()) { 6382 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6383 return LHSType; 6384 } 6385 6386 if (!IsCompAssign) 6387 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 6388 return RHSType; 6389 } 6390 6391 if (getLangOpts().LaxVectorConversions && 6392 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) { 6393 // If we are allowing lax vector conversions, and LHS and RHS are both 6394 // vectors, the total size only needs to be the same. This is a 6395 // bitcast; no bits are changed but the result type is different. 6396 // FIXME: Should we really be allowing this? 6397 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6398 return LHSType; 6399 } 6400 6401 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can 6402 // swap back (so that we don't reverse the inputs to a subtract, for instance. 6403 bool swapped = false; 6404 if (RHSType->isExtVectorType() && !IsCompAssign) { 6405 swapped = true; 6406 std::swap(RHS, LHS); 6407 std::swap(RHSType, LHSType); 6408 } 6409 6410 // Handle the case of an ext vector and scalar. 6411 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) { 6412 QualType EltTy = LV->getElementType(); 6413 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) { 6414 int order = Context.getIntegerTypeOrder(EltTy, RHSType); 6415 if (order > 0) 6416 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast); 6417 if (order >= 0) { 6418 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 6419 if (swapped) std::swap(RHS, LHS); 6420 return LHSType; 6421 } 6422 } 6423 if (EltTy->isRealFloatingType() && RHSType->isScalarType()) { 6424 if (RHSType->isRealFloatingType()) { 6425 int order = Context.getFloatingTypeOrder(EltTy, RHSType); 6426 if (order > 0) 6427 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast); 6428 if (order >= 0) { 6429 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 6430 if (swapped) std::swap(RHS, LHS); 6431 return LHSType; 6432 } 6433 } 6434 if (RHSType->isIntegralType(Context)) { 6435 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralToFloating); 6436 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat); 6437 if (swapped) std::swap(RHS, LHS); 6438 return LHSType; 6439 } 6440 } 6441 } 6442 6443 // Vectors of different size or scalar and non-ext-vector are errors. 6444 if (swapped) std::swap(RHS, LHS); 6445 Diag(Loc, diag::err_typecheck_vector_not_convertable) 6446 << LHS.get()->getType() << RHS.get()->getType() 6447 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6448 return QualType(); 6449} 6450 6451// checkArithmeticNull - Detect when a NULL constant is used improperly in an 6452// expression. These are mainly cases where the null pointer is used as an 6453// integer instead of a pointer. 6454static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 6455 SourceLocation Loc, bool IsCompare) { 6456 // The canonical way to check for a GNU null is with isNullPointerConstant, 6457 // but we use a bit of a hack here for speed; this is a relatively 6458 // hot path, and isNullPointerConstant is slow. 6459 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 6460 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 6461 6462 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 6463 6464 // Avoid analyzing cases where the result will either be invalid (and 6465 // diagnosed as such) or entirely valid and not something to warn about. 6466 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 6467 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 6468 return; 6469 6470 // Comparison operations would not make sense with a null pointer no matter 6471 // what the other expression is. 6472 if (!IsCompare) { 6473 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 6474 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 6475 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 6476 return; 6477 } 6478 6479 // The rest of the operations only make sense with a null pointer 6480 // if the other expression is a pointer. 6481 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 6482 NonNullType->canDecayToPointerType()) 6483 return; 6484 6485 S.Diag(Loc, diag::warn_null_in_comparison_operation) 6486 << LHSNull /* LHS is NULL */ << NonNullType 6487 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6488} 6489 6490QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 6491 SourceLocation Loc, 6492 bool IsCompAssign, bool IsDiv) { 6493 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6494 6495 if (LHS.get()->getType()->isVectorType() || 6496 RHS.get()->getType()->isVectorType()) 6497 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6498 6499 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6500 if (LHS.isInvalid() || RHS.isInvalid()) 6501 return QualType(); 6502 6503 6504 if (compType.isNull() || !compType->isArithmeticType()) 6505 return InvalidOperands(Loc, LHS, RHS); 6506 6507 // Check for division by zero. 6508 llvm::APSInt RHSValue; 6509 if (IsDiv && !RHS.get()->isValueDependent() && 6510 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0) 6511 DiagRuntimeBehavior(Loc, RHS.get(), 6512 PDiag(diag::warn_division_by_zero) 6513 << RHS.get()->getSourceRange()); 6514 6515 return compType; 6516} 6517 6518QualType Sema::CheckRemainderOperands( 6519 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 6520 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6521 6522 if (LHS.get()->getType()->isVectorType() || 6523 RHS.get()->getType()->isVectorType()) { 6524 if (LHS.get()->getType()->hasIntegerRepresentation() && 6525 RHS.get()->getType()->hasIntegerRepresentation()) 6526 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6527 return InvalidOperands(Loc, LHS, RHS); 6528 } 6529 6530 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6531 if (LHS.isInvalid() || RHS.isInvalid()) 6532 return QualType(); 6533 6534 if (compType.isNull() || !compType->isIntegerType()) 6535 return InvalidOperands(Loc, LHS, RHS); 6536 6537 // Check for remainder by zero. 6538 llvm::APSInt RHSValue; 6539 if (!RHS.get()->isValueDependent() && 6540 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0) 6541 DiagRuntimeBehavior(Loc, RHS.get(), 6542 PDiag(diag::warn_remainder_by_zero) 6543 << RHS.get()->getSourceRange()); 6544 6545 return compType; 6546} 6547 6548/// \brief Diagnose invalid arithmetic on two void pointers. 6549static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 6550 Expr *LHSExpr, Expr *RHSExpr) { 6551 S.Diag(Loc, S.getLangOpts().CPlusPlus 6552 ? diag::err_typecheck_pointer_arith_void_type 6553 : diag::ext_gnu_void_ptr) 6554 << 1 /* two pointers */ << LHSExpr->getSourceRange() 6555 << RHSExpr->getSourceRange(); 6556} 6557 6558/// \brief Diagnose invalid arithmetic on a void pointer. 6559static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 6560 Expr *Pointer) { 6561 S.Diag(Loc, S.getLangOpts().CPlusPlus 6562 ? diag::err_typecheck_pointer_arith_void_type 6563 : diag::ext_gnu_void_ptr) 6564 << 0 /* one pointer */ << Pointer->getSourceRange(); 6565} 6566 6567/// \brief Diagnose invalid arithmetic on two function pointers. 6568static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 6569 Expr *LHS, Expr *RHS) { 6570 assert(LHS->getType()->isAnyPointerType()); 6571 assert(RHS->getType()->isAnyPointerType()); 6572 S.Diag(Loc, S.getLangOpts().CPlusPlus 6573 ? diag::err_typecheck_pointer_arith_function_type 6574 : diag::ext_gnu_ptr_func_arith) 6575 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 6576 // We only show the second type if it differs from the first. 6577 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 6578 RHS->getType()) 6579 << RHS->getType()->getPointeeType() 6580 << LHS->getSourceRange() << RHS->getSourceRange(); 6581} 6582 6583/// \brief Diagnose invalid arithmetic on a function pointer. 6584static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 6585 Expr *Pointer) { 6586 assert(Pointer->getType()->isAnyPointerType()); 6587 S.Diag(Loc, S.getLangOpts().CPlusPlus 6588 ? diag::err_typecheck_pointer_arith_function_type 6589 : diag::ext_gnu_ptr_func_arith) 6590 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 6591 << 0 /* one pointer, so only one type */ 6592 << Pointer->getSourceRange(); 6593} 6594 6595/// \brief Emit error if Operand is incomplete pointer type 6596/// 6597/// \returns True if pointer has incomplete type 6598static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 6599 Expr *Operand) { 6600 assert(Operand->getType()->isAnyPointerType() && 6601 !Operand->getType()->isDependentType()); 6602 QualType PointeeTy = Operand->getType()->getPointeeType(); 6603 return S.RequireCompleteType(Loc, PointeeTy, 6604 diag::err_typecheck_arithmetic_incomplete_type, 6605 PointeeTy, Operand->getSourceRange()); 6606} 6607 6608/// \brief Check the validity of an arithmetic pointer operand. 6609/// 6610/// If the operand has pointer type, this code will check for pointer types 6611/// which are invalid in arithmetic operations. These will be diagnosed 6612/// appropriately, including whether or not the use is supported as an 6613/// extension. 6614/// 6615/// \returns True when the operand is valid to use (even if as an extension). 6616static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 6617 Expr *Operand) { 6618 if (!Operand->getType()->isAnyPointerType()) return true; 6619 6620 QualType PointeeTy = Operand->getType()->getPointeeType(); 6621 if (PointeeTy->isVoidType()) { 6622 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 6623 return !S.getLangOpts().CPlusPlus; 6624 } 6625 if (PointeeTy->isFunctionType()) { 6626 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 6627 return !S.getLangOpts().CPlusPlus; 6628 } 6629 6630 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 6631 6632 return true; 6633} 6634 6635/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 6636/// operands. 6637/// 6638/// This routine will diagnose any invalid arithmetic on pointer operands much 6639/// like \see checkArithmeticOpPointerOperand. However, it has special logic 6640/// for emitting a single diagnostic even for operations where both LHS and RHS 6641/// are (potentially problematic) pointers. 6642/// 6643/// \returns True when the operand is valid to use (even if as an extension). 6644static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 6645 Expr *LHSExpr, Expr *RHSExpr) { 6646 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 6647 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 6648 if (!isLHSPointer && !isRHSPointer) return true; 6649 6650 QualType LHSPointeeTy, RHSPointeeTy; 6651 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 6652 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 6653 6654 // Check for arithmetic on pointers to incomplete types. 6655 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 6656 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 6657 if (isLHSVoidPtr || isRHSVoidPtr) { 6658 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 6659 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 6660 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 6661 6662 return !S.getLangOpts().CPlusPlus; 6663 } 6664 6665 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 6666 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 6667 if (isLHSFuncPtr || isRHSFuncPtr) { 6668 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 6669 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 6670 RHSExpr); 6671 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 6672 6673 return !S.getLangOpts().CPlusPlus; 6674 } 6675 6676 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 6677 return false; 6678 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 6679 return false; 6680 6681 return true; 6682} 6683 6684/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 6685/// literal. 6686static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 6687 Expr *LHSExpr, Expr *RHSExpr) { 6688 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 6689 Expr* IndexExpr = RHSExpr; 6690 if (!StrExpr) { 6691 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 6692 IndexExpr = LHSExpr; 6693 } 6694 6695 bool IsStringPlusInt = StrExpr && 6696 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 6697 if (!IsStringPlusInt) 6698 return; 6699 6700 llvm::APSInt index; 6701 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 6702 unsigned StrLenWithNull = StrExpr->getLength() + 1; 6703 if (index.isNonNegative() && 6704 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 6705 index.isUnsigned())) 6706 return; 6707 } 6708 6709 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 6710 Self.Diag(OpLoc, diag::warn_string_plus_int) 6711 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 6712 6713 // Only print a fixit for "str" + int, not for int + "str". 6714 if (IndexExpr == RHSExpr) { 6715 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 6716 Self.Diag(OpLoc, diag::note_string_plus_int_silence) 6717 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 6718 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 6719 << FixItHint::CreateInsertion(EndLoc, "]"); 6720 } else 6721 Self.Diag(OpLoc, diag::note_string_plus_int_silence); 6722} 6723 6724/// \brief Emit error when two pointers are incompatible. 6725static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 6726 Expr *LHSExpr, Expr *RHSExpr) { 6727 assert(LHSExpr->getType()->isAnyPointerType()); 6728 assert(RHSExpr->getType()->isAnyPointerType()); 6729 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 6730 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 6731 << RHSExpr->getSourceRange(); 6732} 6733 6734QualType Sema::CheckAdditionOperands( // C99 6.5.6 6735 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 6736 QualType* CompLHSTy) { 6737 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6738 6739 if (LHS.get()->getType()->isVectorType() || 6740 RHS.get()->getType()->isVectorType()) { 6741 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 6742 if (CompLHSTy) *CompLHSTy = compType; 6743 return compType; 6744 } 6745 6746 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 6747 if (LHS.isInvalid() || RHS.isInvalid()) 6748 return QualType(); 6749 6750 // Diagnose "string literal" '+' int. 6751 if (Opc == BO_Add) 6752 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 6753 6754 // handle the common case first (both operands are arithmetic). 6755 if (!compType.isNull() && compType->isArithmeticType()) { 6756 if (CompLHSTy) *CompLHSTy = compType; 6757 return compType; 6758 } 6759 6760 // Type-checking. Ultimately the pointer's going to be in PExp; 6761 // note that we bias towards the LHS being the pointer. 6762 Expr *PExp = LHS.get(), *IExp = RHS.get(); 6763 6764 bool isObjCPointer; 6765 if (PExp->getType()->isPointerType()) { 6766 isObjCPointer = false; 6767 } else if (PExp->getType()->isObjCObjectPointerType()) { 6768 isObjCPointer = true; 6769 } else { 6770 std::swap(PExp, IExp); 6771 if (PExp->getType()->isPointerType()) { 6772 isObjCPointer = false; 6773 } else if (PExp->getType()->isObjCObjectPointerType()) { 6774 isObjCPointer = true; 6775 } else { 6776 return InvalidOperands(Loc, LHS, RHS); 6777 } 6778 } 6779 assert(PExp->getType()->isAnyPointerType()); 6780 6781 if (!IExp->getType()->isIntegerType()) 6782 return InvalidOperands(Loc, LHS, RHS); 6783 6784 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 6785 return QualType(); 6786 6787 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 6788 return QualType(); 6789 6790 // Check array bounds for pointer arithemtic 6791 CheckArrayAccess(PExp, IExp); 6792 6793 if (CompLHSTy) { 6794 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 6795 if (LHSTy.isNull()) { 6796 LHSTy = LHS.get()->getType(); 6797 if (LHSTy->isPromotableIntegerType()) 6798 LHSTy = Context.getPromotedIntegerType(LHSTy); 6799 } 6800 *CompLHSTy = LHSTy; 6801 } 6802 6803 return PExp->getType(); 6804} 6805 6806// C99 6.5.6 6807QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 6808 SourceLocation Loc, 6809 QualType* CompLHSTy) { 6810 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6811 6812 if (LHS.get()->getType()->isVectorType() || 6813 RHS.get()->getType()->isVectorType()) { 6814 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 6815 if (CompLHSTy) *CompLHSTy = compType; 6816 return compType; 6817 } 6818 6819 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 6820 if (LHS.isInvalid() || RHS.isInvalid()) 6821 return QualType(); 6822 6823 // Enforce type constraints: C99 6.5.6p3. 6824 6825 // Handle the common case first (both operands are arithmetic). 6826 if (!compType.isNull() && compType->isArithmeticType()) { 6827 if (CompLHSTy) *CompLHSTy = compType; 6828 return compType; 6829 } 6830 6831 // Either ptr - int or ptr - ptr. 6832 if (LHS.get()->getType()->isAnyPointerType()) { 6833 QualType lpointee = LHS.get()->getType()->getPointeeType(); 6834 6835 // Diagnose bad cases where we step over interface counts. 6836 if (LHS.get()->getType()->isObjCObjectPointerType() && 6837 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 6838 return QualType(); 6839 6840 // The result type of a pointer-int computation is the pointer type. 6841 if (RHS.get()->getType()->isIntegerType()) { 6842 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 6843 return QualType(); 6844 6845 // Check array bounds for pointer arithemtic 6846 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0, 6847 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 6848 6849 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 6850 return LHS.get()->getType(); 6851 } 6852 6853 // Handle pointer-pointer subtractions. 6854 if (const PointerType *RHSPTy 6855 = RHS.get()->getType()->getAs<PointerType>()) { 6856 QualType rpointee = RHSPTy->getPointeeType(); 6857 6858 if (getLangOpts().CPlusPlus) { 6859 // Pointee types must be the same: C++ [expr.add] 6860 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 6861 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 6862 } 6863 } else { 6864 // Pointee types must be compatible C99 6.5.6p3 6865 if (!Context.typesAreCompatible( 6866 Context.getCanonicalType(lpointee).getUnqualifiedType(), 6867 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 6868 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 6869 return QualType(); 6870 } 6871 } 6872 6873 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 6874 LHS.get(), RHS.get())) 6875 return QualType(); 6876 6877 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 6878 return Context.getPointerDiffType(); 6879 } 6880 } 6881 6882 return InvalidOperands(Loc, LHS, RHS); 6883} 6884 6885static bool isScopedEnumerationType(QualType T) { 6886 if (const EnumType *ET = dyn_cast<EnumType>(T)) 6887 return ET->getDecl()->isScoped(); 6888 return false; 6889} 6890 6891static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 6892 SourceLocation Loc, unsigned Opc, 6893 QualType LHSType) { 6894 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 6895 // so skip remaining warnings as we don't want to modify values within Sema. 6896 if (S.getLangOpts().OpenCL) 6897 return; 6898 6899 llvm::APSInt Right; 6900 // Check right/shifter operand 6901 if (RHS.get()->isValueDependent() || 6902 !RHS.get()->isIntegerConstantExpr(Right, S.Context)) 6903 return; 6904 6905 if (Right.isNegative()) { 6906 S.DiagRuntimeBehavior(Loc, RHS.get(), 6907 S.PDiag(diag::warn_shift_negative) 6908 << RHS.get()->getSourceRange()); 6909 return; 6910 } 6911 llvm::APInt LeftBits(Right.getBitWidth(), 6912 S.Context.getTypeSize(LHS.get()->getType())); 6913 if (Right.uge(LeftBits)) { 6914 S.DiagRuntimeBehavior(Loc, RHS.get(), 6915 S.PDiag(diag::warn_shift_gt_typewidth) 6916 << RHS.get()->getSourceRange()); 6917 return; 6918 } 6919 if (Opc != BO_Shl) 6920 return; 6921 6922 // When left shifting an ICE which is signed, we can check for overflow which 6923 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 6924 // integers have defined behavior modulo one more than the maximum value 6925 // representable in the result type, so never warn for those. 6926 llvm::APSInt Left; 6927 if (LHS.get()->isValueDependent() || 6928 !LHS.get()->isIntegerConstantExpr(Left, S.Context) || 6929 LHSType->hasUnsignedIntegerRepresentation()) 6930 return; 6931 llvm::APInt ResultBits = 6932 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 6933 if (LeftBits.uge(ResultBits)) 6934 return; 6935 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 6936 Result = Result.shl(Right); 6937 6938 // Print the bit representation of the signed integer as an unsigned 6939 // hexadecimal number. 6940 SmallString<40> HexResult; 6941 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 6942 6943 // If we are only missing a sign bit, this is less likely to result in actual 6944 // bugs -- if the result is cast back to an unsigned type, it will have the 6945 // expected value. Thus we place this behind a different warning that can be 6946 // turned off separately if needed. 6947 if (LeftBits == ResultBits - 1) { 6948 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 6949 << HexResult.str() << LHSType 6950 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6951 return; 6952 } 6953 6954 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 6955 << HexResult.str() << Result.getMinSignedBits() << LHSType 6956 << Left.getBitWidth() << LHS.get()->getSourceRange() 6957 << RHS.get()->getSourceRange(); 6958} 6959 6960// C99 6.5.7 6961QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 6962 SourceLocation Loc, unsigned Opc, 6963 bool IsCompAssign) { 6964 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6965 6966 // Vector shifts promote their scalar inputs to vector type. 6967 if (LHS.get()->getType()->isVectorType() || 6968 RHS.get()->getType()->isVectorType()) 6969 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6970 6971 // Shifts don't perform usual arithmetic conversions, they just do integer 6972 // promotions on each operand. C99 6.5.7p3 6973 6974 // For the LHS, do usual unary conversions, but then reset them away 6975 // if this is a compound assignment. 6976 ExprResult OldLHS = LHS; 6977 LHS = UsualUnaryConversions(LHS.take()); 6978 if (LHS.isInvalid()) 6979 return QualType(); 6980 QualType LHSType = LHS.get()->getType(); 6981 if (IsCompAssign) LHS = OldLHS; 6982 6983 // The RHS is simpler. 6984 RHS = UsualUnaryConversions(RHS.take()); 6985 if (RHS.isInvalid()) 6986 return QualType(); 6987 QualType RHSType = RHS.get()->getType(); 6988 6989 // C99 6.5.7p2: Each of the operands shall have integer type. 6990 if (!LHSType->hasIntegerRepresentation() || 6991 !RHSType->hasIntegerRepresentation()) 6992 return InvalidOperands(Loc, LHS, RHS); 6993 6994 // C++0x: Don't allow scoped enums. FIXME: Use something better than 6995 // hasIntegerRepresentation() above instead of this. 6996 if (isScopedEnumerationType(LHSType) || 6997 isScopedEnumerationType(RHSType)) { 6998 return InvalidOperands(Loc, LHS, RHS); 6999 } 7000 // Sanity-check shift operands 7001 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 7002 7003 // "The type of the result is that of the promoted left operand." 7004 return LHSType; 7005} 7006 7007static bool IsWithinTemplateSpecialization(Decl *D) { 7008 if (DeclContext *DC = D->getDeclContext()) { 7009 if (isa<ClassTemplateSpecializationDecl>(DC)) 7010 return true; 7011 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 7012 return FD->isFunctionTemplateSpecialization(); 7013 } 7014 return false; 7015} 7016 7017/// If two different enums are compared, raise a warning. 7018static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 7019 Expr *RHS) { 7020 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 7021 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 7022 7023 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 7024 if (!LHSEnumType) 7025 return; 7026 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 7027 if (!RHSEnumType) 7028 return; 7029 7030 // Ignore anonymous enums. 7031 if (!LHSEnumType->getDecl()->getIdentifier()) 7032 return; 7033 if (!RHSEnumType->getDecl()->getIdentifier()) 7034 return; 7035 7036 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 7037 return; 7038 7039 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 7040 << LHSStrippedType << RHSStrippedType 7041 << LHS->getSourceRange() << RHS->getSourceRange(); 7042} 7043 7044/// \brief Diagnose bad pointer comparisons. 7045static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 7046 ExprResult &LHS, ExprResult &RHS, 7047 bool IsError) { 7048 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 7049 : diag::ext_typecheck_comparison_of_distinct_pointers) 7050 << LHS.get()->getType() << RHS.get()->getType() 7051 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7052} 7053 7054/// \brief Returns false if the pointers are converted to a composite type, 7055/// true otherwise. 7056static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 7057 ExprResult &LHS, ExprResult &RHS) { 7058 // C++ [expr.rel]p2: 7059 // [...] Pointer conversions (4.10) and qualification 7060 // conversions (4.4) are performed on pointer operands (or on 7061 // a pointer operand and a null pointer constant) to bring 7062 // them to their composite pointer type. [...] 7063 // 7064 // C++ [expr.eq]p1 uses the same notion for (in)equality 7065 // comparisons of pointers. 7066 7067 // C++ [expr.eq]p2: 7068 // In addition, pointers to members can be compared, or a pointer to 7069 // member and a null pointer constant. Pointer to member conversions 7070 // (4.11) and qualification conversions (4.4) are performed to bring 7071 // them to a common type. If one operand is a null pointer constant, 7072 // the common type is the type of the other operand. Otherwise, the 7073 // common type is a pointer to member type similar (4.4) to the type 7074 // of one of the operands, with a cv-qualification signature (4.4) 7075 // that is the union of the cv-qualification signatures of the operand 7076 // types. 7077 7078 QualType LHSType = LHS.get()->getType(); 7079 QualType RHSType = RHS.get()->getType(); 7080 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 7081 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 7082 7083 bool NonStandardCompositeType = false; 7084 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType; 7085 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 7086 if (T.isNull()) { 7087 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 7088 return true; 7089 } 7090 7091 if (NonStandardCompositeType) 7092 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 7093 << LHSType << RHSType << T << LHS.get()->getSourceRange() 7094 << RHS.get()->getSourceRange(); 7095 7096 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast); 7097 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast); 7098 return false; 7099} 7100 7101static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 7102 ExprResult &LHS, 7103 ExprResult &RHS, 7104 bool IsError) { 7105 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 7106 : diag::ext_typecheck_comparison_of_fptr_to_void) 7107 << LHS.get()->getType() << RHS.get()->getType() 7108 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7109} 7110 7111static bool isObjCObjectLiteral(ExprResult &E) { 7112 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 7113 case Stmt::ObjCArrayLiteralClass: 7114 case Stmt::ObjCDictionaryLiteralClass: 7115 case Stmt::ObjCStringLiteralClass: 7116 case Stmt::ObjCBoxedExprClass: 7117 return true; 7118 default: 7119 // Note that ObjCBoolLiteral is NOT an object literal! 7120 return false; 7121 } 7122} 7123 7124static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 7125 const ObjCObjectPointerType *Type = 7126 LHS->getType()->getAs<ObjCObjectPointerType>(); 7127 7128 // If this is not actually an Objective-C object, bail out. 7129 if (!Type) 7130 return false; 7131 7132 // Get the LHS object's interface type. 7133 QualType InterfaceType = Type->getPointeeType(); 7134 if (const ObjCObjectType *iQFaceTy = 7135 InterfaceType->getAsObjCQualifiedInterfaceType()) 7136 InterfaceType = iQFaceTy->getBaseType(); 7137 7138 // If the RHS isn't an Objective-C object, bail out. 7139 if (!RHS->getType()->isObjCObjectPointerType()) 7140 return false; 7141 7142 // Try to find the -isEqual: method. 7143 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 7144 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 7145 InterfaceType, 7146 /*instance=*/true); 7147 if (!Method) { 7148 if (Type->isObjCIdType()) { 7149 // For 'id', just check the global pool. 7150 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 7151 /*receiverId=*/true, 7152 /*warn=*/false); 7153 } else { 7154 // Check protocols. 7155 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 7156 /*instance=*/true); 7157 } 7158 } 7159 7160 if (!Method) 7161 return false; 7162 7163 QualType T = Method->param_begin()[0]->getType(); 7164 if (!T->isObjCObjectPointerType()) 7165 return false; 7166 7167 QualType R = Method->getResultType(); 7168 if (!R->isScalarType()) 7169 return false; 7170 7171 return true; 7172} 7173 7174Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 7175 FromE = FromE->IgnoreParenImpCasts(); 7176 switch (FromE->getStmtClass()) { 7177 default: 7178 break; 7179 case Stmt::ObjCStringLiteralClass: 7180 // "string literal" 7181 return LK_String; 7182 case Stmt::ObjCArrayLiteralClass: 7183 // "array literal" 7184 return LK_Array; 7185 case Stmt::ObjCDictionaryLiteralClass: 7186 // "dictionary literal" 7187 return LK_Dictionary; 7188 case Stmt::BlockExprClass: 7189 return LK_Block; 7190 case Stmt::ObjCBoxedExprClass: { 7191 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 7192 switch (Inner->getStmtClass()) { 7193 case Stmt::IntegerLiteralClass: 7194 case Stmt::FloatingLiteralClass: 7195 case Stmt::CharacterLiteralClass: 7196 case Stmt::ObjCBoolLiteralExprClass: 7197 case Stmt::CXXBoolLiteralExprClass: 7198 // "numeric literal" 7199 return LK_Numeric; 7200 case Stmt::ImplicitCastExprClass: { 7201 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 7202 // Boolean literals can be represented by implicit casts. 7203 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 7204 return LK_Numeric; 7205 break; 7206 } 7207 default: 7208 break; 7209 } 7210 return LK_Boxed; 7211 } 7212 } 7213 return LK_None; 7214} 7215 7216static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 7217 ExprResult &LHS, ExprResult &RHS, 7218 BinaryOperator::Opcode Opc){ 7219 Expr *Literal; 7220 Expr *Other; 7221 if (isObjCObjectLiteral(LHS)) { 7222 Literal = LHS.get(); 7223 Other = RHS.get(); 7224 } else { 7225 Literal = RHS.get(); 7226 Other = LHS.get(); 7227 } 7228 7229 // Don't warn on comparisons against nil. 7230 Other = Other->IgnoreParenCasts(); 7231 if (Other->isNullPointerConstant(S.getASTContext(), 7232 Expr::NPC_ValueDependentIsNotNull)) 7233 return; 7234 7235 // This should be kept in sync with warn_objc_literal_comparison. 7236 // LK_String should always be after the other literals, since it has its own 7237 // warning flag. 7238 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 7239 assert(LiteralKind != Sema::LK_Block); 7240 if (LiteralKind == Sema::LK_None) { 7241 llvm_unreachable("Unknown Objective-C object literal kind"); 7242 } 7243 7244 if (LiteralKind == Sema::LK_String) 7245 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 7246 << Literal->getSourceRange(); 7247 else 7248 S.Diag(Loc, diag::warn_objc_literal_comparison) 7249 << LiteralKind << Literal->getSourceRange(); 7250 7251 if (BinaryOperator::isEqualityOp(Opc) && 7252 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 7253 SourceLocation Start = LHS.get()->getLocStart(); 7254 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 7255 CharSourceRange OpRange = 7256 CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc)); 7257 7258 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 7259 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 7260 << FixItHint::CreateReplacement(OpRange, " isEqual:") 7261 << FixItHint::CreateInsertion(End, "]"); 7262 } 7263} 7264 7265static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 7266 ExprResult &RHS, 7267 SourceLocation Loc, 7268 unsigned OpaqueOpc) { 7269 // This checking requires bools. 7270 if (!S.getLangOpts().Bool) return; 7271 7272 // Check that left hand side is !something. 7273 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 7274 if (!UO || UO->getOpcode() != UO_LNot) return; 7275 7276 // Only check if the right hand side is non-bool arithmetic type. 7277 if (RHS.get()->getType()->isBooleanType()) return; 7278 7279 // Make sure that the something in !something is not bool. 7280 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 7281 if (SubExpr->getType()->isBooleanType()) return; 7282 7283 // Emit warning. 7284 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 7285 << Loc; 7286 7287 // First note suggest !(x < y) 7288 SourceLocation FirstOpen = SubExpr->getLocStart(); 7289 SourceLocation FirstClose = RHS.get()->getLocEnd(); 7290 FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose); 7291 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 7292 << FixItHint::CreateInsertion(FirstOpen, "(") 7293 << FixItHint::CreateInsertion(FirstClose, ")"); 7294 7295 // Second note suggests (!x) < y 7296 SourceLocation SecondOpen = LHS.get()->getLocStart(); 7297 SourceLocation SecondClose = LHS.get()->getLocEnd(); 7298 SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose); 7299 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 7300 << FixItHint::CreateInsertion(SecondOpen, "(") 7301 << FixItHint::CreateInsertion(SecondClose, ")"); 7302} 7303 7304// C99 6.5.8, C++ [expr.rel] 7305QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 7306 SourceLocation Loc, unsigned OpaqueOpc, 7307 bool IsRelational) { 7308 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 7309 7310 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 7311 7312 // Handle vector comparisons separately. 7313 if (LHS.get()->getType()->isVectorType() || 7314 RHS.get()->getType()->isVectorType()) 7315 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 7316 7317 QualType LHSType = LHS.get()->getType(); 7318 QualType RHSType = RHS.get()->getType(); 7319 7320 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 7321 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 7322 7323 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 7324 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc); 7325 7326 if (!LHSType->hasFloatingRepresentation() && 7327 !(LHSType->isBlockPointerType() && IsRelational) && 7328 !LHS.get()->getLocStart().isMacroID() && 7329 !RHS.get()->getLocStart().isMacroID()) { 7330 // For non-floating point types, check for self-comparisons of the form 7331 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 7332 // often indicate logic errors in the program. 7333 // 7334 // NOTE: Don't warn about comparison expressions resulting from macro 7335 // expansion. Also don't warn about comparisons which are only self 7336 // comparisons within a template specialization. The warnings should catch 7337 // obvious cases in the definition of the template anyways. The idea is to 7338 // warn when the typed comparison operator will always evaluate to the same 7339 // result. 7340 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) { 7341 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) { 7342 if (DRL->getDecl() == DRR->getDecl() && 7343 !IsWithinTemplateSpecialization(DRL->getDecl())) { 7344 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7345 << 0 // self- 7346 << (Opc == BO_EQ 7347 || Opc == BO_LE 7348 || Opc == BO_GE)); 7349 } else if (LHSType->isArrayType() && RHSType->isArrayType() && 7350 !DRL->getDecl()->getType()->isReferenceType() && 7351 !DRR->getDecl()->getType()->isReferenceType()) { 7352 // what is it always going to eval to? 7353 char always_evals_to; 7354 switch(Opc) { 7355 case BO_EQ: // e.g. array1 == array2 7356 always_evals_to = 0; // false 7357 break; 7358 case BO_NE: // e.g. array1 != array2 7359 always_evals_to = 1; // true 7360 break; 7361 default: 7362 // best we can say is 'a constant' 7363 always_evals_to = 2; // e.g. array1 <= array2 7364 break; 7365 } 7366 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7367 << 1 // array 7368 << always_evals_to); 7369 } 7370 } 7371 } 7372 7373 if (isa<CastExpr>(LHSStripped)) 7374 LHSStripped = LHSStripped->IgnoreParenCasts(); 7375 if (isa<CastExpr>(RHSStripped)) 7376 RHSStripped = RHSStripped->IgnoreParenCasts(); 7377 7378 // Warn about comparisons against a string constant (unless the other 7379 // operand is null), the user probably wants strcmp. 7380 Expr *literalString = 0; 7381 Expr *literalStringStripped = 0; 7382 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 7383 !RHSStripped->isNullPointerConstant(Context, 7384 Expr::NPC_ValueDependentIsNull)) { 7385 literalString = LHS.get(); 7386 literalStringStripped = LHSStripped; 7387 } else if ((isa<StringLiteral>(RHSStripped) || 7388 isa<ObjCEncodeExpr>(RHSStripped)) && 7389 !LHSStripped->isNullPointerConstant(Context, 7390 Expr::NPC_ValueDependentIsNull)) { 7391 literalString = RHS.get(); 7392 literalStringStripped = RHSStripped; 7393 } 7394 7395 if (literalString) { 7396 DiagRuntimeBehavior(Loc, 0, 7397 PDiag(diag::warn_stringcompare) 7398 << isa<ObjCEncodeExpr>(literalStringStripped) 7399 << literalString->getSourceRange()); 7400 } 7401 } 7402 7403 // C99 6.5.8p3 / C99 6.5.9p4 7404 if (LHS.get()->getType()->isArithmeticType() && 7405 RHS.get()->getType()->isArithmeticType()) { 7406 UsualArithmeticConversions(LHS, RHS); 7407 if (LHS.isInvalid() || RHS.isInvalid()) 7408 return QualType(); 7409 } 7410 else { 7411 LHS = UsualUnaryConversions(LHS.take()); 7412 if (LHS.isInvalid()) 7413 return QualType(); 7414 7415 RHS = UsualUnaryConversions(RHS.take()); 7416 if (RHS.isInvalid()) 7417 return QualType(); 7418 } 7419 7420 LHSType = LHS.get()->getType(); 7421 RHSType = RHS.get()->getType(); 7422 7423 // The result of comparisons is 'bool' in C++, 'int' in C. 7424 QualType ResultTy = Context.getLogicalOperationType(); 7425 7426 if (IsRelational) { 7427 if (LHSType->isRealType() && RHSType->isRealType()) 7428 return ResultTy; 7429 } else { 7430 // Check for comparisons of floating point operands using != and ==. 7431 if (LHSType->hasFloatingRepresentation()) 7432 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 7433 7434 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 7435 return ResultTy; 7436 } 7437 7438 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context, 7439 Expr::NPC_ValueDependentIsNull); 7440 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context, 7441 Expr::NPC_ValueDependentIsNull); 7442 7443 // All of the following pointer-related warnings are GCC extensions, except 7444 // when handling null pointer constants. 7445 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 7446 QualType LCanPointeeTy = 7447 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7448 QualType RCanPointeeTy = 7449 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7450 7451 if (getLangOpts().CPlusPlus) { 7452 if (LCanPointeeTy == RCanPointeeTy) 7453 return ResultTy; 7454 if (!IsRelational && 7455 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7456 // Valid unless comparison between non-null pointer and function pointer 7457 // This is a gcc extension compatibility comparison. 7458 // In a SFINAE context, we treat this as a hard error to maintain 7459 // conformance with the C++ standard. 7460 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7461 && !LHSIsNull && !RHSIsNull) { 7462 diagnoseFunctionPointerToVoidComparison( 7463 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 7464 7465 if (isSFINAEContext()) 7466 return QualType(); 7467 7468 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7469 return ResultTy; 7470 } 7471 } 7472 7473 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7474 return QualType(); 7475 else 7476 return ResultTy; 7477 } 7478 // C99 6.5.9p2 and C99 6.5.8p2 7479 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 7480 RCanPointeeTy.getUnqualifiedType())) { 7481 // Valid unless a relational comparison of function pointers 7482 if (IsRelational && LCanPointeeTy->isFunctionType()) { 7483 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 7484 << LHSType << RHSType << LHS.get()->getSourceRange() 7485 << RHS.get()->getSourceRange(); 7486 } 7487 } else if (!IsRelational && 7488 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7489 // Valid unless comparison between non-null pointer and function pointer 7490 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7491 && !LHSIsNull && !RHSIsNull) 7492 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 7493 /*isError*/false); 7494 } else { 7495 // Invalid 7496 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 7497 } 7498 if (LCanPointeeTy != RCanPointeeTy) { 7499 if (LHSIsNull && !RHSIsNull) 7500 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 7501 else 7502 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7503 } 7504 return ResultTy; 7505 } 7506 7507 if (getLangOpts().CPlusPlus) { 7508 // Comparison of nullptr_t with itself. 7509 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 7510 return ResultTy; 7511 7512 // Comparison of pointers with null pointer constants and equality 7513 // comparisons of member pointers to null pointer constants. 7514 if (RHSIsNull && 7515 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 7516 (!IsRelational && 7517 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 7518 RHS = ImpCastExprToType(RHS.take(), LHSType, 7519 LHSType->isMemberPointerType() 7520 ? CK_NullToMemberPointer 7521 : CK_NullToPointer); 7522 return ResultTy; 7523 } 7524 if (LHSIsNull && 7525 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 7526 (!IsRelational && 7527 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 7528 LHS = ImpCastExprToType(LHS.take(), RHSType, 7529 RHSType->isMemberPointerType() 7530 ? CK_NullToMemberPointer 7531 : CK_NullToPointer); 7532 return ResultTy; 7533 } 7534 7535 // Comparison of member pointers. 7536 if (!IsRelational && 7537 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 7538 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7539 return QualType(); 7540 else 7541 return ResultTy; 7542 } 7543 7544 // Handle scoped enumeration types specifically, since they don't promote 7545 // to integers. 7546 if (LHS.get()->getType()->isEnumeralType() && 7547 Context.hasSameUnqualifiedType(LHS.get()->getType(), 7548 RHS.get()->getType())) 7549 return ResultTy; 7550 } 7551 7552 // Handle block pointer types. 7553 if (!IsRelational && LHSType->isBlockPointerType() && 7554 RHSType->isBlockPointerType()) { 7555 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 7556 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 7557 7558 if (!LHSIsNull && !RHSIsNull && 7559 !Context.typesAreCompatible(lpointee, rpointee)) { 7560 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 7561 << LHSType << RHSType << LHS.get()->getSourceRange() 7562 << RHS.get()->getSourceRange(); 7563 } 7564 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7565 return ResultTy; 7566 } 7567 7568 // Allow block pointers to be compared with null pointer constants. 7569 if (!IsRelational 7570 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 7571 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 7572 if (!LHSIsNull && !RHSIsNull) { 7573 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 7574 ->getPointeeType()->isVoidType()) 7575 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 7576 ->getPointeeType()->isVoidType()))) 7577 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 7578 << LHSType << RHSType << LHS.get()->getSourceRange() 7579 << RHS.get()->getSourceRange(); 7580 } 7581 if (LHSIsNull && !RHSIsNull) 7582 LHS = ImpCastExprToType(LHS.take(), RHSType, 7583 RHSType->isPointerType() ? CK_BitCast 7584 : CK_AnyPointerToBlockPointerCast); 7585 else 7586 RHS = ImpCastExprToType(RHS.take(), LHSType, 7587 LHSType->isPointerType() ? CK_BitCast 7588 : CK_AnyPointerToBlockPointerCast); 7589 return ResultTy; 7590 } 7591 7592 if (LHSType->isObjCObjectPointerType() || 7593 RHSType->isObjCObjectPointerType()) { 7594 const PointerType *LPT = LHSType->getAs<PointerType>(); 7595 const PointerType *RPT = RHSType->getAs<PointerType>(); 7596 if (LPT || RPT) { 7597 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 7598 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 7599 7600 if (!LPtrToVoid && !RPtrToVoid && 7601 !Context.typesAreCompatible(LHSType, RHSType)) { 7602 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 7603 /*isError*/false); 7604 } 7605 if (LHSIsNull && !RHSIsNull) 7606 LHS = ImpCastExprToType(LHS.take(), RHSType, 7607 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 7608 else 7609 RHS = ImpCastExprToType(RHS.take(), LHSType, 7610 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 7611 return ResultTy; 7612 } 7613 if (LHSType->isObjCObjectPointerType() && 7614 RHSType->isObjCObjectPointerType()) { 7615 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 7616 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 7617 /*isError*/false); 7618 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 7619 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 7620 7621 if (LHSIsNull && !RHSIsNull) 7622 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 7623 else 7624 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7625 return ResultTy; 7626 } 7627 } 7628 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 7629 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 7630 unsigned DiagID = 0; 7631 bool isError = false; 7632 if (LangOpts.DebuggerSupport) { 7633 // Under a debugger, allow the comparison of pointers to integers, 7634 // since users tend to want to compare addresses. 7635 } else if ((LHSIsNull && LHSType->isIntegerType()) || 7636 (RHSIsNull && RHSType->isIntegerType())) { 7637 if (IsRelational && !getLangOpts().CPlusPlus) 7638 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 7639 } else if (IsRelational && !getLangOpts().CPlusPlus) 7640 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 7641 else if (getLangOpts().CPlusPlus) { 7642 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 7643 isError = true; 7644 } else 7645 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 7646 7647 if (DiagID) { 7648 Diag(Loc, DiagID) 7649 << LHSType << RHSType << LHS.get()->getSourceRange() 7650 << RHS.get()->getSourceRange(); 7651 if (isError) 7652 return QualType(); 7653 } 7654 7655 if (LHSType->isIntegerType()) 7656 LHS = ImpCastExprToType(LHS.take(), RHSType, 7657 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 7658 else 7659 RHS = ImpCastExprToType(RHS.take(), LHSType, 7660 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 7661 return ResultTy; 7662 } 7663 7664 // Handle block pointers. 7665 if (!IsRelational && RHSIsNull 7666 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 7667 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 7668 return ResultTy; 7669 } 7670 if (!IsRelational && LHSIsNull 7671 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 7672 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer); 7673 return ResultTy; 7674 } 7675 7676 return InvalidOperands(Loc, LHS, RHS); 7677} 7678 7679 7680// Return a signed type that is of identical size and number of elements. 7681// For floating point vectors, return an integer type of identical size 7682// and number of elements. 7683QualType Sema::GetSignedVectorType(QualType V) { 7684 const VectorType *VTy = V->getAs<VectorType>(); 7685 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 7686 if (TypeSize == Context.getTypeSize(Context.CharTy)) 7687 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 7688 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 7689 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 7690 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 7691 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 7692 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 7693 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 7694 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 7695 "Unhandled vector element size in vector compare"); 7696 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 7697} 7698 7699/// CheckVectorCompareOperands - vector comparisons are a clang extension that 7700/// operates on extended vector types. Instead of producing an IntTy result, 7701/// like a scalar comparison, a vector comparison produces a vector of integer 7702/// types. 7703QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 7704 SourceLocation Loc, 7705 bool IsRelational) { 7706 // Check to make sure we're operating on vectors of the same type and width, 7707 // Allowing one side to be a scalar of element type. 7708 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false); 7709 if (vType.isNull()) 7710 return vType; 7711 7712 QualType LHSType = LHS.get()->getType(); 7713 7714 // If AltiVec, the comparison results in a numeric type, i.e. 7715 // bool for C++, int for C 7716 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 7717 return Context.getLogicalOperationType(); 7718 7719 // For non-floating point types, check for self-comparisons of the form 7720 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 7721 // often indicate logic errors in the program. 7722 if (!LHSType->hasFloatingRepresentation()) { 7723 if (DeclRefExpr* DRL 7724 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 7725 if (DeclRefExpr* DRR 7726 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 7727 if (DRL->getDecl() == DRR->getDecl()) 7728 DiagRuntimeBehavior(Loc, 0, 7729 PDiag(diag::warn_comparison_always) 7730 << 0 // self- 7731 << 2 // "a constant" 7732 ); 7733 } 7734 7735 // Check for comparisons of floating point operands using != and ==. 7736 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 7737 assert (RHS.get()->getType()->hasFloatingRepresentation()); 7738 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 7739 } 7740 7741 // Return a signed type for the vector. 7742 return GetSignedVectorType(LHSType); 7743} 7744 7745QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 7746 SourceLocation Loc) { 7747 // Ensure that either both operands are of the same vector type, or 7748 // one operand is of a vector type and the other is of its element type. 7749 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false); 7750 if (vType.isNull()) 7751 return InvalidOperands(Loc, LHS, RHS); 7752 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 7753 vType->hasFloatingRepresentation()) 7754 return InvalidOperands(Loc, LHS, RHS); 7755 7756 return GetSignedVectorType(LHS.get()->getType()); 7757} 7758 7759inline QualType Sema::CheckBitwiseOperands( 7760 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 7761 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7762 7763 if (LHS.get()->getType()->isVectorType() || 7764 RHS.get()->getType()->isVectorType()) { 7765 if (LHS.get()->getType()->hasIntegerRepresentation() && 7766 RHS.get()->getType()->hasIntegerRepresentation()) 7767 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 7768 7769 return InvalidOperands(Loc, LHS, RHS); 7770 } 7771 7772 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS); 7773 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 7774 IsCompAssign); 7775 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 7776 return QualType(); 7777 LHS = LHSResult.take(); 7778 RHS = RHSResult.take(); 7779 7780 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 7781 return compType; 7782 return InvalidOperands(Loc, LHS, RHS); 7783} 7784 7785inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 7786 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) { 7787 7788 // Check vector operands differently. 7789 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 7790 return CheckVectorLogicalOperands(LHS, RHS, Loc); 7791 7792 // Diagnose cases where the user write a logical and/or but probably meant a 7793 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 7794 // is a constant. 7795 if (LHS.get()->getType()->isIntegerType() && 7796 !LHS.get()->getType()->isBooleanType() && 7797 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 7798 // Don't warn in macros or template instantiations. 7799 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 7800 // If the RHS can be constant folded, and if it constant folds to something 7801 // that isn't 0 or 1 (which indicate a potential logical operation that 7802 // happened to fold to true/false) then warn. 7803 // Parens on the RHS are ignored. 7804 llvm::APSInt Result; 7805 if (RHS.get()->EvaluateAsInt(Result, Context)) 7806 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) || 7807 (Result != 0 && Result != 1)) { 7808 Diag(Loc, diag::warn_logical_instead_of_bitwise) 7809 << RHS.get()->getSourceRange() 7810 << (Opc == BO_LAnd ? "&&" : "||"); 7811 // Suggest replacing the logical operator with the bitwise version 7812 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 7813 << (Opc == BO_LAnd ? "&" : "|") 7814 << FixItHint::CreateReplacement(SourceRange( 7815 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(), 7816 getLangOpts())), 7817 Opc == BO_LAnd ? "&" : "|"); 7818 if (Opc == BO_LAnd) 7819 // Suggest replacing "Foo() && kNonZero" with "Foo()" 7820 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 7821 << FixItHint::CreateRemoval( 7822 SourceRange( 7823 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(), 7824 0, getSourceManager(), 7825 getLangOpts()), 7826 RHS.get()->getLocEnd())); 7827 } 7828 } 7829 7830 if (!Context.getLangOpts().CPlusPlus) { 7831 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 7832 // not operate on the built-in scalar and vector float types. 7833 if (Context.getLangOpts().OpenCL && 7834 Context.getLangOpts().OpenCLVersion < 120) { 7835 if (LHS.get()->getType()->isFloatingType() || 7836 RHS.get()->getType()->isFloatingType()) 7837 return InvalidOperands(Loc, LHS, RHS); 7838 } 7839 7840 LHS = UsualUnaryConversions(LHS.take()); 7841 if (LHS.isInvalid()) 7842 return QualType(); 7843 7844 RHS = UsualUnaryConversions(RHS.take()); 7845 if (RHS.isInvalid()) 7846 return QualType(); 7847 7848 if (!LHS.get()->getType()->isScalarType() || 7849 !RHS.get()->getType()->isScalarType()) 7850 return InvalidOperands(Loc, LHS, RHS); 7851 7852 return Context.IntTy; 7853 } 7854 7855 // The following is safe because we only use this method for 7856 // non-overloadable operands. 7857 7858 // C++ [expr.log.and]p1 7859 // C++ [expr.log.or]p1 7860 // The operands are both contextually converted to type bool. 7861 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 7862 if (LHSRes.isInvalid()) 7863 return InvalidOperands(Loc, LHS, RHS); 7864 LHS = LHSRes; 7865 7866 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 7867 if (RHSRes.isInvalid()) 7868 return InvalidOperands(Loc, LHS, RHS); 7869 RHS = RHSRes; 7870 7871 // C++ [expr.log.and]p2 7872 // C++ [expr.log.or]p2 7873 // The result is a bool. 7874 return Context.BoolTy; 7875} 7876 7877static bool IsReadonlyMessage(Expr *E, Sema &S) { 7878 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 7879 if (!ME) return false; 7880 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 7881 ObjCMessageExpr *Base = 7882 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 7883 if (!Base) return false; 7884 return Base->getMethodDecl() != 0; 7885} 7886 7887/// Is the given expression (which must be 'const') a reference to a 7888/// variable which was originally non-const, but which has become 7889/// 'const' due to being captured within a block? 7890enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 7891static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 7892 assert(E->isLValue() && E->getType().isConstQualified()); 7893 E = E->IgnoreParens(); 7894 7895 // Must be a reference to a declaration from an enclosing scope. 7896 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 7897 if (!DRE) return NCCK_None; 7898 if (!DRE->refersToEnclosingLocal()) return NCCK_None; 7899 7900 // The declaration must be a variable which is not declared 'const'. 7901 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 7902 if (!var) return NCCK_None; 7903 if (var->getType().isConstQualified()) return NCCK_None; 7904 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 7905 7906 // Decide whether the first capture was for a block or a lambda. 7907 DeclContext *DC = S.CurContext; 7908 while (DC->getParent() != var->getDeclContext()) 7909 DC = DC->getParent(); 7910 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 7911} 7912 7913/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 7914/// emit an error and return true. If so, return false. 7915static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 7916 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 7917 SourceLocation OrigLoc = Loc; 7918 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 7919 &Loc); 7920 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 7921 IsLV = Expr::MLV_InvalidMessageExpression; 7922 if (IsLV == Expr::MLV_Valid) 7923 return false; 7924 7925 unsigned Diag = 0; 7926 bool NeedType = false; 7927 switch (IsLV) { // C99 6.5.16p2 7928 case Expr::MLV_ConstQualified: 7929 Diag = diag::err_typecheck_assign_const; 7930 7931 // Use a specialized diagnostic when we're assigning to an object 7932 // from an enclosing function or block. 7933 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 7934 if (NCCK == NCCK_Block) 7935 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 7936 else 7937 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue; 7938 break; 7939 } 7940 7941 // In ARC, use some specialized diagnostics for occasions where we 7942 // infer 'const'. These are always pseudo-strong variables. 7943 if (S.getLangOpts().ObjCAutoRefCount) { 7944 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 7945 if (declRef && isa<VarDecl>(declRef->getDecl())) { 7946 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 7947 7948 // Use the normal diagnostic if it's pseudo-__strong but the 7949 // user actually wrote 'const'. 7950 if (var->isARCPseudoStrong() && 7951 (!var->getTypeSourceInfo() || 7952 !var->getTypeSourceInfo()->getType().isConstQualified())) { 7953 // There are two pseudo-strong cases: 7954 // - self 7955 ObjCMethodDecl *method = S.getCurMethodDecl(); 7956 if (method && var == method->getSelfDecl()) 7957 Diag = method->isClassMethod() 7958 ? diag::err_typecheck_arc_assign_self_class_method 7959 : diag::err_typecheck_arc_assign_self; 7960 7961 // - fast enumeration variables 7962 else 7963 Diag = diag::err_typecheck_arr_assign_enumeration; 7964 7965 SourceRange Assign; 7966 if (Loc != OrigLoc) 7967 Assign = SourceRange(OrigLoc, OrigLoc); 7968 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 7969 // We need to preserve the AST regardless, so migration tool 7970 // can do its job. 7971 return false; 7972 } 7973 } 7974 } 7975 7976 break; 7977 case Expr::MLV_ArrayType: 7978 case Expr::MLV_ArrayTemporary: 7979 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 7980 NeedType = true; 7981 break; 7982 case Expr::MLV_NotObjectType: 7983 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 7984 NeedType = true; 7985 break; 7986 case Expr::MLV_LValueCast: 7987 Diag = diag::err_typecheck_lvalue_casts_not_supported; 7988 break; 7989 case Expr::MLV_Valid: 7990 llvm_unreachable("did not take early return for MLV_Valid"); 7991 case Expr::MLV_InvalidExpression: 7992 case Expr::MLV_MemberFunction: 7993 case Expr::MLV_ClassTemporary: 7994 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 7995 break; 7996 case Expr::MLV_IncompleteType: 7997 case Expr::MLV_IncompleteVoidType: 7998 return S.RequireCompleteType(Loc, E->getType(), 7999 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 8000 case Expr::MLV_DuplicateVectorComponents: 8001 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 8002 break; 8003 case Expr::MLV_NoSetterProperty: 8004 llvm_unreachable("readonly properties should be processed differently"); 8005 case Expr::MLV_InvalidMessageExpression: 8006 Diag = diag::error_readonly_message_assignment; 8007 break; 8008 case Expr::MLV_SubObjCPropertySetting: 8009 Diag = diag::error_no_subobject_property_setting; 8010 break; 8011 } 8012 8013 SourceRange Assign; 8014 if (Loc != OrigLoc) 8015 Assign = SourceRange(OrigLoc, OrigLoc); 8016 if (NeedType) 8017 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 8018 else 8019 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 8020 return true; 8021} 8022 8023static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 8024 SourceLocation Loc, 8025 Sema &Sema) { 8026 // C / C++ fields 8027 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 8028 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 8029 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 8030 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 8031 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 8032 } 8033 8034 // Objective-C instance variables 8035 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 8036 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 8037 if (OL && OR && OL->getDecl() == OR->getDecl()) { 8038 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 8039 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 8040 if (RL && RR && RL->getDecl() == RR->getDecl()) 8041 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 8042 } 8043} 8044 8045// C99 6.5.16.1 8046QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 8047 SourceLocation Loc, 8048 QualType CompoundType) { 8049 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 8050 8051 // Verify that LHS is a modifiable lvalue, and emit error if not. 8052 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 8053 return QualType(); 8054 8055 QualType LHSType = LHSExpr->getType(); 8056 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 8057 CompoundType; 8058 AssignConvertType ConvTy; 8059 if (CompoundType.isNull()) { 8060 Expr *RHSCheck = RHS.get(); 8061 8062 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 8063 8064 QualType LHSTy(LHSType); 8065 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 8066 if (RHS.isInvalid()) 8067 return QualType(); 8068 // Special case of NSObject attributes on c-style pointer types. 8069 if (ConvTy == IncompatiblePointer && 8070 ((Context.isObjCNSObjectType(LHSType) && 8071 RHSType->isObjCObjectPointerType()) || 8072 (Context.isObjCNSObjectType(RHSType) && 8073 LHSType->isObjCObjectPointerType()))) 8074 ConvTy = Compatible; 8075 8076 if (ConvTy == Compatible && 8077 LHSType->isObjCObjectType()) 8078 Diag(Loc, diag::err_objc_object_assignment) 8079 << LHSType; 8080 8081 // If the RHS is a unary plus or minus, check to see if they = and + are 8082 // right next to each other. If so, the user may have typo'd "x =+ 4" 8083 // instead of "x += 4". 8084 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 8085 RHSCheck = ICE->getSubExpr(); 8086 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 8087 if ((UO->getOpcode() == UO_Plus || 8088 UO->getOpcode() == UO_Minus) && 8089 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 8090 // Only if the two operators are exactly adjacent. 8091 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 8092 // And there is a space or other character before the subexpr of the 8093 // unary +/-. We don't want to warn on "x=-1". 8094 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 8095 UO->getSubExpr()->getLocStart().isFileID()) { 8096 Diag(Loc, diag::warn_not_compound_assign) 8097 << (UO->getOpcode() == UO_Plus ? "+" : "-") 8098 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 8099 } 8100 } 8101 8102 if (ConvTy == Compatible) { 8103 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 8104 // Warn about retain cycles where a block captures the LHS, but 8105 // not if the LHS is a simple variable into which the block is 8106 // being stored...unless that variable can be captured by reference! 8107 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 8108 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 8109 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 8110 checkRetainCycles(LHSExpr, RHS.get()); 8111 8112 // It is safe to assign a weak reference into a strong variable. 8113 // Although this code can still have problems: 8114 // id x = self.weakProp; 8115 // id y = self.weakProp; 8116 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8117 // paths through the function. This should be revisited if 8118 // -Wrepeated-use-of-weak is made flow-sensitive. 8119 DiagnosticsEngine::Level Level = 8120 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 8121 RHS.get()->getLocStart()); 8122 if (Level != DiagnosticsEngine::Ignored) 8123 getCurFunction()->markSafeWeakUse(RHS.get()); 8124 8125 } else if (getLangOpts().ObjCAutoRefCount) { 8126 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 8127 } 8128 } 8129 } else { 8130 // Compound assignment "x += y" 8131 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 8132 } 8133 8134 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 8135 RHS.get(), AA_Assigning)) 8136 return QualType(); 8137 8138 CheckForNullPointerDereference(*this, LHSExpr); 8139 8140 // C99 6.5.16p3: The type of an assignment expression is the type of the 8141 // left operand unless the left operand has qualified type, in which case 8142 // it is the unqualified version of the type of the left operand. 8143 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 8144 // is converted to the type of the assignment expression (above). 8145 // C++ 5.17p1: the type of the assignment expression is that of its left 8146 // operand. 8147 return (getLangOpts().CPlusPlus 8148 ? LHSType : LHSType.getUnqualifiedType()); 8149} 8150 8151// C99 6.5.17 8152static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 8153 SourceLocation Loc) { 8154 LHS = S.CheckPlaceholderExpr(LHS.take()); 8155 RHS = S.CheckPlaceholderExpr(RHS.take()); 8156 if (LHS.isInvalid() || RHS.isInvalid()) 8157 return QualType(); 8158 8159 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 8160 // operands, but not unary promotions. 8161 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 8162 8163 // So we treat the LHS as a ignored value, and in C++ we allow the 8164 // containing site to determine what should be done with the RHS. 8165 LHS = S.IgnoredValueConversions(LHS.take()); 8166 if (LHS.isInvalid()) 8167 return QualType(); 8168 8169 S.DiagnoseUnusedExprResult(LHS.get()); 8170 8171 if (!S.getLangOpts().CPlusPlus) { 8172 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take()); 8173 if (RHS.isInvalid()) 8174 return QualType(); 8175 if (!RHS.get()->getType()->isVoidType()) 8176 S.RequireCompleteType(Loc, RHS.get()->getType(), 8177 diag::err_incomplete_type); 8178 } 8179 8180 return RHS.get()->getType(); 8181} 8182 8183/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 8184/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 8185static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 8186 ExprValueKind &VK, 8187 SourceLocation OpLoc, 8188 bool IsInc, bool IsPrefix) { 8189 if (Op->isTypeDependent()) 8190 return S.Context.DependentTy; 8191 8192 QualType ResType = Op->getType(); 8193 // Atomic types can be used for increment / decrement where the non-atomic 8194 // versions can, so ignore the _Atomic() specifier for the purpose of 8195 // checking. 8196 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8197 ResType = ResAtomicType->getValueType(); 8198 8199 assert(!ResType.isNull() && "no type for increment/decrement expression"); 8200 8201 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 8202 // Decrement of bool is not allowed. 8203 if (!IsInc) { 8204 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 8205 return QualType(); 8206 } 8207 // Increment of bool sets it to true, but is deprecated. 8208 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 8209 } else if (ResType->isRealType()) { 8210 // OK! 8211 } else if (ResType->isPointerType()) { 8212 // C99 6.5.2.4p2, 6.5.6p2 8213 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 8214 return QualType(); 8215 } else if (ResType->isObjCObjectPointerType()) { 8216 // On modern runtimes, ObjC pointer arithmetic is forbidden. 8217 // Otherwise, we just need a complete type. 8218 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 8219 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 8220 return QualType(); 8221 } else if (ResType->isAnyComplexType()) { 8222 // C99 does not support ++/-- on complex types, we allow as an extension. 8223 S.Diag(OpLoc, diag::ext_integer_increment_complex) 8224 << ResType << Op->getSourceRange(); 8225 } else if (ResType->isPlaceholderType()) { 8226 ExprResult PR = S.CheckPlaceholderExpr(Op); 8227 if (PR.isInvalid()) return QualType(); 8228 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc, 8229 IsInc, IsPrefix); 8230 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 8231 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 8232 } else { 8233 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 8234 << ResType << int(IsInc) << Op->getSourceRange(); 8235 return QualType(); 8236 } 8237 // At this point, we know we have a real, complex or pointer type. 8238 // Now make sure the operand is a modifiable lvalue. 8239 if (CheckForModifiableLvalue(Op, OpLoc, S)) 8240 return QualType(); 8241 // In C++, a prefix increment is the same type as the operand. Otherwise 8242 // (in C or with postfix), the increment is the unqualified type of the 8243 // operand. 8244 if (IsPrefix && S.getLangOpts().CPlusPlus) { 8245 VK = VK_LValue; 8246 return ResType; 8247 } else { 8248 VK = VK_RValue; 8249 return ResType.getUnqualifiedType(); 8250 } 8251} 8252 8253 8254/// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 8255/// This routine allows us to typecheck complex/recursive expressions 8256/// where the declaration is needed for type checking. We only need to 8257/// handle cases when the expression references a function designator 8258/// or is an lvalue. Here are some examples: 8259/// - &(x) => x 8260/// - &*****f => f for f a function designator. 8261/// - &s.xx => s 8262/// - &s.zz[1].yy -> s, if zz is an array 8263/// - *(x + 1) -> x, if x is an array 8264/// - &"123"[2] -> 0 8265/// - & __real__ x -> x 8266static ValueDecl *getPrimaryDecl(Expr *E) { 8267 switch (E->getStmtClass()) { 8268 case Stmt::DeclRefExprClass: 8269 return cast<DeclRefExpr>(E)->getDecl(); 8270 case Stmt::MemberExprClass: 8271 // If this is an arrow operator, the address is an offset from 8272 // the base's value, so the object the base refers to is 8273 // irrelevant. 8274 if (cast<MemberExpr>(E)->isArrow()) 8275 return 0; 8276 // Otherwise, the expression refers to a part of the base 8277 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 8278 case Stmt::ArraySubscriptExprClass: { 8279 // FIXME: This code shouldn't be necessary! We should catch the implicit 8280 // promotion of register arrays earlier. 8281 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 8282 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 8283 if (ICE->getSubExpr()->getType()->isArrayType()) 8284 return getPrimaryDecl(ICE->getSubExpr()); 8285 } 8286 return 0; 8287 } 8288 case Stmt::UnaryOperatorClass: { 8289 UnaryOperator *UO = cast<UnaryOperator>(E); 8290 8291 switch(UO->getOpcode()) { 8292 case UO_Real: 8293 case UO_Imag: 8294 case UO_Extension: 8295 return getPrimaryDecl(UO->getSubExpr()); 8296 default: 8297 return 0; 8298 } 8299 } 8300 case Stmt::ParenExprClass: 8301 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 8302 case Stmt::ImplicitCastExprClass: 8303 // If the result of an implicit cast is an l-value, we care about 8304 // the sub-expression; otherwise, the result here doesn't matter. 8305 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 8306 default: 8307 return 0; 8308 } 8309} 8310 8311namespace { 8312 enum { 8313 AO_Bit_Field = 0, 8314 AO_Vector_Element = 1, 8315 AO_Property_Expansion = 2, 8316 AO_Register_Variable = 3, 8317 AO_No_Error = 4 8318 }; 8319} 8320/// \brief Diagnose invalid operand for address of operations. 8321/// 8322/// \param Type The type of operand which cannot have its address taken. 8323static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 8324 Expr *E, unsigned Type) { 8325 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 8326} 8327 8328/// CheckAddressOfOperand - The operand of & must be either a function 8329/// designator or an lvalue designating an object. If it is an lvalue, the 8330/// object cannot be declared with storage class register or be a bit field. 8331/// Note: The usual conversions are *not* applied to the operand of the & 8332/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 8333/// In C++, the operand might be an overloaded function name, in which case 8334/// we allow the '&' but retain the overloaded-function type. 8335static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp, 8336 SourceLocation OpLoc) { 8337 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 8338 if (PTy->getKind() == BuiltinType::Overload) { 8339 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) { 8340 assert(cast<UnaryOperator>(OrigOp.get()->IgnoreParens())->getOpcode() 8341 == UO_AddrOf); 8342 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 8343 << OrigOp.get()->getSourceRange(); 8344 return QualType(); 8345 } 8346 8347 OverloadExpr *Ovl = cast<OverloadExpr>(OrigOp.get()->IgnoreParens()); 8348 if (isa<UnresolvedMemberExpr>(Ovl)) 8349 if (!S.ResolveSingleFunctionTemplateSpecialization(Ovl)) { 8350 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8351 << OrigOp.get()->getSourceRange(); 8352 return QualType(); 8353 } 8354 8355 return S.Context.OverloadTy; 8356 } 8357 8358 if (PTy->getKind() == BuiltinType::UnknownAny) 8359 return S.Context.UnknownAnyTy; 8360 8361 if (PTy->getKind() == BuiltinType::BoundMember) { 8362 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8363 << OrigOp.get()->getSourceRange(); 8364 return QualType(); 8365 } 8366 8367 OrigOp = S.CheckPlaceholderExpr(OrigOp.take()); 8368 if (OrigOp.isInvalid()) return QualType(); 8369 } 8370 8371 if (OrigOp.get()->isTypeDependent()) 8372 return S.Context.DependentTy; 8373 8374 assert(!OrigOp.get()->getType()->isPlaceholderType()); 8375 8376 // Make sure to ignore parentheses in subsequent checks 8377 Expr *op = OrigOp.get()->IgnoreParens(); 8378 8379 if (S.getLangOpts().C99) { 8380 // Implement C99-only parts of addressof rules. 8381 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 8382 if (uOp->getOpcode() == UO_Deref) 8383 // Per C99 6.5.3.2, the address of a deref always returns a valid result 8384 // (assuming the deref expression is valid). 8385 return uOp->getSubExpr()->getType(); 8386 } 8387 // Technically, there should be a check for array subscript 8388 // expressions here, but the result of one is always an lvalue anyway. 8389 } 8390 ValueDecl *dcl = getPrimaryDecl(op); 8391 Expr::LValueClassification lval = op->ClassifyLValue(S.Context); 8392 unsigned AddressOfError = AO_No_Error; 8393 8394 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 8395 bool sfinae = (bool)S.isSFINAEContext(); 8396 S.Diag(OpLoc, S.isSFINAEContext() ? diag::err_typecheck_addrof_temporary 8397 : diag::ext_typecheck_addrof_temporary) 8398 << op->getType() << op->getSourceRange(); 8399 if (sfinae) 8400 return QualType(); 8401 // Materialize the temporary as an lvalue so that we can take its address. 8402 OrigOp = op = new (S.Context) 8403 MaterializeTemporaryExpr(op->getType(), OrigOp.take(), true, 0); 8404 } else if (isa<ObjCSelectorExpr>(op)) { 8405 return S.Context.getPointerType(op->getType()); 8406 } else if (lval == Expr::LV_MemberFunction) { 8407 // If it's an instance method, make a member pointer. 8408 // The expression must have exactly the form &A::foo. 8409 8410 // If the underlying expression isn't a decl ref, give up. 8411 if (!isa<DeclRefExpr>(op)) { 8412 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8413 << OrigOp.get()->getSourceRange(); 8414 return QualType(); 8415 } 8416 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 8417 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 8418 8419 // The id-expression was parenthesized. 8420 if (OrigOp.get() != DRE) { 8421 S.Diag(OpLoc, diag::err_parens_pointer_member_function) 8422 << OrigOp.get()->getSourceRange(); 8423 8424 // The method was named without a qualifier. 8425 } else if (!DRE->getQualifier()) { 8426 if (MD->getParent()->getName().empty()) 8427 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8428 << op->getSourceRange(); 8429 else { 8430 SmallString<32> Str; 8431 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 8432 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8433 << op->getSourceRange() 8434 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 8435 } 8436 } 8437 8438 return S.Context.getMemberPointerType(op->getType(), 8439 S.Context.getTypeDeclType(MD->getParent()).getTypePtr()); 8440 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 8441 // C99 6.5.3.2p1 8442 // The operand must be either an l-value or a function designator 8443 if (!op->getType()->isFunctionType()) { 8444 // Use a special diagnostic for loads from property references. 8445 if (isa<PseudoObjectExpr>(op)) { 8446 AddressOfError = AO_Property_Expansion; 8447 } else { 8448 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 8449 << op->getType() << op->getSourceRange(); 8450 return QualType(); 8451 } 8452 } 8453 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 8454 // The operand cannot be a bit-field 8455 AddressOfError = AO_Bit_Field; 8456 } else if (op->getObjectKind() == OK_VectorComponent) { 8457 // The operand cannot be an element of a vector 8458 AddressOfError = AO_Vector_Element; 8459 } else if (dcl) { // C99 6.5.3.2p1 8460 // We have an lvalue with a decl. Make sure the decl is not declared 8461 // with the register storage-class specifier. 8462 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 8463 // in C++ it is not error to take address of a register 8464 // variable (c++03 7.1.1P3) 8465 if (vd->getStorageClass() == SC_Register && 8466 !S.getLangOpts().CPlusPlus) { 8467 AddressOfError = AO_Register_Variable; 8468 } 8469 } else if (isa<FunctionTemplateDecl>(dcl)) { 8470 return S.Context.OverloadTy; 8471 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 8472 // Okay: we can take the address of a field. 8473 // Could be a pointer to member, though, if there is an explicit 8474 // scope qualifier for the class. 8475 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 8476 DeclContext *Ctx = dcl->getDeclContext(); 8477 if (Ctx && Ctx->isRecord()) { 8478 if (dcl->getType()->isReferenceType()) { 8479 S.Diag(OpLoc, 8480 diag::err_cannot_form_pointer_to_member_of_reference_type) 8481 << dcl->getDeclName() << dcl->getType(); 8482 return QualType(); 8483 } 8484 8485 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 8486 Ctx = Ctx->getParent(); 8487 return S.Context.getMemberPointerType(op->getType(), 8488 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 8489 } 8490 } 8491 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 8492 llvm_unreachable("Unknown/unexpected decl type"); 8493 } 8494 8495 if (AddressOfError != AO_No_Error) { 8496 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError); 8497 return QualType(); 8498 } 8499 8500 if (lval == Expr::LV_IncompleteVoidType) { 8501 // Taking the address of a void variable is technically illegal, but we 8502 // allow it in cases which are otherwise valid. 8503 // Example: "extern void x; void* y = &x;". 8504 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 8505 } 8506 8507 // If the operand has type "type", the result has type "pointer to type". 8508 if (op->getType()->isObjCObjectType()) 8509 return S.Context.getObjCObjectPointerType(op->getType()); 8510 return S.Context.getPointerType(op->getType()); 8511} 8512 8513/// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 8514static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 8515 SourceLocation OpLoc) { 8516 if (Op->isTypeDependent()) 8517 return S.Context.DependentTy; 8518 8519 ExprResult ConvResult = S.UsualUnaryConversions(Op); 8520 if (ConvResult.isInvalid()) 8521 return QualType(); 8522 Op = ConvResult.take(); 8523 QualType OpTy = Op->getType(); 8524 QualType Result; 8525 8526 if (isa<CXXReinterpretCastExpr>(Op)) { 8527 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 8528 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 8529 Op->getSourceRange()); 8530 } 8531 8532 // Note that per both C89 and C99, indirection is always legal, even if OpTy 8533 // is an incomplete type or void. It would be possible to warn about 8534 // dereferencing a void pointer, but it's completely well-defined, and such a 8535 // warning is unlikely to catch any mistakes. 8536 if (const PointerType *PT = OpTy->getAs<PointerType>()) 8537 Result = PT->getPointeeType(); 8538 else if (const ObjCObjectPointerType *OPT = 8539 OpTy->getAs<ObjCObjectPointerType>()) 8540 Result = OPT->getPointeeType(); 8541 else { 8542 ExprResult PR = S.CheckPlaceholderExpr(Op); 8543 if (PR.isInvalid()) return QualType(); 8544 if (PR.take() != Op) 8545 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc); 8546 } 8547 8548 if (Result.isNull()) { 8549 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 8550 << OpTy << Op->getSourceRange(); 8551 return QualType(); 8552 } 8553 8554 // Dereferences are usually l-values... 8555 VK = VK_LValue; 8556 8557 // ...except that certain expressions are never l-values in C. 8558 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 8559 VK = VK_RValue; 8560 8561 return Result; 8562} 8563 8564static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode( 8565 tok::TokenKind Kind) { 8566 BinaryOperatorKind Opc; 8567 switch (Kind) { 8568 default: llvm_unreachable("Unknown binop!"); 8569 case tok::periodstar: Opc = BO_PtrMemD; break; 8570 case tok::arrowstar: Opc = BO_PtrMemI; break; 8571 case tok::star: Opc = BO_Mul; break; 8572 case tok::slash: Opc = BO_Div; break; 8573 case tok::percent: Opc = BO_Rem; break; 8574 case tok::plus: Opc = BO_Add; break; 8575 case tok::minus: Opc = BO_Sub; break; 8576 case tok::lessless: Opc = BO_Shl; break; 8577 case tok::greatergreater: Opc = BO_Shr; break; 8578 case tok::lessequal: Opc = BO_LE; break; 8579 case tok::less: Opc = BO_LT; break; 8580 case tok::greaterequal: Opc = BO_GE; break; 8581 case tok::greater: Opc = BO_GT; break; 8582 case tok::exclaimequal: Opc = BO_NE; break; 8583 case tok::equalequal: Opc = BO_EQ; break; 8584 case tok::amp: Opc = BO_And; break; 8585 case tok::caret: Opc = BO_Xor; break; 8586 case tok::pipe: Opc = BO_Or; break; 8587 case tok::ampamp: Opc = BO_LAnd; break; 8588 case tok::pipepipe: Opc = BO_LOr; break; 8589 case tok::equal: Opc = BO_Assign; break; 8590 case tok::starequal: Opc = BO_MulAssign; break; 8591 case tok::slashequal: Opc = BO_DivAssign; break; 8592 case tok::percentequal: Opc = BO_RemAssign; break; 8593 case tok::plusequal: Opc = BO_AddAssign; break; 8594 case tok::minusequal: Opc = BO_SubAssign; break; 8595 case tok::lesslessequal: Opc = BO_ShlAssign; break; 8596 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 8597 case tok::ampequal: Opc = BO_AndAssign; break; 8598 case tok::caretequal: Opc = BO_XorAssign; break; 8599 case tok::pipeequal: Opc = BO_OrAssign; break; 8600 case tok::comma: Opc = BO_Comma; break; 8601 } 8602 return Opc; 8603} 8604 8605static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 8606 tok::TokenKind Kind) { 8607 UnaryOperatorKind Opc; 8608 switch (Kind) { 8609 default: llvm_unreachable("Unknown unary op!"); 8610 case tok::plusplus: Opc = UO_PreInc; break; 8611 case tok::minusminus: Opc = UO_PreDec; break; 8612 case tok::amp: Opc = UO_AddrOf; break; 8613 case tok::star: Opc = UO_Deref; break; 8614 case tok::plus: Opc = UO_Plus; break; 8615 case tok::minus: Opc = UO_Minus; break; 8616 case tok::tilde: Opc = UO_Not; break; 8617 case tok::exclaim: Opc = UO_LNot; break; 8618 case tok::kw___real: Opc = UO_Real; break; 8619 case tok::kw___imag: Opc = UO_Imag; break; 8620 case tok::kw___extension__: Opc = UO_Extension; break; 8621 } 8622 return Opc; 8623} 8624 8625/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 8626/// This warning is only emitted for builtin assignment operations. It is also 8627/// suppressed in the event of macro expansions. 8628static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 8629 SourceLocation OpLoc) { 8630 if (!S.ActiveTemplateInstantiations.empty()) 8631 return; 8632 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 8633 return; 8634 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 8635 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 8636 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 8637 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 8638 if (!LHSDeclRef || !RHSDeclRef || 8639 LHSDeclRef->getLocation().isMacroID() || 8640 RHSDeclRef->getLocation().isMacroID()) 8641 return; 8642 const ValueDecl *LHSDecl = 8643 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 8644 const ValueDecl *RHSDecl = 8645 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 8646 if (LHSDecl != RHSDecl) 8647 return; 8648 if (LHSDecl->getType().isVolatileQualified()) 8649 return; 8650 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 8651 if (RefTy->getPointeeType().isVolatileQualified()) 8652 return; 8653 8654 S.Diag(OpLoc, diag::warn_self_assignment) 8655 << LHSDeclRef->getType() 8656 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8657} 8658 8659/// Check if a bitwise-& is performed on an Objective-C pointer. This 8660/// is usually indicative of introspection within the Objective-C pointer. 8661static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 8662 SourceLocation OpLoc) { 8663 if (!S.getLangOpts().ObjC1) 8664 return; 8665 8666 const Expr *ObjCPointerExpr = 0, *OtherExpr = 0; 8667 const Expr *LHS = L.get(); 8668 const Expr *RHS = R.get(); 8669 8670 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 8671 ObjCPointerExpr = LHS; 8672 OtherExpr = RHS; 8673 } 8674 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 8675 ObjCPointerExpr = RHS; 8676 OtherExpr = LHS; 8677 } 8678 8679 // This warning is deliberately made very specific to reduce false 8680 // positives with logic that uses '&' for hashing. This logic mainly 8681 // looks for code trying to introspect into tagged pointers, which 8682 // code should generally never do. 8683 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 8684 unsigned Diag = diag::warn_objc_pointer_masking; 8685 // Determine if we are introspecting the result of performSelectorXXX. 8686 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 8687 // Special case messages to -performSelector and friends, which 8688 // can return non-pointer values boxed in a pointer value. 8689 // Some clients may wish to silence warnings in this subcase. 8690 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 8691 Selector S = ME->getSelector(); 8692 StringRef SelArg0 = S.getNameForSlot(0); 8693 if (SelArg0.startswith("performSelector")) 8694 Diag = diag::warn_objc_pointer_masking_performSelector; 8695 } 8696 8697 S.Diag(OpLoc, Diag) 8698 << ObjCPointerExpr->getSourceRange(); 8699 } 8700} 8701 8702/// CreateBuiltinBinOp - Creates a new built-in binary operation with 8703/// operator @p Opc at location @c TokLoc. This routine only supports 8704/// built-in operations; ActOnBinOp handles overloaded operators. 8705ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 8706 BinaryOperatorKind Opc, 8707 Expr *LHSExpr, Expr *RHSExpr) { 8708 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 8709 // The syntax only allows initializer lists on the RHS of assignment, 8710 // so we don't need to worry about accepting invalid code for 8711 // non-assignment operators. 8712 // C++11 5.17p9: 8713 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 8714 // of x = {} is x = T(). 8715 InitializationKind Kind = 8716 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 8717 InitializedEntity Entity = 8718 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 8719 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 8720 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 8721 if (Init.isInvalid()) 8722 return Init; 8723 RHSExpr = Init.take(); 8724 } 8725 8726 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 8727 QualType ResultTy; // Result type of the binary operator. 8728 // The following two variables are used for compound assignment operators 8729 QualType CompLHSTy; // Type of LHS after promotions for computation 8730 QualType CompResultTy; // Type of computation result 8731 ExprValueKind VK = VK_RValue; 8732 ExprObjectKind OK = OK_Ordinary; 8733 8734 switch (Opc) { 8735 case BO_Assign: 8736 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 8737 if (getLangOpts().CPlusPlus && 8738 LHS.get()->getObjectKind() != OK_ObjCProperty) { 8739 VK = LHS.get()->getValueKind(); 8740 OK = LHS.get()->getObjectKind(); 8741 } 8742 if (!ResultTy.isNull()) 8743 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 8744 break; 8745 case BO_PtrMemD: 8746 case BO_PtrMemI: 8747 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 8748 Opc == BO_PtrMemI); 8749 break; 8750 case BO_Mul: 8751 case BO_Div: 8752 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 8753 Opc == BO_Div); 8754 break; 8755 case BO_Rem: 8756 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 8757 break; 8758 case BO_Add: 8759 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 8760 break; 8761 case BO_Sub: 8762 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 8763 break; 8764 case BO_Shl: 8765 case BO_Shr: 8766 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 8767 break; 8768 case BO_LE: 8769 case BO_LT: 8770 case BO_GE: 8771 case BO_GT: 8772 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 8773 break; 8774 case BO_EQ: 8775 case BO_NE: 8776 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 8777 break; 8778 case BO_And: 8779 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 8780 case BO_Xor: 8781 case BO_Or: 8782 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 8783 break; 8784 case BO_LAnd: 8785 case BO_LOr: 8786 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 8787 break; 8788 case BO_MulAssign: 8789 case BO_DivAssign: 8790 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 8791 Opc == BO_DivAssign); 8792 CompLHSTy = CompResultTy; 8793 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8794 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8795 break; 8796 case BO_RemAssign: 8797 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 8798 CompLHSTy = CompResultTy; 8799 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8800 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8801 break; 8802 case BO_AddAssign: 8803 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 8804 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8805 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8806 break; 8807 case BO_SubAssign: 8808 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 8809 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8810 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8811 break; 8812 case BO_ShlAssign: 8813 case BO_ShrAssign: 8814 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 8815 CompLHSTy = CompResultTy; 8816 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8817 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8818 break; 8819 case BO_AndAssign: 8820 case BO_XorAssign: 8821 case BO_OrAssign: 8822 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 8823 CompLHSTy = CompResultTy; 8824 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 8825 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 8826 break; 8827 case BO_Comma: 8828 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 8829 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 8830 VK = RHS.get()->getValueKind(); 8831 OK = RHS.get()->getObjectKind(); 8832 } 8833 break; 8834 } 8835 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 8836 return ExprError(); 8837 8838 // Check for array bounds violations for both sides of the BinaryOperator 8839 CheckArrayAccess(LHS.get()); 8840 CheckArrayAccess(RHS.get()); 8841 8842 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 8843 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 8844 &Context.Idents.get("object_setClass"), 8845 SourceLocation(), LookupOrdinaryName); 8846 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 8847 SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 8848 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 8849 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 8850 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 8851 FixItHint::CreateInsertion(RHSLocEnd, ")"); 8852 } 8853 else 8854 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 8855 } 8856 else if (const ObjCIvarRefExpr *OIRE = 8857 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 8858 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 8859 8860 if (CompResultTy.isNull()) 8861 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc, 8862 ResultTy, VK, OK, OpLoc, 8863 FPFeatures.fp_contract)); 8864 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 8865 OK_ObjCProperty) { 8866 VK = VK_LValue; 8867 OK = LHS.get()->getObjectKind(); 8868 } 8869 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc, 8870 ResultTy, VK, OK, CompLHSTy, 8871 CompResultTy, OpLoc, 8872 FPFeatures.fp_contract)); 8873} 8874 8875/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 8876/// operators are mixed in a way that suggests that the programmer forgot that 8877/// comparison operators have higher precedence. The most typical example of 8878/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 8879static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 8880 SourceLocation OpLoc, Expr *LHSExpr, 8881 Expr *RHSExpr) { 8882 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 8883 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 8884 8885 // Check that one of the sides is a comparison operator. 8886 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 8887 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 8888 if (!isLeftComp && !isRightComp) 8889 return; 8890 8891 // Bitwise operations are sometimes used as eager logical ops. 8892 // Don't diagnose this. 8893 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 8894 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 8895 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise)) 8896 return; 8897 8898 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 8899 OpLoc) 8900 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 8901 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 8902 SourceRange ParensRange = isLeftComp ? 8903 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 8904 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart()); 8905 8906 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 8907 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 8908 SuggestParentheses(Self, OpLoc, 8909 Self.PDiag(diag::note_precedence_silence) << OpStr, 8910 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 8911 SuggestParentheses(Self, OpLoc, 8912 Self.PDiag(diag::note_precedence_bitwise_first) 8913 << BinaryOperator::getOpcodeStr(Opc), 8914 ParensRange); 8915} 8916 8917/// \brief It accepts a '&' expr that is inside a '|' one. 8918/// Emit a diagnostic together with a fixit hint that wraps the '&' expression 8919/// in parentheses. 8920static void 8921EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 8922 BinaryOperator *Bop) { 8923 assert(Bop->getOpcode() == BO_And); 8924 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 8925 << Bop->getSourceRange() << OpLoc; 8926 SuggestParentheses(Self, Bop->getOperatorLoc(), 8927 Self.PDiag(diag::note_precedence_silence) 8928 << Bop->getOpcodeStr(), 8929 Bop->getSourceRange()); 8930} 8931 8932/// \brief It accepts a '&&' expr that is inside a '||' one. 8933/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 8934/// in parentheses. 8935static void 8936EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 8937 BinaryOperator *Bop) { 8938 assert(Bop->getOpcode() == BO_LAnd); 8939 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 8940 << Bop->getSourceRange() << OpLoc; 8941 SuggestParentheses(Self, Bop->getOperatorLoc(), 8942 Self.PDiag(diag::note_precedence_silence) 8943 << Bop->getOpcodeStr(), 8944 Bop->getSourceRange()); 8945} 8946 8947/// \brief Returns true if the given expression can be evaluated as a constant 8948/// 'true'. 8949static bool EvaluatesAsTrue(Sema &S, Expr *E) { 8950 bool Res; 8951 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 8952} 8953 8954/// \brief Returns true if the given expression can be evaluated as a constant 8955/// 'false'. 8956static bool EvaluatesAsFalse(Sema &S, Expr *E) { 8957 bool Res; 8958 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 8959} 8960 8961/// \brief Look for '&&' in the left hand of a '||' expr. 8962static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 8963 Expr *LHSExpr, Expr *RHSExpr) { 8964 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 8965 if (Bop->getOpcode() == BO_LAnd) { 8966 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 8967 if (EvaluatesAsFalse(S, RHSExpr)) 8968 return; 8969 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 8970 if (!EvaluatesAsTrue(S, Bop->getLHS())) 8971 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 8972 } else if (Bop->getOpcode() == BO_LOr) { 8973 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 8974 // If it's "a || b && 1 || c" we didn't warn earlier for 8975 // "a || b && 1", but warn now. 8976 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 8977 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 8978 } 8979 } 8980 } 8981} 8982 8983/// \brief Look for '&&' in the right hand of a '||' expr. 8984static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 8985 Expr *LHSExpr, Expr *RHSExpr) { 8986 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 8987 if (Bop->getOpcode() == BO_LAnd) { 8988 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 8989 if (EvaluatesAsFalse(S, LHSExpr)) 8990 return; 8991 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 8992 if (!EvaluatesAsTrue(S, Bop->getRHS())) 8993 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 8994 } 8995 } 8996} 8997 8998/// \brief Look for '&' in the left or right hand of a '|' expr. 8999static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 9000 Expr *OrArg) { 9001 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 9002 if (Bop->getOpcode() == BO_And) 9003 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 9004 } 9005} 9006 9007static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 9008 Expr *SubExpr, StringRef Shift) { 9009 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 9010 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 9011 StringRef Op = Bop->getOpcodeStr(); 9012 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 9013 << Bop->getSourceRange() << OpLoc << Shift << Op; 9014 SuggestParentheses(S, Bop->getOperatorLoc(), 9015 S.PDiag(diag::note_precedence_silence) << Op, 9016 Bop->getSourceRange()); 9017 } 9018 } 9019} 9020 9021static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 9022 Expr *LHSExpr, Expr *RHSExpr) { 9023 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 9024 if (!OCE) 9025 return; 9026 9027 FunctionDecl *FD = OCE->getDirectCallee(); 9028 if (!FD || !FD->isOverloadedOperator()) 9029 return; 9030 9031 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 9032 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 9033 return; 9034 9035 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 9036 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 9037 << (Kind == OO_LessLess); 9038 SuggestParentheses(S, OCE->getOperatorLoc(), 9039 S.PDiag(diag::note_precedence_silence) 9040 << (Kind == OO_LessLess ? "<<" : ">>"), 9041 OCE->getSourceRange()); 9042 SuggestParentheses(S, OpLoc, 9043 S.PDiag(diag::note_evaluate_comparison_first), 9044 SourceRange(OCE->getArg(1)->getLocStart(), 9045 RHSExpr->getLocEnd())); 9046} 9047 9048/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 9049/// precedence. 9050static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 9051 SourceLocation OpLoc, Expr *LHSExpr, 9052 Expr *RHSExpr){ 9053 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 9054 if (BinaryOperator::isBitwiseOp(Opc)) 9055 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 9056 9057 // Diagnose "arg1 & arg2 | arg3" 9058 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 9059 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr); 9060 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr); 9061 } 9062 9063 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 9064 // We don't warn for 'assert(a || b && "bad")' since this is safe. 9065 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 9066 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 9067 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 9068 } 9069 9070 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 9071 || Opc == BO_Shr) { 9072 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 9073 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 9074 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 9075 } 9076 9077 // Warn on overloaded shift operators and comparisons, such as: 9078 // cout << 5 == 4; 9079 if (BinaryOperator::isComparisonOp(Opc)) 9080 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 9081} 9082 9083// Binary Operators. 'Tok' is the token for the operator. 9084ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 9085 tok::TokenKind Kind, 9086 Expr *LHSExpr, Expr *RHSExpr) { 9087 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 9088 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression"); 9089 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression"); 9090 9091 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 9092 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 9093 9094 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 9095} 9096 9097/// Build an overloaded binary operator expression in the given scope. 9098static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 9099 BinaryOperatorKind Opc, 9100 Expr *LHS, Expr *RHS) { 9101 // Find all of the overloaded operators visible from this 9102 // point. We perform both an operator-name lookup from the local 9103 // scope and an argument-dependent lookup based on the types of 9104 // the arguments. 9105 UnresolvedSet<16> Functions; 9106 OverloadedOperatorKind OverOp 9107 = BinaryOperator::getOverloadedOperator(Opc); 9108 if (Sc && OverOp != OO_None) 9109 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 9110 RHS->getType(), Functions); 9111 9112 // Build the (potentially-overloaded, potentially-dependent) 9113 // binary operation. 9114 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 9115} 9116 9117ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 9118 BinaryOperatorKind Opc, 9119 Expr *LHSExpr, Expr *RHSExpr) { 9120 // We want to end up calling one of checkPseudoObjectAssignment 9121 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 9122 // both expressions are overloadable or either is type-dependent), 9123 // or CreateBuiltinBinOp (in any other case). We also want to get 9124 // any placeholder types out of the way. 9125 9126 // Handle pseudo-objects in the LHS. 9127 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 9128 // Assignments with a pseudo-object l-value need special analysis. 9129 if (pty->getKind() == BuiltinType::PseudoObject && 9130 BinaryOperator::isAssignmentOp(Opc)) 9131 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 9132 9133 // Don't resolve overloads if the other type is overloadable. 9134 if (pty->getKind() == BuiltinType::Overload) { 9135 // We can't actually test that if we still have a placeholder, 9136 // though. Fortunately, none of the exceptions we see in that 9137 // code below are valid when the LHS is an overload set. Note 9138 // that an overload set can be dependently-typed, but it never 9139 // instantiates to having an overloadable type. 9140 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9141 if (resolvedRHS.isInvalid()) return ExprError(); 9142 RHSExpr = resolvedRHS.take(); 9143 9144 if (RHSExpr->isTypeDependent() || 9145 RHSExpr->getType()->isOverloadableType()) 9146 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9147 } 9148 9149 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 9150 if (LHS.isInvalid()) return ExprError(); 9151 LHSExpr = LHS.take(); 9152 } 9153 9154 // Handle pseudo-objects in the RHS. 9155 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 9156 // An overload in the RHS can potentially be resolved by the type 9157 // being assigned to. 9158 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 9159 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9160 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9161 9162 if (LHSExpr->getType()->isOverloadableType()) 9163 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9164 9165 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9166 } 9167 9168 // Don't resolve overloads if the other type is overloadable. 9169 if (pty->getKind() == BuiltinType::Overload && 9170 LHSExpr->getType()->isOverloadableType()) 9171 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9172 9173 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9174 if (!resolvedRHS.isUsable()) return ExprError(); 9175 RHSExpr = resolvedRHS.take(); 9176 } 9177 9178 if (getLangOpts().CPlusPlus) { 9179 // If either expression is type-dependent, always build an 9180 // overloaded op. 9181 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9182 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9183 9184 // Otherwise, build an overloaded op if either expression has an 9185 // overloadable type. 9186 if (LHSExpr->getType()->isOverloadableType() || 9187 RHSExpr->getType()->isOverloadableType()) 9188 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9189 } 9190 9191 // Build a built-in binary operation. 9192 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9193} 9194 9195ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 9196 UnaryOperatorKind Opc, 9197 Expr *InputExpr) { 9198 ExprResult Input = Owned(InputExpr); 9199 ExprValueKind VK = VK_RValue; 9200 ExprObjectKind OK = OK_Ordinary; 9201 QualType resultType; 9202 switch (Opc) { 9203 case UO_PreInc: 9204 case UO_PreDec: 9205 case UO_PostInc: 9206 case UO_PostDec: 9207 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc, 9208 Opc == UO_PreInc || 9209 Opc == UO_PostInc, 9210 Opc == UO_PreInc || 9211 Opc == UO_PreDec); 9212 break; 9213 case UO_AddrOf: 9214 resultType = CheckAddressOfOperand(*this, Input, OpLoc); 9215 break; 9216 case UO_Deref: { 9217 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 9218 if (Input.isInvalid()) return ExprError(); 9219 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 9220 break; 9221 } 9222 case UO_Plus: 9223 case UO_Minus: 9224 Input = UsualUnaryConversions(Input.take()); 9225 if (Input.isInvalid()) return ExprError(); 9226 resultType = Input.get()->getType(); 9227 if (resultType->isDependentType()) 9228 break; 9229 if (resultType->isArithmeticType() || // C99 6.5.3.3p1 9230 resultType->isVectorType()) 9231 break; 9232 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7 9233 resultType->isEnumeralType()) 9234 break; 9235 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 9236 Opc == UO_Plus && 9237 resultType->isPointerType()) 9238 break; 9239 9240 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9241 << resultType << Input.get()->getSourceRange()); 9242 9243 case UO_Not: // bitwise complement 9244 Input = UsualUnaryConversions(Input.take()); 9245 if (Input.isInvalid()) 9246 return ExprError(); 9247 resultType = Input.get()->getType(); 9248 if (resultType->isDependentType()) 9249 break; 9250 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 9251 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 9252 // C99 does not support '~' for complex conjugation. 9253 Diag(OpLoc, diag::ext_integer_complement_complex) 9254 << resultType << Input.get()->getSourceRange(); 9255 else if (resultType->hasIntegerRepresentation()) 9256 break; 9257 else if (resultType->isExtVectorType()) { 9258 if (Context.getLangOpts().OpenCL) { 9259 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 9260 // on vector float types. 9261 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9262 if (!T->isIntegerType()) 9263 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9264 << resultType << Input.get()->getSourceRange()); 9265 } 9266 break; 9267 } else { 9268 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9269 << resultType << Input.get()->getSourceRange()); 9270 } 9271 break; 9272 9273 case UO_LNot: // logical negation 9274 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 9275 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 9276 if (Input.isInvalid()) return ExprError(); 9277 resultType = Input.get()->getType(); 9278 9279 // Though we still have to promote half FP to float... 9280 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 9281 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take(); 9282 resultType = Context.FloatTy; 9283 } 9284 9285 if (resultType->isDependentType()) 9286 break; 9287 if (resultType->isScalarType()) { 9288 // C99 6.5.3.3p1: ok, fallthrough; 9289 if (Context.getLangOpts().CPlusPlus) { 9290 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 9291 // operand contextually converted to bool. 9292 Input = ImpCastExprToType(Input.take(), Context.BoolTy, 9293 ScalarTypeToBooleanCastKind(resultType)); 9294 } else if (Context.getLangOpts().OpenCL && 9295 Context.getLangOpts().OpenCLVersion < 120) { 9296 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9297 // operate on scalar float types. 9298 if (!resultType->isIntegerType()) 9299 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9300 << resultType << Input.get()->getSourceRange()); 9301 } 9302 } else if (resultType->isExtVectorType()) { 9303 if (Context.getLangOpts().OpenCL && 9304 Context.getLangOpts().OpenCLVersion < 120) { 9305 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9306 // operate on vector float types. 9307 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9308 if (!T->isIntegerType()) 9309 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9310 << resultType << Input.get()->getSourceRange()); 9311 } 9312 // Vector logical not returns the signed variant of the operand type. 9313 resultType = GetSignedVectorType(resultType); 9314 break; 9315 } else { 9316 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9317 << resultType << Input.get()->getSourceRange()); 9318 } 9319 9320 // LNot always has type int. C99 6.5.3.3p5. 9321 // In C++, it's bool. C++ 5.3.1p8 9322 resultType = Context.getLogicalOperationType(); 9323 break; 9324 case UO_Real: 9325 case UO_Imag: 9326 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 9327 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 9328 // complex l-values to ordinary l-values and all other values to r-values. 9329 if (Input.isInvalid()) return ExprError(); 9330 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 9331 if (Input.get()->getValueKind() != VK_RValue && 9332 Input.get()->getObjectKind() == OK_Ordinary) 9333 VK = Input.get()->getValueKind(); 9334 } else if (!getLangOpts().CPlusPlus) { 9335 // In C, a volatile scalar is read by __imag. In C++, it is not. 9336 Input = DefaultLvalueConversion(Input.take()); 9337 } 9338 break; 9339 case UO_Extension: 9340 resultType = Input.get()->getType(); 9341 VK = Input.get()->getValueKind(); 9342 OK = Input.get()->getObjectKind(); 9343 break; 9344 } 9345 if (resultType.isNull() || Input.isInvalid()) 9346 return ExprError(); 9347 9348 // Check for array bounds violations in the operand of the UnaryOperator, 9349 // except for the '*' and '&' operators that have to be handled specially 9350 // by CheckArrayAccess (as there are special cases like &array[arraysize] 9351 // that are explicitly defined as valid by the standard). 9352 if (Opc != UO_AddrOf && Opc != UO_Deref) 9353 CheckArrayAccess(Input.get()); 9354 9355 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType, 9356 VK, OK, OpLoc)); 9357} 9358 9359/// \brief Determine whether the given expression is a qualified member 9360/// access expression, of a form that could be turned into a pointer to member 9361/// with the address-of operator. 9362static bool isQualifiedMemberAccess(Expr *E) { 9363 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9364 if (!DRE->getQualifier()) 9365 return false; 9366 9367 ValueDecl *VD = DRE->getDecl(); 9368 if (!VD->isCXXClassMember()) 9369 return false; 9370 9371 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 9372 return true; 9373 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 9374 return Method->isInstance(); 9375 9376 return false; 9377 } 9378 9379 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 9380 if (!ULE->getQualifier()) 9381 return false; 9382 9383 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(), 9384 DEnd = ULE->decls_end(); 9385 D != DEnd; ++D) { 9386 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) { 9387 if (Method->isInstance()) 9388 return true; 9389 } else { 9390 // Overload set does not contain methods. 9391 break; 9392 } 9393 } 9394 9395 return false; 9396 } 9397 9398 return false; 9399} 9400 9401ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 9402 UnaryOperatorKind Opc, Expr *Input) { 9403 // First things first: handle placeholders so that the 9404 // overloaded-operator check considers the right type. 9405 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 9406 // Increment and decrement of pseudo-object references. 9407 if (pty->getKind() == BuiltinType::PseudoObject && 9408 UnaryOperator::isIncrementDecrementOp(Opc)) 9409 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 9410 9411 // extension is always a builtin operator. 9412 if (Opc == UO_Extension) 9413 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9414 9415 // & gets special logic for several kinds of placeholder. 9416 // The builtin code knows what to do. 9417 if (Opc == UO_AddrOf && 9418 (pty->getKind() == BuiltinType::Overload || 9419 pty->getKind() == BuiltinType::UnknownAny || 9420 pty->getKind() == BuiltinType::BoundMember)) 9421 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9422 9423 // Anything else needs to be handled now. 9424 ExprResult Result = CheckPlaceholderExpr(Input); 9425 if (Result.isInvalid()) return ExprError(); 9426 Input = Result.take(); 9427 } 9428 9429 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 9430 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 9431 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 9432 // Find all of the overloaded operators visible from this 9433 // point. We perform both an operator-name lookup from the local 9434 // scope and an argument-dependent lookup based on the types of 9435 // the arguments. 9436 UnresolvedSet<16> Functions; 9437 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 9438 if (S && OverOp != OO_None) 9439 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 9440 Functions); 9441 9442 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 9443 } 9444 9445 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9446} 9447 9448// Unary Operators. 'Tok' is the token for the operator. 9449ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 9450 tok::TokenKind Op, Expr *Input) { 9451 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 9452} 9453 9454/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 9455ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 9456 LabelDecl *TheDecl) { 9457 TheDecl->setUsed(); 9458 // Create the AST node. The address of a label always has type 'void*'. 9459 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 9460 Context.getPointerType(Context.VoidTy))); 9461} 9462 9463/// Given the last statement in a statement-expression, check whether 9464/// the result is a producing expression (like a call to an 9465/// ns_returns_retained function) and, if so, rebuild it to hoist the 9466/// release out of the full-expression. Otherwise, return null. 9467/// Cannot fail. 9468static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 9469 // Should always be wrapped with one of these. 9470 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 9471 if (!cleanups) return 0; 9472 9473 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 9474 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 9475 return 0; 9476 9477 // Splice out the cast. This shouldn't modify any interesting 9478 // features of the statement. 9479 Expr *producer = cast->getSubExpr(); 9480 assert(producer->getType() == cast->getType()); 9481 assert(producer->getValueKind() == cast->getValueKind()); 9482 cleanups->setSubExpr(producer); 9483 return cleanups; 9484} 9485 9486void Sema::ActOnStartStmtExpr() { 9487 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 9488} 9489 9490void Sema::ActOnStmtExprError() { 9491 // Note that function is also called by TreeTransform when leaving a 9492 // StmtExpr scope without rebuilding anything. 9493 9494 DiscardCleanupsInEvaluationContext(); 9495 PopExpressionEvaluationContext(); 9496} 9497 9498ExprResult 9499Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 9500 SourceLocation RPLoc) { // "({..})" 9501 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 9502 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 9503 9504 if (hasAnyUnrecoverableErrorsInThisFunction()) 9505 DiscardCleanupsInEvaluationContext(); 9506 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 9507 PopExpressionEvaluationContext(); 9508 9509 bool isFileScope 9510 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0); 9511 if (isFileScope) 9512 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 9513 9514 // FIXME: there are a variety of strange constraints to enforce here, for 9515 // example, it is not possible to goto into a stmt expression apparently. 9516 // More semantic analysis is needed. 9517 9518 // If there are sub stmts in the compound stmt, take the type of the last one 9519 // as the type of the stmtexpr. 9520 QualType Ty = Context.VoidTy; 9521 bool StmtExprMayBindToTemp = false; 9522 if (!Compound->body_empty()) { 9523 Stmt *LastStmt = Compound->body_back(); 9524 LabelStmt *LastLabelStmt = 0; 9525 // If LastStmt is a label, skip down through into the body. 9526 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 9527 LastLabelStmt = Label; 9528 LastStmt = Label->getSubStmt(); 9529 } 9530 9531 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 9532 // Do function/array conversion on the last expression, but not 9533 // lvalue-to-rvalue. However, initialize an unqualified type. 9534 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 9535 if (LastExpr.isInvalid()) 9536 return ExprError(); 9537 Ty = LastExpr.get()->getType().getUnqualifiedType(); 9538 9539 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 9540 // In ARC, if the final expression ends in a consume, splice 9541 // the consume out and bind it later. In the alternate case 9542 // (when dealing with a retainable type), the result 9543 // initialization will create a produce. In both cases the 9544 // result will be +1, and we'll need to balance that out with 9545 // a bind. 9546 if (Expr *rebuiltLastStmt 9547 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 9548 LastExpr = rebuiltLastStmt; 9549 } else { 9550 LastExpr = PerformCopyInitialization( 9551 InitializedEntity::InitializeResult(LPLoc, 9552 Ty, 9553 false), 9554 SourceLocation(), 9555 LastExpr); 9556 } 9557 9558 if (LastExpr.isInvalid()) 9559 return ExprError(); 9560 if (LastExpr.get() != 0) { 9561 if (!LastLabelStmt) 9562 Compound->setLastStmt(LastExpr.take()); 9563 else 9564 LastLabelStmt->setSubStmt(LastExpr.take()); 9565 StmtExprMayBindToTemp = true; 9566 } 9567 } 9568 } 9569 } 9570 9571 // FIXME: Check that expression type is complete/non-abstract; statement 9572 // expressions are not lvalues. 9573 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 9574 if (StmtExprMayBindToTemp) 9575 return MaybeBindToTemporary(ResStmtExpr); 9576 return Owned(ResStmtExpr); 9577} 9578 9579ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 9580 TypeSourceInfo *TInfo, 9581 OffsetOfComponent *CompPtr, 9582 unsigned NumComponents, 9583 SourceLocation RParenLoc) { 9584 QualType ArgTy = TInfo->getType(); 9585 bool Dependent = ArgTy->isDependentType(); 9586 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 9587 9588 // We must have at least one component that refers to the type, and the first 9589 // one is known to be a field designator. Verify that the ArgTy represents 9590 // a struct/union/class. 9591 if (!Dependent && !ArgTy->isRecordType()) 9592 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 9593 << ArgTy << TypeRange); 9594 9595 // Type must be complete per C99 7.17p3 because a declaring a variable 9596 // with an incomplete type would be ill-formed. 9597 if (!Dependent 9598 && RequireCompleteType(BuiltinLoc, ArgTy, 9599 diag::err_offsetof_incomplete_type, TypeRange)) 9600 return ExprError(); 9601 9602 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 9603 // GCC extension, diagnose them. 9604 // FIXME: This diagnostic isn't actually visible because the location is in 9605 // a system header! 9606 if (NumComponents != 1) 9607 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 9608 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 9609 9610 bool DidWarnAboutNonPOD = false; 9611 QualType CurrentType = ArgTy; 9612 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 9613 SmallVector<OffsetOfNode, 4> Comps; 9614 SmallVector<Expr*, 4> Exprs; 9615 for (unsigned i = 0; i != NumComponents; ++i) { 9616 const OffsetOfComponent &OC = CompPtr[i]; 9617 if (OC.isBrackets) { 9618 // Offset of an array sub-field. TODO: Should we allow vector elements? 9619 if (!CurrentType->isDependentType()) { 9620 const ArrayType *AT = Context.getAsArrayType(CurrentType); 9621 if(!AT) 9622 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 9623 << CurrentType); 9624 CurrentType = AT->getElementType(); 9625 } else 9626 CurrentType = Context.DependentTy; 9627 9628 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 9629 if (IdxRval.isInvalid()) 9630 return ExprError(); 9631 Expr *Idx = IdxRval.take(); 9632 9633 // The expression must be an integral expression. 9634 // FIXME: An integral constant expression? 9635 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 9636 !Idx->getType()->isIntegerType()) 9637 return ExprError(Diag(Idx->getLocStart(), 9638 diag::err_typecheck_subscript_not_integer) 9639 << Idx->getSourceRange()); 9640 9641 // Record this array index. 9642 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 9643 Exprs.push_back(Idx); 9644 continue; 9645 } 9646 9647 // Offset of a field. 9648 if (CurrentType->isDependentType()) { 9649 // We have the offset of a field, but we can't look into the dependent 9650 // type. Just record the identifier of the field. 9651 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 9652 CurrentType = Context.DependentTy; 9653 continue; 9654 } 9655 9656 // We need to have a complete type to look into. 9657 if (RequireCompleteType(OC.LocStart, CurrentType, 9658 diag::err_offsetof_incomplete_type)) 9659 return ExprError(); 9660 9661 // Look for the designated field. 9662 const RecordType *RC = CurrentType->getAs<RecordType>(); 9663 if (!RC) 9664 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 9665 << CurrentType); 9666 RecordDecl *RD = RC->getDecl(); 9667 9668 // C++ [lib.support.types]p5: 9669 // The macro offsetof accepts a restricted set of type arguments in this 9670 // International Standard. type shall be a POD structure or a POD union 9671 // (clause 9). 9672 // C++11 [support.types]p4: 9673 // If type is not a standard-layout class (Clause 9), the results are 9674 // undefined. 9675 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 9676 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 9677 unsigned DiagID = 9678 LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type 9679 : diag::warn_offsetof_non_pod_type; 9680 9681 if (!IsSafe && !DidWarnAboutNonPOD && 9682 DiagRuntimeBehavior(BuiltinLoc, 0, 9683 PDiag(DiagID) 9684 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 9685 << CurrentType)) 9686 DidWarnAboutNonPOD = true; 9687 } 9688 9689 // Look for the field. 9690 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 9691 LookupQualifiedName(R, RD); 9692 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 9693 IndirectFieldDecl *IndirectMemberDecl = 0; 9694 if (!MemberDecl) { 9695 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 9696 MemberDecl = IndirectMemberDecl->getAnonField(); 9697 } 9698 9699 if (!MemberDecl) 9700 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 9701 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 9702 OC.LocEnd)); 9703 9704 // C99 7.17p3: 9705 // (If the specified member is a bit-field, the behavior is undefined.) 9706 // 9707 // We diagnose this as an error. 9708 if (MemberDecl->isBitField()) { 9709 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 9710 << MemberDecl->getDeclName() 9711 << SourceRange(BuiltinLoc, RParenLoc); 9712 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 9713 return ExprError(); 9714 } 9715 9716 RecordDecl *Parent = MemberDecl->getParent(); 9717 if (IndirectMemberDecl) 9718 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 9719 9720 // If the member was found in a base class, introduce OffsetOfNodes for 9721 // the base class indirections. 9722 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 9723 /*DetectVirtual=*/false); 9724 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 9725 CXXBasePath &Path = Paths.front(); 9726 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 9727 B != BEnd; ++B) 9728 Comps.push_back(OffsetOfNode(B->Base)); 9729 } 9730 9731 if (IndirectMemberDecl) { 9732 for (IndirectFieldDecl::chain_iterator FI = 9733 IndirectMemberDecl->chain_begin(), 9734 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) { 9735 assert(isa<FieldDecl>(*FI)); 9736 Comps.push_back(OffsetOfNode(OC.LocStart, 9737 cast<FieldDecl>(*FI), OC.LocEnd)); 9738 } 9739 } else 9740 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 9741 9742 CurrentType = MemberDecl->getType().getNonReferenceType(); 9743 } 9744 9745 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 9746 TInfo, Comps, Exprs, RParenLoc)); 9747} 9748 9749ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 9750 SourceLocation BuiltinLoc, 9751 SourceLocation TypeLoc, 9752 ParsedType ParsedArgTy, 9753 OffsetOfComponent *CompPtr, 9754 unsigned NumComponents, 9755 SourceLocation RParenLoc) { 9756 9757 TypeSourceInfo *ArgTInfo; 9758 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 9759 if (ArgTy.isNull()) 9760 return ExprError(); 9761 9762 if (!ArgTInfo) 9763 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 9764 9765 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 9766 RParenLoc); 9767} 9768 9769 9770ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 9771 Expr *CondExpr, 9772 Expr *LHSExpr, Expr *RHSExpr, 9773 SourceLocation RPLoc) { 9774 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 9775 9776 ExprValueKind VK = VK_RValue; 9777 ExprObjectKind OK = OK_Ordinary; 9778 QualType resType; 9779 bool ValueDependent = false; 9780 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 9781 resType = Context.DependentTy; 9782 ValueDependent = true; 9783 } else { 9784 // The conditional expression is required to be a constant expression. 9785 llvm::APSInt condEval(32); 9786 ExprResult CondICE 9787 = VerifyIntegerConstantExpression(CondExpr, &condEval, 9788 diag::err_typecheck_choose_expr_requires_constant, false); 9789 if (CondICE.isInvalid()) 9790 return ExprError(); 9791 CondExpr = CondICE.take(); 9792 9793 // If the condition is > zero, then the AST type is the same as the LSHExpr. 9794 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr; 9795 9796 resType = ActiveExpr->getType(); 9797 ValueDependent = ActiveExpr->isValueDependent(); 9798 VK = ActiveExpr->getValueKind(); 9799 OK = ActiveExpr->getObjectKind(); 9800 } 9801 9802 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 9803 resType, VK, OK, RPLoc, 9804 resType->isDependentType(), 9805 ValueDependent)); 9806} 9807 9808//===----------------------------------------------------------------------===// 9809// Clang Extensions. 9810//===----------------------------------------------------------------------===// 9811 9812/// ActOnBlockStart - This callback is invoked when a block literal is started. 9813void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 9814 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 9815 9816 { 9817 Decl *ManglingContextDecl; 9818 if (MangleNumberingContext *MCtx = 9819 getCurrentMangleNumberContext(Block->getDeclContext(), 9820 ManglingContextDecl)) { 9821 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 9822 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 9823 } 9824 } 9825 9826 PushBlockScope(CurScope, Block); 9827 CurContext->addDecl(Block); 9828 if (CurScope) 9829 PushDeclContext(CurScope, Block); 9830 else 9831 CurContext = Block; 9832 9833 getCurBlock()->HasImplicitReturnType = true; 9834 9835 // Enter a new evaluation context to insulate the block from any 9836 // cleanups from the enclosing full-expression. 9837 PushExpressionEvaluationContext(PotentiallyEvaluated); 9838} 9839 9840void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 9841 Scope *CurScope) { 9842 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!"); 9843 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 9844 BlockScopeInfo *CurBlock = getCurBlock(); 9845 9846 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 9847 QualType T = Sig->getType(); 9848 9849 // FIXME: We should allow unexpanded parameter packs here, but that would, 9850 // in turn, make the block expression contain unexpanded parameter packs. 9851 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 9852 // Drop the parameters. 9853 FunctionProtoType::ExtProtoInfo EPI; 9854 EPI.HasTrailingReturn = false; 9855 EPI.TypeQuals |= DeclSpec::TQ_const; 9856 T = Context.getFunctionType(Context.DependentTy, None, EPI); 9857 Sig = Context.getTrivialTypeSourceInfo(T); 9858 } 9859 9860 // GetTypeForDeclarator always produces a function type for a block 9861 // literal signature. Furthermore, it is always a FunctionProtoType 9862 // unless the function was written with a typedef. 9863 assert(T->isFunctionType() && 9864 "GetTypeForDeclarator made a non-function block signature"); 9865 9866 // Look for an explicit signature in that function type. 9867 FunctionProtoTypeLoc ExplicitSignature; 9868 9869 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 9870 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 9871 9872 // Check whether that explicit signature was synthesized by 9873 // GetTypeForDeclarator. If so, don't save that as part of the 9874 // written signature. 9875 if (ExplicitSignature.getLocalRangeBegin() == 9876 ExplicitSignature.getLocalRangeEnd()) { 9877 // This would be much cheaper if we stored TypeLocs instead of 9878 // TypeSourceInfos. 9879 TypeLoc Result = ExplicitSignature.getResultLoc(); 9880 unsigned Size = Result.getFullDataSize(); 9881 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 9882 Sig->getTypeLoc().initializeFullCopy(Result, Size); 9883 9884 ExplicitSignature = FunctionProtoTypeLoc(); 9885 } 9886 } 9887 9888 CurBlock->TheDecl->setSignatureAsWritten(Sig); 9889 CurBlock->FunctionType = T; 9890 9891 const FunctionType *Fn = T->getAs<FunctionType>(); 9892 QualType RetTy = Fn->getResultType(); 9893 bool isVariadic = 9894 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 9895 9896 CurBlock->TheDecl->setIsVariadic(isVariadic); 9897 9898 // Context.DependentTy is used as a placeholder for a missing block 9899 // return type. TODO: what should we do with declarators like: 9900 // ^ * { ... } 9901 // If the answer is "apply template argument deduction".... 9902 if (RetTy != Context.DependentTy) { 9903 CurBlock->ReturnType = RetTy; 9904 CurBlock->TheDecl->setBlockMissingReturnType(false); 9905 CurBlock->HasImplicitReturnType = false; 9906 } 9907 9908 // Push block parameters from the declarator if we had them. 9909 SmallVector<ParmVarDecl*, 8> Params; 9910 if (ExplicitSignature) { 9911 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) { 9912 ParmVarDecl *Param = ExplicitSignature.getArg(I); 9913 if (Param->getIdentifier() == 0 && 9914 !Param->isImplicit() && 9915 !Param->isInvalidDecl() && 9916 !getLangOpts().CPlusPlus) 9917 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 9918 Params.push_back(Param); 9919 } 9920 9921 // Fake up parameter variables if we have a typedef, like 9922 // ^ fntype { ... } 9923 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 9924 for (FunctionProtoType::arg_type_iterator 9925 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) { 9926 ParmVarDecl *Param = 9927 BuildParmVarDeclForTypedef(CurBlock->TheDecl, 9928 ParamInfo.getLocStart(), 9929 *I); 9930 Params.push_back(Param); 9931 } 9932 } 9933 9934 // Set the parameters on the block decl. 9935 if (!Params.empty()) { 9936 CurBlock->TheDecl->setParams(Params); 9937 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 9938 CurBlock->TheDecl->param_end(), 9939 /*CheckParameterNames=*/false); 9940 } 9941 9942 // Finally we can process decl attributes. 9943 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 9944 9945 // Put the parameter variables in scope. 9946 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(), 9947 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) { 9948 (*AI)->setOwningFunction(CurBlock->TheDecl); 9949 9950 // If this has an identifier, add it to the scope stack. 9951 if ((*AI)->getIdentifier()) { 9952 CheckShadow(CurBlock->TheScope, *AI); 9953 9954 PushOnScopeChains(*AI, CurBlock->TheScope); 9955 } 9956 } 9957} 9958 9959/// ActOnBlockError - If there is an error parsing a block, this callback 9960/// is invoked to pop the information about the block from the action impl. 9961void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 9962 // Leave the expression-evaluation context. 9963 DiscardCleanupsInEvaluationContext(); 9964 PopExpressionEvaluationContext(); 9965 9966 // Pop off CurBlock, handle nested blocks. 9967 PopDeclContext(); 9968 PopFunctionScopeInfo(); 9969} 9970 9971/// ActOnBlockStmtExpr - This is called when the body of a block statement 9972/// literal was successfully completed. ^(int x){...} 9973ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 9974 Stmt *Body, Scope *CurScope) { 9975 // If blocks are disabled, emit an error. 9976 if (!LangOpts.Blocks) 9977 Diag(CaretLoc, diag::err_blocks_disable); 9978 9979 // Leave the expression-evaluation context. 9980 if (hasAnyUnrecoverableErrorsInThisFunction()) 9981 DiscardCleanupsInEvaluationContext(); 9982 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 9983 PopExpressionEvaluationContext(); 9984 9985 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 9986 9987 if (BSI->HasImplicitReturnType) 9988 deduceClosureReturnType(*BSI); 9989 9990 PopDeclContext(); 9991 9992 QualType RetTy = Context.VoidTy; 9993 if (!BSI->ReturnType.isNull()) 9994 RetTy = BSI->ReturnType; 9995 9996 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>(); 9997 QualType BlockTy; 9998 9999 // Set the captured variables on the block. 10000 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 10001 SmallVector<BlockDecl::Capture, 4> Captures; 10002 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) { 10003 CapturingScopeInfo::Capture &Cap = BSI->Captures[i]; 10004 if (Cap.isThisCapture()) 10005 continue; 10006 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 10007 Cap.isNested(), Cap.getInitExpr()); 10008 Captures.push_back(NewCap); 10009 } 10010 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(), 10011 BSI->CXXThisCaptureIndex != 0); 10012 10013 // If the user wrote a function type in some form, try to use that. 10014 if (!BSI->FunctionType.isNull()) { 10015 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 10016 10017 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 10018 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 10019 10020 // Turn protoless block types into nullary block types. 10021 if (isa<FunctionNoProtoType>(FTy)) { 10022 FunctionProtoType::ExtProtoInfo EPI; 10023 EPI.ExtInfo = Ext; 10024 BlockTy = Context.getFunctionType(RetTy, None, EPI); 10025 10026 // Otherwise, if we don't need to change anything about the function type, 10027 // preserve its sugar structure. 10028 } else if (FTy->getResultType() == RetTy && 10029 (!NoReturn || FTy->getNoReturnAttr())) { 10030 BlockTy = BSI->FunctionType; 10031 10032 // Otherwise, make the minimal modifications to the function type. 10033 } else { 10034 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 10035 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10036 EPI.TypeQuals = 0; // FIXME: silently? 10037 EPI.ExtInfo = Ext; 10038 BlockTy = Context.getFunctionType(RetTy, FPT->getArgTypes(), EPI); 10039 } 10040 10041 // If we don't have a function type, just build one from nothing. 10042 } else { 10043 FunctionProtoType::ExtProtoInfo EPI; 10044 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 10045 BlockTy = Context.getFunctionType(RetTy, None, EPI); 10046 } 10047 10048 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 10049 BSI->TheDecl->param_end()); 10050 BlockTy = Context.getBlockPointerType(BlockTy); 10051 10052 // If needed, diagnose invalid gotos and switches in the block. 10053 if (getCurFunction()->NeedsScopeChecking() && 10054 !hasAnyUnrecoverableErrorsInThisFunction() && 10055 !PP.isCodeCompletionEnabled()) 10056 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 10057 10058 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 10059 10060 // Try to apply the named return value optimization. We have to check again 10061 // if we can do this, though, because blocks keep return statements around 10062 // to deduce an implicit return type. 10063 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 10064 !BSI->TheDecl->isDependentContext()) 10065 computeNRVO(Body, getCurBlock()); 10066 10067 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 10068 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy(); 10069 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 10070 10071 // If the block isn't obviously global, i.e. it captures anything at 10072 // all, then we need to do a few things in the surrounding context: 10073 if (Result->getBlockDecl()->hasCaptures()) { 10074 // First, this expression has a new cleanup object. 10075 ExprCleanupObjects.push_back(Result->getBlockDecl()); 10076 ExprNeedsCleanups = true; 10077 10078 // It also gets a branch-protected scope if any of the captured 10079 // variables needs destruction. 10080 for (BlockDecl::capture_const_iterator 10081 ci = Result->getBlockDecl()->capture_begin(), 10082 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) { 10083 const VarDecl *var = ci->getVariable(); 10084 if (var->getType().isDestructedType() != QualType::DK_none) { 10085 getCurFunction()->setHasBranchProtectedScope(); 10086 break; 10087 } 10088 } 10089 } 10090 10091 return Owned(Result); 10092} 10093 10094ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 10095 Expr *E, ParsedType Ty, 10096 SourceLocation RPLoc) { 10097 TypeSourceInfo *TInfo; 10098 GetTypeFromParser(Ty, &TInfo); 10099 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 10100} 10101 10102ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 10103 Expr *E, TypeSourceInfo *TInfo, 10104 SourceLocation RPLoc) { 10105 Expr *OrigExpr = E; 10106 10107 // Get the va_list type 10108 QualType VaListType = Context.getBuiltinVaListType(); 10109 if (VaListType->isArrayType()) { 10110 // Deal with implicit array decay; for example, on x86-64, 10111 // va_list is an array, but it's supposed to decay to 10112 // a pointer for va_arg. 10113 VaListType = Context.getArrayDecayedType(VaListType); 10114 // Make sure the input expression also decays appropriately. 10115 ExprResult Result = UsualUnaryConversions(E); 10116 if (Result.isInvalid()) 10117 return ExprError(); 10118 E = Result.take(); 10119 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 10120 // If va_list is a record type and we are compiling in C++ mode, 10121 // check the argument using reference binding. 10122 InitializedEntity Entity 10123 = InitializedEntity::InitializeParameter(Context, 10124 Context.getLValueReferenceType(VaListType), false); 10125 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 10126 if (Init.isInvalid()) 10127 return ExprError(); 10128 E = Init.takeAs<Expr>(); 10129 } else { 10130 // Otherwise, the va_list argument must be an l-value because 10131 // it is modified by va_arg. 10132 if (!E->isTypeDependent() && 10133 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 10134 return ExprError(); 10135 } 10136 10137 if (!E->isTypeDependent() && 10138 !Context.hasSameType(VaListType, E->getType())) { 10139 return ExprError(Diag(E->getLocStart(), 10140 diag::err_first_argument_to_va_arg_not_of_type_va_list) 10141 << OrigExpr->getType() << E->getSourceRange()); 10142 } 10143 10144 if (!TInfo->getType()->isDependentType()) { 10145 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 10146 diag::err_second_parameter_to_va_arg_incomplete, 10147 TInfo->getTypeLoc())) 10148 return ExprError(); 10149 10150 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 10151 TInfo->getType(), 10152 diag::err_second_parameter_to_va_arg_abstract, 10153 TInfo->getTypeLoc())) 10154 return ExprError(); 10155 10156 if (!TInfo->getType().isPODType(Context)) { 10157 Diag(TInfo->getTypeLoc().getBeginLoc(), 10158 TInfo->getType()->isObjCLifetimeType() 10159 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 10160 : diag::warn_second_parameter_to_va_arg_not_pod) 10161 << TInfo->getType() 10162 << TInfo->getTypeLoc().getSourceRange(); 10163 } 10164 10165 // Check for va_arg where arguments of the given type will be promoted 10166 // (i.e. this va_arg is guaranteed to have undefined behavior). 10167 QualType PromoteType; 10168 if (TInfo->getType()->isPromotableIntegerType()) { 10169 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 10170 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 10171 PromoteType = QualType(); 10172 } 10173 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 10174 PromoteType = Context.DoubleTy; 10175 if (!PromoteType.isNull()) 10176 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 10177 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 10178 << TInfo->getType() 10179 << PromoteType 10180 << TInfo->getTypeLoc().getSourceRange()); 10181 } 10182 10183 QualType T = TInfo->getType().getNonLValueExprType(Context); 10184 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T)); 10185} 10186 10187ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 10188 // The type of __null will be int or long, depending on the size of 10189 // pointers on the target. 10190 QualType Ty; 10191 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 10192 if (pw == Context.getTargetInfo().getIntWidth()) 10193 Ty = Context.IntTy; 10194 else if (pw == Context.getTargetInfo().getLongWidth()) 10195 Ty = Context.LongTy; 10196 else if (pw == Context.getTargetInfo().getLongLongWidth()) 10197 Ty = Context.LongLongTy; 10198 else { 10199 llvm_unreachable("I don't know size of pointer!"); 10200 } 10201 10202 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); 10203} 10204 10205static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType, 10206 Expr *SrcExpr, FixItHint &Hint, 10207 bool &IsNSString) { 10208 if (!SemaRef.getLangOpts().ObjC1) 10209 return; 10210 10211 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 10212 if (!PT) 10213 return; 10214 10215 // Check if the destination is of type 'id'. 10216 if (!PT->isObjCIdType()) { 10217 // Check if the destination is the 'NSString' interface. 10218 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 10219 if (!ID || !ID->getIdentifier()->isStr("NSString")) 10220 return; 10221 IsNSString = true; 10222 } 10223 10224 // Ignore any parens, implicit casts (should only be 10225 // array-to-pointer decays), and not-so-opaque values. The last is 10226 // important for making this trigger for property assignments. 10227 SrcExpr = SrcExpr->IgnoreParenImpCasts(); 10228 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 10229 if (OV->getSourceExpr()) 10230 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 10231 10232 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 10233 if (!SL || !SL->isAscii()) 10234 return; 10235 10236 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@"); 10237} 10238 10239bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 10240 SourceLocation Loc, 10241 QualType DstType, QualType SrcType, 10242 Expr *SrcExpr, AssignmentAction Action, 10243 bool *Complained) { 10244 if (Complained) 10245 *Complained = false; 10246 10247 // Decode the result (notice that AST's are still created for extensions). 10248 bool CheckInferredResultType = false; 10249 bool isInvalid = false; 10250 unsigned DiagKind = 0; 10251 FixItHint Hint; 10252 ConversionFixItGenerator ConvHints; 10253 bool MayHaveConvFixit = false; 10254 bool MayHaveFunctionDiff = false; 10255 bool IsNSString = false; 10256 10257 switch (ConvTy) { 10258 case Compatible: 10259 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 10260 return false; 10261 10262 case PointerToInt: 10263 DiagKind = diag::ext_typecheck_convert_pointer_int; 10264 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10265 MayHaveConvFixit = true; 10266 break; 10267 case IntToPointer: 10268 DiagKind = diag::ext_typecheck_convert_int_pointer; 10269 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10270 MayHaveConvFixit = true; 10271 break; 10272 case IncompatiblePointer: 10273 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint, IsNSString); 10274 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 10275 CheckInferredResultType = DstType->isObjCObjectPointerType() && 10276 SrcType->isObjCObjectPointerType(); 10277 if (Hint.isNull() && !CheckInferredResultType) { 10278 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10279 } 10280 else if (CheckInferredResultType) { 10281 SrcType = SrcType.getUnqualifiedType(); 10282 DstType = DstType.getUnqualifiedType(); 10283 } 10284 else if (IsNSString && !Hint.isNull()) 10285 DiagKind = diag::warn_missing_atsign_prefix; 10286 MayHaveConvFixit = true; 10287 break; 10288 case IncompatiblePointerSign: 10289 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 10290 break; 10291 case FunctionVoidPointer: 10292 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 10293 break; 10294 case IncompatiblePointerDiscardsQualifiers: { 10295 // Perform array-to-pointer decay if necessary. 10296 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 10297 10298 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 10299 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 10300 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 10301 DiagKind = diag::err_typecheck_incompatible_address_space; 10302 break; 10303 10304 10305 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 10306 DiagKind = diag::err_typecheck_incompatible_ownership; 10307 break; 10308 } 10309 10310 llvm_unreachable("unknown error case for discarding qualifiers!"); 10311 // fallthrough 10312 } 10313 case CompatiblePointerDiscardsQualifiers: 10314 // If the qualifiers lost were because we were applying the 10315 // (deprecated) C++ conversion from a string literal to a char* 10316 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 10317 // Ideally, this check would be performed in 10318 // checkPointerTypesForAssignment. However, that would require a 10319 // bit of refactoring (so that the second argument is an 10320 // expression, rather than a type), which should be done as part 10321 // of a larger effort to fix checkPointerTypesForAssignment for 10322 // C++ semantics. 10323 if (getLangOpts().CPlusPlus && 10324 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 10325 return false; 10326 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 10327 break; 10328 case IncompatibleNestedPointerQualifiers: 10329 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 10330 break; 10331 case IntToBlockPointer: 10332 DiagKind = diag::err_int_to_block_pointer; 10333 break; 10334 case IncompatibleBlockPointer: 10335 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 10336 break; 10337 case IncompatibleObjCQualifiedId: 10338 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 10339 // it can give a more specific diagnostic. 10340 DiagKind = diag::warn_incompatible_qualified_id; 10341 break; 10342 case IncompatibleVectors: 10343 DiagKind = diag::warn_incompatible_vectors; 10344 break; 10345 case IncompatibleObjCWeakRef: 10346 DiagKind = diag::err_arc_weak_unavailable_assign; 10347 break; 10348 case Incompatible: 10349 DiagKind = diag::err_typecheck_convert_incompatible; 10350 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10351 MayHaveConvFixit = true; 10352 isInvalid = true; 10353 MayHaveFunctionDiff = true; 10354 break; 10355 } 10356 10357 QualType FirstType, SecondType; 10358 switch (Action) { 10359 case AA_Assigning: 10360 case AA_Initializing: 10361 // The destination type comes first. 10362 FirstType = DstType; 10363 SecondType = SrcType; 10364 break; 10365 10366 case AA_Returning: 10367 case AA_Passing: 10368 case AA_Converting: 10369 case AA_Sending: 10370 case AA_Casting: 10371 // The source type comes first. 10372 FirstType = SrcType; 10373 SecondType = DstType; 10374 break; 10375 } 10376 10377 PartialDiagnostic FDiag = PDiag(DiagKind); 10378 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 10379 10380 // If we can fix the conversion, suggest the FixIts. 10381 assert(ConvHints.isNull() || Hint.isNull()); 10382 if (!ConvHints.isNull()) { 10383 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(), 10384 HE = ConvHints.Hints.end(); HI != HE; ++HI) 10385 FDiag << *HI; 10386 } else { 10387 FDiag << Hint; 10388 } 10389 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 10390 10391 if (MayHaveFunctionDiff) 10392 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 10393 10394 Diag(Loc, FDiag); 10395 10396 if (SecondType == Context.OverloadTy) 10397 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 10398 FirstType); 10399 10400 if (CheckInferredResultType) 10401 EmitRelatedResultTypeNote(SrcExpr); 10402 10403 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 10404 EmitRelatedResultTypeNoteForReturn(DstType); 10405 10406 if (Complained) 10407 *Complained = true; 10408 return isInvalid; 10409} 10410 10411ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 10412 llvm::APSInt *Result) { 10413 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 10414 public: 10415 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 10416 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 10417 } 10418 } Diagnoser; 10419 10420 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 10421} 10422 10423ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 10424 llvm::APSInt *Result, 10425 unsigned DiagID, 10426 bool AllowFold) { 10427 class IDDiagnoser : public VerifyICEDiagnoser { 10428 unsigned DiagID; 10429 10430 public: 10431 IDDiagnoser(unsigned DiagID) 10432 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 10433 10434 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 10435 S.Diag(Loc, DiagID) << SR; 10436 } 10437 } Diagnoser(DiagID); 10438 10439 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 10440} 10441 10442void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 10443 SourceRange SR) { 10444 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 10445} 10446 10447ExprResult 10448Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 10449 VerifyICEDiagnoser &Diagnoser, 10450 bool AllowFold) { 10451 SourceLocation DiagLoc = E->getLocStart(); 10452 10453 if (getLangOpts().CPlusPlus11) { 10454 // C++11 [expr.const]p5: 10455 // If an expression of literal class type is used in a context where an 10456 // integral constant expression is required, then that class type shall 10457 // have a single non-explicit conversion function to an integral or 10458 // unscoped enumeration type 10459 ExprResult Converted; 10460 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 10461 public: 10462 CXX11ConvertDiagnoser(bool Silent) 10463 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 10464 Silent, true) {} 10465 10466 virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 10467 QualType T) { 10468 return S.Diag(Loc, diag::err_ice_not_integral) << T; 10469 } 10470 10471 virtual SemaDiagnosticBuilder diagnoseIncomplete( 10472 Sema &S, SourceLocation Loc, QualType T) { 10473 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 10474 } 10475 10476 virtual SemaDiagnosticBuilder diagnoseExplicitConv( 10477 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) { 10478 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 10479 } 10480 10481 virtual SemaDiagnosticBuilder noteExplicitConv( 10482 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) { 10483 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10484 << ConvTy->isEnumeralType() << ConvTy; 10485 } 10486 10487 virtual SemaDiagnosticBuilder diagnoseAmbiguous( 10488 Sema &S, SourceLocation Loc, QualType T) { 10489 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 10490 } 10491 10492 virtual SemaDiagnosticBuilder noteAmbiguous( 10493 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) { 10494 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10495 << ConvTy->isEnumeralType() << ConvTy; 10496 } 10497 10498 virtual SemaDiagnosticBuilder diagnoseConversion( 10499 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) { 10500 llvm_unreachable("conversion functions are permitted"); 10501 } 10502 } ConvertDiagnoser(Diagnoser.Suppress); 10503 10504 Converted = PerformContextualImplicitConversion(DiagLoc, E, 10505 ConvertDiagnoser); 10506 if (Converted.isInvalid()) 10507 return Converted; 10508 E = Converted.take(); 10509 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 10510 return ExprError(); 10511 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 10512 // An ICE must be of integral or unscoped enumeration type. 10513 if (!Diagnoser.Suppress) 10514 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 10515 return ExprError(); 10516 } 10517 10518 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 10519 // in the non-ICE case. 10520 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 10521 if (Result) 10522 *Result = E->EvaluateKnownConstInt(Context); 10523 return Owned(E); 10524 } 10525 10526 Expr::EvalResult EvalResult; 10527 SmallVector<PartialDiagnosticAt, 8> Notes; 10528 EvalResult.Diag = &Notes; 10529 10530 // Try to evaluate the expression, and produce diagnostics explaining why it's 10531 // not a constant expression as a side-effect. 10532 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 10533 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 10534 10535 // In C++11, we can rely on diagnostics being produced for any expression 10536 // which is not a constant expression. If no diagnostics were produced, then 10537 // this is a constant expression. 10538 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 10539 if (Result) 10540 *Result = EvalResult.Val.getInt(); 10541 return Owned(E); 10542 } 10543 10544 // If our only note is the usual "invalid subexpression" note, just point 10545 // the caret at its location rather than producing an essentially 10546 // redundant note. 10547 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 10548 diag::note_invalid_subexpr_in_const_expr) { 10549 DiagLoc = Notes[0].first; 10550 Notes.clear(); 10551 } 10552 10553 if (!Folded || !AllowFold) { 10554 if (!Diagnoser.Suppress) { 10555 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 10556 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10557 Diag(Notes[I].first, Notes[I].second); 10558 } 10559 10560 return ExprError(); 10561 } 10562 10563 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 10564 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10565 Diag(Notes[I].first, Notes[I].second); 10566 10567 if (Result) 10568 *Result = EvalResult.Val.getInt(); 10569 return Owned(E); 10570} 10571 10572namespace { 10573 // Handle the case where we conclude a expression which we speculatively 10574 // considered to be unevaluated is actually evaluated. 10575 class TransformToPE : public TreeTransform<TransformToPE> { 10576 typedef TreeTransform<TransformToPE> BaseTransform; 10577 10578 public: 10579 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 10580 10581 // Make sure we redo semantic analysis 10582 bool AlwaysRebuild() { return true; } 10583 10584 // Make sure we handle LabelStmts correctly. 10585 // FIXME: This does the right thing, but maybe we need a more general 10586 // fix to TreeTransform? 10587 StmtResult TransformLabelStmt(LabelStmt *S) { 10588 S->getDecl()->setStmt(0); 10589 return BaseTransform::TransformLabelStmt(S); 10590 } 10591 10592 // We need to special-case DeclRefExprs referring to FieldDecls which 10593 // are not part of a member pointer formation; normal TreeTransforming 10594 // doesn't catch this case because of the way we represent them in the AST. 10595 // FIXME: This is a bit ugly; is it really the best way to handle this 10596 // case? 10597 // 10598 // Error on DeclRefExprs referring to FieldDecls. 10599 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 10600 if (isa<FieldDecl>(E->getDecl()) && 10601 !SemaRef.isUnevaluatedContext()) 10602 return SemaRef.Diag(E->getLocation(), 10603 diag::err_invalid_non_static_member_use) 10604 << E->getDecl() << E->getSourceRange(); 10605 10606 return BaseTransform::TransformDeclRefExpr(E); 10607 } 10608 10609 // Exception: filter out member pointer formation 10610 ExprResult TransformUnaryOperator(UnaryOperator *E) { 10611 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 10612 return E; 10613 10614 return BaseTransform::TransformUnaryOperator(E); 10615 } 10616 10617 ExprResult TransformLambdaExpr(LambdaExpr *E) { 10618 // Lambdas never need to be transformed. 10619 return E; 10620 } 10621 }; 10622} 10623 10624ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 10625 assert(isUnevaluatedContext() && 10626 "Should only transform unevaluated expressions"); 10627 ExprEvalContexts.back().Context = 10628 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 10629 if (isUnevaluatedContext()) 10630 return E; 10631 return TransformToPE(*this).TransformExpr(E); 10632} 10633 10634void 10635Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 10636 Decl *LambdaContextDecl, 10637 bool IsDecltype) { 10638 ExprEvalContexts.push_back( 10639 ExpressionEvaluationContextRecord(NewContext, 10640 ExprCleanupObjects.size(), 10641 ExprNeedsCleanups, 10642 LambdaContextDecl, 10643 IsDecltype)); 10644 ExprNeedsCleanups = false; 10645 if (!MaybeODRUseExprs.empty()) 10646 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 10647} 10648 10649void 10650Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 10651 ReuseLambdaContextDecl_t, 10652 bool IsDecltype) { 10653 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 10654 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 10655} 10656 10657void Sema::PopExpressionEvaluationContext() { 10658 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 10659 10660 if (!Rec.Lambdas.empty()) { 10661 if (Rec.isUnevaluated()) { 10662 // C++11 [expr.prim.lambda]p2: 10663 // A lambda-expression shall not appear in an unevaluated operand 10664 // (Clause 5). 10665 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) 10666 Diag(Rec.Lambdas[I]->getLocStart(), 10667 diag::err_lambda_unevaluated_operand); 10668 } else { 10669 // Mark the capture expressions odr-used. This was deferred 10670 // during lambda expression creation. 10671 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) { 10672 LambdaExpr *Lambda = Rec.Lambdas[I]; 10673 for (LambdaExpr::capture_init_iterator 10674 C = Lambda->capture_init_begin(), 10675 CEnd = Lambda->capture_init_end(); 10676 C != CEnd; ++C) { 10677 MarkDeclarationsReferencedInExpr(*C); 10678 } 10679 } 10680 } 10681 } 10682 10683 // When are coming out of an unevaluated context, clear out any 10684 // temporaries that we may have created as part of the evaluation of 10685 // the expression in that context: they aren't relevant because they 10686 // will never be constructed. 10687 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 10688 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 10689 ExprCleanupObjects.end()); 10690 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 10691 CleanupVarDeclMarking(); 10692 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 10693 // Otherwise, merge the contexts together. 10694 } else { 10695 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 10696 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 10697 Rec.SavedMaybeODRUseExprs.end()); 10698 } 10699 10700 // Pop the current expression evaluation context off the stack. 10701 ExprEvalContexts.pop_back(); 10702} 10703 10704void Sema::DiscardCleanupsInEvaluationContext() { 10705 ExprCleanupObjects.erase( 10706 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 10707 ExprCleanupObjects.end()); 10708 ExprNeedsCleanups = false; 10709 MaybeODRUseExprs.clear(); 10710} 10711 10712ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 10713 if (!E->getType()->isVariablyModifiedType()) 10714 return E; 10715 return TransformToPotentiallyEvaluated(E); 10716} 10717 10718static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 10719 // Do not mark anything as "used" within a dependent context; wait for 10720 // an instantiation. 10721 if (SemaRef.CurContext->isDependentContext()) 10722 return false; 10723 10724 switch (SemaRef.ExprEvalContexts.back().Context) { 10725 case Sema::Unevaluated: 10726 case Sema::UnevaluatedAbstract: 10727 // We are in an expression that is not potentially evaluated; do nothing. 10728 // (Depending on how you read the standard, we actually do need to do 10729 // something here for null pointer constants, but the standard's 10730 // definition of a null pointer constant is completely crazy.) 10731 return false; 10732 10733 case Sema::ConstantEvaluated: 10734 case Sema::PotentiallyEvaluated: 10735 // We are in a potentially evaluated expression (or a constant-expression 10736 // in C++03); we need to do implicit template instantiation, implicitly 10737 // define class members, and mark most declarations as used. 10738 return true; 10739 10740 case Sema::PotentiallyEvaluatedIfUsed: 10741 // Referenced declarations will only be used if the construct in the 10742 // containing expression is used. 10743 return false; 10744 } 10745 llvm_unreachable("Invalid context"); 10746} 10747 10748/// \brief Mark a function referenced, and check whether it is odr-used 10749/// (C++ [basic.def.odr]p2, C99 6.9p3) 10750void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) { 10751 assert(Func && "No function?"); 10752 10753 Func->setReferenced(); 10754 10755 // C++11 [basic.def.odr]p3: 10756 // A function whose name appears as a potentially-evaluated expression is 10757 // odr-used if it is the unique lookup result or the selected member of a 10758 // set of overloaded functions [...]. 10759 // 10760 // We (incorrectly) mark overload resolution as an unevaluated context, so we 10761 // can just check that here. Skip the rest of this function if we've already 10762 // marked the function as used. 10763 if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) { 10764 // C++11 [temp.inst]p3: 10765 // Unless a function template specialization has been explicitly 10766 // instantiated or explicitly specialized, the function template 10767 // specialization is implicitly instantiated when the specialization is 10768 // referenced in a context that requires a function definition to exist. 10769 // 10770 // We consider constexpr function templates to be referenced in a context 10771 // that requires a definition to exist whenever they are referenced. 10772 // 10773 // FIXME: This instantiates constexpr functions too frequently. If this is 10774 // really an unevaluated context (and we're not just in the definition of a 10775 // function template or overload resolution or other cases which we 10776 // incorrectly consider to be unevaluated contexts), and we're not in a 10777 // subexpression which we actually need to evaluate (for instance, a 10778 // template argument, array bound or an expression in a braced-init-list), 10779 // we are not permitted to instantiate this constexpr function definition. 10780 // 10781 // FIXME: This also implicitly defines special members too frequently. They 10782 // are only supposed to be implicitly defined if they are odr-used, but they 10783 // are not odr-used from constant expressions in unevaluated contexts. 10784 // However, they cannot be referenced if they are deleted, and they are 10785 // deleted whenever the implicit definition of the special member would 10786 // fail. 10787 if (!Func->isConstexpr() || Func->getBody()) 10788 return; 10789 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 10790 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 10791 return; 10792 } 10793 10794 // Note that this declaration has been used. 10795 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 10796 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 10797 if (Constructor->isDefaultConstructor()) { 10798 if (Constructor->isTrivial()) 10799 return; 10800 if (!Constructor->isUsed(false)) 10801 DefineImplicitDefaultConstructor(Loc, Constructor); 10802 } else if (Constructor->isCopyConstructor()) { 10803 if (!Constructor->isUsed(false)) 10804 DefineImplicitCopyConstructor(Loc, Constructor); 10805 } else if (Constructor->isMoveConstructor()) { 10806 if (!Constructor->isUsed(false)) 10807 DefineImplicitMoveConstructor(Loc, Constructor); 10808 } 10809 } else if (Constructor->getInheritedConstructor()) { 10810 if (!Constructor->isUsed(false)) 10811 DefineInheritingConstructor(Loc, Constructor); 10812 } 10813 10814 MarkVTableUsed(Loc, Constructor->getParent()); 10815 } else if (CXXDestructorDecl *Destructor = 10816 dyn_cast<CXXDestructorDecl>(Func)) { 10817 if (Destructor->isDefaulted() && !Destructor->isDeleted() && 10818 !Destructor->isUsed(false)) 10819 DefineImplicitDestructor(Loc, Destructor); 10820 if (Destructor->isVirtual()) 10821 MarkVTableUsed(Loc, Destructor->getParent()); 10822 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 10823 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() && 10824 MethodDecl->isOverloadedOperator() && 10825 MethodDecl->getOverloadedOperator() == OO_Equal) { 10826 if (!MethodDecl->isUsed(false)) { 10827 if (MethodDecl->isCopyAssignmentOperator()) 10828 DefineImplicitCopyAssignment(Loc, MethodDecl); 10829 else 10830 DefineImplicitMoveAssignment(Loc, MethodDecl); 10831 } 10832 } else if (isa<CXXConversionDecl>(MethodDecl) && 10833 MethodDecl->getParent()->isLambda()) { 10834 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl); 10835 if (Conversion->isLambdaToBlockPointerConversion()) 10836 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 10837 else 10838 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 10839 } else if (MethodDecl->isVirtual()) 10840 MarkVTableUsed(Loc, MethodDecl->getParent()); 10841 } 10842 10843 // Recursive functions should be marked when used from another function. 10844 // FIXME: Is this really right? 10845 if (CurContext == Func) return; 10846 10847 // Resolve the exception specification for any function which is 10848 // used: CodeGen will need it. 10849 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 10850 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 10851 ResolveExceptionSpec(Loc, FPT); 10852 10853 // Implicit instantiation of function templates and member functions of 10854 // class templates. 10855 if (Func->isImplicitlyInstantiable()) { 10856 bool AlreadyInstantiated = false; 10857 SourceLocation PointOfInstantiation = Loc; 10858 if (FunctionTemplateSpecializationInfo *SpecInfo 10859 = Func->getTemplateSpecializationInfo()) { 10860 if (SpecInfo->getPointOfInstantiation().isInvalid()) 10861 SpecInfo->setPointOfInstantiation(Loc); 10862 else if (SpecInfo->getTemplateSpecializationKind() 10863 == TSK_ImplicitInstantiation) { 10864 AlreadyInstantiated = true; 10865 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 10866 } 10867 } else if (MemberSpecializationInfo *MSInfo 10868 = Func->getMemberSpecializationInfo()) { 10869 if (MSInfo->getPointOfInstantiation().isInvalid()) 10870 MSInfo->setPointOfInstantiation(Loc); 10871 else if (MSInfo->getTemplateSpecializationKind() 10872 == TSK_ImplicitInstantiation) { 10873 AlreadyInstantiated = true; 10874 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 10875 } 10876 } 10877 10878 if (!AlreadyInstantiated || Func->isConstexpr()) { 10879 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 10880 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 10881 ActiveTemplateInstantiations.size()) 10882 PendingLocalImplicitInstantiations.push_back( 10883 std::make_pair(Func, PointOfInstantiation)); 10884 else if (Func->isConstexpr()) 10885 // Do not defer instantiations of constexpr functions, to avoid the 10886 // expression evaluator needing to call back into Sema if it sees a 10887 // call to such a function. 10888 InstantiateFunctionDefinition(PointOfInstantiation, Func); 10889 else { 10890 PendingInstantiations.push_back(std::make_pair(Func, 10891 PointOfInstantiation)); 10892 // Notify the consumer that a function was implicitly instantiated. 10893 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 10894 } 10895 } 10896 } else { 10897 // Walk redefinitions, as some of them may be instantiable. 10898 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()), 10899 e(Func->redecls_end()); i != e; ++i) { 10900 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 10901 MarkFunctionReferenced(Loc, *i); 10902 } 10903 } 10904 10905 // Keep track of used but undefined functions. 10906 if (!Func->isDefined()) { 10907 if (mightHaveNonExternalLinkage(Func)) 10908 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 10909 else if (Func->getMostRecentDecl()->isInlined() && 10910 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 10911 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 10912 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 10913 } 10914 10915 // Normally the must current decl is marked used while processing the use and 10916 // any subsequent decls are marked used by decl merging. This fails with 10917 // template instantiation since marking can happen at the end of the file 10918 // and, because of the two phase lookup, this function is called with at 10919 // decl in the middle of a decl chain. We loop to maintain the invariant 10920 // that once a decl is used, all decls after it are also used. 10921 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) { 10922 F->setUsed(true); 10923 if (F == Func) 10924 break; 10925 } 10926} 10927 10928static void 10929diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 10930 VarDecl *var, DeclContext *DC) { 10931 DeclContext *VarDC = var->getDeclContext(); 10932 10933 // If the parameter still belongs to the translation unit, then 10934 // we're actually just using one parameter in the declaration of 10935 // the next. 10936 if (isa<ParmVarDecl>(var) && 10937 isa<TranslationUnitDecl>(VarDC)) 10938 return; 10939 10940 // For C code, don't diagnose about capture if we're not actually in code 10941 // right now; it's impossible to write a non-constant expression outside of 10942 // function context, so we'll get other (more useful) diagnostics later. 10943 // 10944 // For C++, things get a bit more nasty... it would be nice to suppress this 10945 // diagnostic for certain cases like using a local variable in an array bound 10946 // for a member of a local class, but the correct predicate is not obvious. 10947 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 10948 return; 10949 10950 if (isa<CXXMethodDecl>(VarDC) && 10951 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 10952 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 10953 << var->getIdentifier(); 10954 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 10955 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 10956 << var->getIdentifier() << fn->getDeclName(); 10957 } else if (isa<BlockDecl>(VarDC)) { 10958 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 10959 << var->getIdentifier(); 10960 } else { 10961 // FIXME: Is there any other context where a local variable can be 10962 // declared? 10963 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 10964 << var->getIdentifier(); 10965 } 10966 10967 S.Diag(var->getLocation(), diag::note_local_variable_declared_here) 10968 << var->getIdentifier(); 10969 10970 // FIXME: Add additional diagnostic info about class etc. which prevents 10971 // capture. 10972} 10973 10974/// \brief Capture the given variable in the captured region. 10975static ExprResult captureInCapturedRegion(Sema &S, CapturedRegionScopeInfo *RSI, 10976 VarDecl *Var, QualType FieldType, 10977 QualType DeclRefType, 10978 SourceLocation Loc, 10979 bool RefersToEnclosingLocal) { 10980 // The current implemention assumes that all variables are captured 10981 // by references. Since there is no capture by copy, no expression evaluation 10982 // will be needed. 10983 // 10984 RecordDecl *RD = RSI->TheRecordDecl; 10985 10986 FieldDecl *Field 10987 = FieldDecl::Create(S.Context, RD, Loc, Loc, 0, FieldType, 10988 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 10989 0, false, ICIS_NoInit); 10990 Field->setImplicit(true); 10991 Field->setAccess(AS_private); 10992 RD->addDecl(Field); 10993 10994 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 10995 DeclRefType, VK_LValue, Loc); 10996 Var->setReferenced(true); 10997 Var->setUsed(true); 10998 10999 return Ref; 11000} 11001 11002/// \brief Capture the given variable in the given lambda expression. 11003static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI, 11004 VarDecl *Var, QualType FieldType, 11005 QualType DeclRefType, 11006 SourceLocation Loc, 11007 bool RefersToEnclosingLocal) { 11008 CXXRecordDecl *Lambda = LSI->Lambda; 11009 11010 // Build the non-static data member. 11011 FieldDecl *Field 11012 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType, 11013 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 11014 0, false, ICIS_NoInit); 11015 Field->setImplicit(true); 11016 Field->setAccess(AS_private); 11017 Lambda->addDecl(Field); 11018 11019 // C++11 [expr.prim.lambda]p21: 11020 // When the lambda-expression is evaluated, the entities that 11021 // are captured by copy are used to direct-initialize each 11022 // corresponding non-static data member of the resulting closure 11023 // object. (For array members, the array elements are 11024 // direct-initialized in increasing subscript order.) These 11025 // initializations are performed in the (unspecified) order in 11026 // which the non-static data members are declared. 11027 11028 // Introduce a new evaluation context for the initialization, so 11029 // that temporaries introduced as part of the capture are retained 11030 // to be re-"exported" from the lambda expression itself. 11031 EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated); 11032 11033 // C++ [expr.prim.labda]p12: 11034 // An entity captured by a lambda-expression is odr-used (3.2) in 11035 // the scope containing the lambda-expression. 11036 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 11037 DeclRefType, VK_LValue, Loc); 11038 Var->setReferenced(true); 11039 Var->setUsed(true); 11040 11041 // When the field has array type, create index variables for each 11042 // dimension of the array. We use these index variables to subscript 11043 // the source array, and other clients (e.g., CodeGen) will perform 11044 // the necessary iteration with these index variables. 11045 SmallVector<VarDecl *, 4> IndexVariables; 11046 QualType BaseType = FieldType; 11047 QualType SizeType = S.Context.getSizeType(); 11048 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size()); 11049 while (const ConstantArrayType *Array 11050 = S.Context.getAsConstantArrayType(BaseType)) { 11051 // Create the iteration variable for this array index. 11052 IdentifierInfo *IterationVarName = 0; 11053 { 11054 SmallString<8> Str; 11055 llvm::raw_svector_ostream OS(Str); 11056 OS << "__i" << IndexVariables.size(); 11057 IterationVarName = &S.Context.Idents.get(OS.str()); 11058 } 11059 VarDecl *IterationVar 11060 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11061 IterationVarName, SizeType, 11062 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11063 SC_None); 11064 IndexVariables.push_back(IterationVar); 11065 LSI->ArrayIndexVars.push_back(IterationVar); 11066 11067 // Create a reference to the iteration variable. 11068 ExprResult IterationVarRef 11069 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 11070 assert(!IterationVarRef.isInvalid() && 11071 "Reference to invented variable cannot fail!"); 11072 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take()); 11073 assert(!IterationVarRef.isInvalid() && 11074 "Conversion of invented variable cannot fail!"); 11075 11076 // Subscript the array with this iteration variable. 11077 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr( 11078 Ref, Loc, IterationVarRef.take(), Loc); 11079 if (Subscript.isInvalid()) { 11080 S.CleanupVarDeclMarking(); 11081 S.DiscardCleanupsInEvaluationContext(); 11082 return ExprError(); 11083 } 11084 11085 Ref = Subscript.take(); 11086 BaseType = Array->getElementType(); 11087 } 11088 11089 // Construct the entity that we will be initializing. For an array, this 11090 // will be first element in the array, which may require several levels 11091 // of array-subscript entities. 11092 SmallVector<InitializedEntity, 4> Entities; 11093 Entities.reserve(1 + IndexVariables.size()); 11094 Entities.push_back( 11095 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc)); 11096 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 11097 Entities.push_back(InitializedEntity::InitializeElement(S.Context, 11098 0, 11099 Entities.back())); 11100 11101 InitializationKind InitKind 11102 = InitializationKind::CreateDirect(Loc, Loc, Loc); 11103 InitializationSequence Init(S, Entities.back(), InitKind, Ref); 11104 ExprResult Result(true); 11105 if (!Init.Diagnose(S, Entities.back(), InitKind, Ref)) 11106 Result = Init.Perform(S, Entities.back(), InitKind, Ref); 11107 11108 // If this initialization requires any cleanups (e.g., due to a 11109 // default argument to a copy constructor), note that for the 11110 // lambda. 11111 if (S.ExprNeedsCleanups) 11112 LSI->ExprNeedsCleanups = true; 11113 11114 // Exit the expression evaluation context used for the capture. 11115 S.CleanupVarDeclMarking(); 11116 S.DiscardCleanupsInEvaluationContext(); 11117 return Result; 11118} 11119 11120bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 11121 TryCaptureKind Kind, SourceLocation EllipsisLoc, 11122 bool BuildAndDiagnose, 11123 QualType &CaptureType, 11124 QualType &DeclRefType) { 11125 bool Nested = false; 11126 11127 DeclContext *DC = CurContext; 11128 if (Var->getDeclContext() == DC) return true; 11129 if (!Var->hasLocalStorage()) return true; 11130 11131 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 11132 11133 // Walk up the stack to determine whether we can capture the variable, 11134 // performing the "simple" checks that don't depend on type. We stop when 11135 // we've either hit the declared scope of the variable or find an existing 11136 // capture of that variable. 11137 CaptureType = Var->getType(); 11138 DeclRefType = CaptureType.getNonReferenceType(); 11139 bool Explicit = (Kind != TryCapture_Implicit); 11140 unsigned FunctionScopesIndex = FunctionScopes.size() - 1; 11141 do { 11142 // Only block literals, captured statements, and lambda expressions can 11143 // capture; other scopes don't work. 11144 DeclContext *ParentDC; 11145 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) 11146 ParentDC = DC->getParent(); 11147 else if (isa<CXXMethodDecl>(DC) && 11148 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call && 11149 cast<CXXRecordDecl>(DC->getParent())->isLambda()) 11150 ParentDC = DC->getParent()->getParent(); 11151 else { 11152 if (BuildAndDiagnose) 11153 diagnoseUncapturableValueReference(*this, Loc, Var, DC); 11154 return true; 11155 } 11156 11157 CapturingScopeInfo *CSI = 11158 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]); 11159 11160 // Check whether we've already captured it. 11161 if (CSI->isCaptured(Var)) { 11162 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 11163 11164 // If we found a capture, any subcaptures are nested. 11165 Nested = true; 11166 11167 // Retrieve the capture type for this variable. 11168 CaptureType = Cap.getCaptureType(); 11169 11170 // Compute the type of an expression that refers to this variable. 11171 DeclRefType = CaptureType.getNonReferenceType(); 11172 11173 if (Cap.isCopyCapture() && 11174 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable)) 11175 DeclRefType.addConst(); 11176 break; 11177 } 11178 11179 bool IsBlock = isa<BlockScopeInfo>(CSI); 11180 bool IsLambda = isa<LambdaScopeInfo>(CSI); 11181 11182 // Lambdas are not allowed to capture unnamed variables 11183 // (e.g. anonymous unions). 11184 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 11185 // assuming that's the intent. 11186 if (IsLambda && !Var->getDeclName()) { 11187 if (BuildAndDiagnose) { 11188 Diag(Loc, diag::err_lambda_capture_anonymous_var); 11189 Diag(Var->getLocation(), diag::note_declared_at); 11190 } 11191 return true; 11192 } 11193 11194 // Prohibit variably-modified types; they're difficult to deal with. 11195 if (Var->getType()->isVariablyModifiedType()) { 11196 if (BuildAndDiagnose) { 11197 if (IsBlock) 11198 Diag(Loc, diag::err_ref_vm_type); 11199 else 11200 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName(); 11201 Diag(Var->getLocation(), diag::note_previous_decl) 11202 << Var->getDeclName(); 11203 } 11204 return true; 11205 } 11206 // Prohibit structs with flexible array members too. 11207 // We cannot capture what is in the tail end of the struct. 11208 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 11209 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 11210 if (BuildAndDiagnose) { 11211 if (IsBlock) 11212 Diag(Loc, diag::err_ref_flexarray_type); 11213 else 11214 Diag(Loc, diag::err_lambda_capture_flexarray_type) 11215 << Var->getDeclName(); 11216 Diag(Var->getLocation(), diag::note_previous_decl) 11217 << Var->getDeclName(); 11218 } 11219 return true; 11220 } 11221 } 11222 // Lambdas and captured statements are not allowed to capture __block 11223 // variables; they don't support the expected semantics. 11224 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 11225 if (BuildAndDiagnose) { 11226 Diag(Loc, diag::err_capture_block_variable) 11227 << Var->getDeclName() << !IsLambda; 11228 Diag(Var->getLocation(), diag::note_previous_decl) 11229 << Var->getDeclName(); 11230 } 11231 return true; 11232 } 11233 11234 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 11235 // No capture-default 11236 if (BuildAndDiagnose) { 11237 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName(); 11238 Diag(Var->getLocation(), diag::note_previous_decl) 11239 << Var->getDeclName(); 11240 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 11241 diag::note_lambda_decl); 11242 } 11243 return true; 11244 } 11245 11246 FunctionScopesIndex--; 11247 DC = ParentDC; 11248 Explicit = false; 11249 } while (!Var->getDeclContext()->Equals(DC)); 11250 11251 // Walk back down the scope stack, computing the type of the capture at 11252 // each step, checking type-specific requirements, and adding captures if 11253 // requested. 11254 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N; 11255 ++I) { 11256 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 11257 11258 // Compute the type of the capture and of a reference to the capture within 11259 // this scope. 11260 if (isa<BlockScopeInfo>(CSI)) { 11261 Expr *CopyExpr = 0; 11262 bool ByRef = false; 11263 11264 // Blocks are not allowed to capture arrays. 11265 if (CaptureType->isArrayType()) { 11266 if (BuildAndDiagnose) { 11267 Diag(Loc, diag::err_ref_array_type); 11268 Diag(Var->getLocation(), diag::note_previous_decl) 11269 << Var->getDeclName(); 11270 } 11271 return true; 11272 } 11273 11274 // Forbid the block-capture of autoreleasing variables. 11275 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11276 if (BuildAndDiagnose) { 11277 Diag(Loc, diag::err_arc_autoreleasing_capture) 11278 << /*block*/ 0; 11279 Diag(Var->getLocation(), diag::note_previous_decl) 11280 << Var->getDeclName(); 11281 } 11282 return true; 11283 } 11284 11285 if (HasBlocksAttr || CaptureType->isReferenceType()) { 11286 // Block capture by reference does not change the capture or 11287 // declaration reference types. 11288 ByRef = true; 11289 } else { 11290 // Block capture by copy introduces 'const'. 11291 CaptureType = CaptureType.getNonReferenceType().withConst(); 11292 DeclRefType = CaptureType; 11293 11294 if (getLangOpts().CPlusPlus && BuildAndDiagnose) { 11295 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 11296 // The capture logic needs the destructor, so make sure we mark it. 11297 // Usually this is unnecessary because most local variables have 11298 // their destructors marked at declaration time, but parameters are 11299 // an exception because it's technically only the call site that 11300 // actually requires the destructor. 11301 if (isa<ParmVarDecl>(Var)) 11302 FinalizeVarWithDestructor(Var, Record); 11303 11304 // Enter a new evaluation context to insulate the copy 11305 // full-expression. 11306 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 11307 11308 // According to the blocks spec, the capture of a variable from 11309 // the stack requires a const copy constructor. This is not true 11310 // of the copy/move done to move a __block variable to the heap. 11311 Expr *DeclRef = new (Context) DeclRefExpr(Var, Nested, 11312 DeclRefType.withConst(), 11313 VK_LValue, Loc); 11314 11315 ExprResult Result 11316 = PerformCopyInitialization( 11317 InitializedEntity::InitializeBlock(Var->getLocation(), 11318 CaptureType, false), 11319 Loc, Owned(DeclRef)); 11320 11321 // Build a full-expression copy expression if initialization 11322 // succeeded and used a non-trivial constructor. Recover from 11323 // errors by pretending that the copy isn't necessary. 11324 if (!Result.isInvalid() && 11325 !cast<CXXConstructExpr>(Result.get())->getConstructor() 11326 ->isTrivial()) { 11327 Result = MaybeCreateExprWithCleanups(Result); 11328 CopyExpr = Result.take(); 11329 } 11330 } 11331 } 11332 } 11333 11334 // Actually capture the variable. 11335 if (BuildAndDiagnose) 11336 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 11337 SourceLocation(), CaptureType, CopyExpr); 11338 Nested = true; 11339 continue; 11340 } 11341 11342 if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 11343 // By default, capture variables by reference. 11344 bool ByRef = true; 11345 // Using an LValue reference type is consistent with Lambdas (see below). 11346 CaptureType = Context.getLValueReferenceType(DeclRefType); 11347 11348 Expr *CopyExpr = 0; 11349 if (BuildAndDiagnose) { 11350 ExprResult Result = captureInCapturedRegion(*this, RSI, Var, 11351 CaptureType, DeclRefType, 11352 Loc, Nested); 11353 if (!Result.isInvalid()) 11354 CopyExpr = Result.take(); 11355 } 11356 11357 // Actually capture the variable. 11358 if (BuildAndDiagnose) 11359 CSI->addCapture(Var, /*isBlock*/false, ByRef, Nested, Loc, 11360 SourceLocation(), CaptureType, CopyExpr); 11361 Nested = true; 11362 continue; 11363 } 11364 11365 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 11366 11367 // Determine whether we are capturing by reference or by value. 11368 bool ByRef = false; 11369 if (I == N - 1 && Kind != TryCapture_Implicit) { 11370 ByRef = (Kind == TryCapture_ExplicitByRef); 11371 } else { 11372 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 11373 } 11374 11375 // Compute the type of the field that will capture this variable. 11376 if (ByRef) { 11377 // C++11 [expr.prim.lambda]p15: 11378 // An entity is captured by reference if it is implicitly or 11379 // explicitly captured but not captured by copy. It is 11380 // unspecified whether additional unnamed non-static data 11381 // members are declared in the closure type for entities 11382 // captured by reference. 11383 // 11384 // FIXME: It is not clear whether we want to build an lvalue reference 11385 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 11386 // to do the former, while EDG does the latter. Core issue 1249 will 11387 // clarify, but for now we follow GCC because it's a more permissive and 11388 // easily defensible position. 11389 CaptureType = Context.getLValueReferenceType(DeclRefType); 11390 } else { 11391 // C++11 [expr.prim.lambda]p14: 11392 // For each entity captured by copy, an unnamed non-static 11393 // data member is declared in the closure type. The 11394 // declaration order of these members is unspecified. The type 11395 // of such a data member is the type of the corresponding 11396 // captured entity if the entity is not a reference to an 11397 // object, or the referenced type otherwise. [Note: If the 11398 // captured entity is a reference to a function, the 11399 // corresponding data member is also a reference to a 11400 // function. - end note ] 11401 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 11402 if (!RefType->getPointeeType()->isFunctionType()) 11403 CaptureType = RefType->getPointeeType(); 11404 } 11405 11406 // Forbid the lambda copy-capture of autoreleasing variables. 11407 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11408 if (BuildAndDiagnose) { 11409 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 11410 Diag(Var->getLocation(), diag::note_previous_decl) 11411 << Var->getDeclName(); 11412 } 11413 return true; 11414 } 11415 } 11416 11417 // Capture this variable in the lambda. 11418 Expr *CopyExpr = 0; 11419 if (BuildAndDiagnose) { 11420 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType, 11421 DeclRefType, Loc, 11422 Nested); 11423 if (!Result.isInvalid()) 11424 CopyExpr = Result.take(); 11425 } 11426 11427 // Compute the type of a reference to this captured variable. 11428 if (ByRef) 11429 DeclRefType = CaptureType.getNonReferenceType(); 11430 else { 11431 // C++ [expr.prim.lambda]p5: 11432 // The closure type for a lambda-expression has a public inline 11433 // function call operator [...]. This function call operator is 11434 // declared const (9.3.1) if and only if the lambda-expression’s 11435 // parameter-declaration-clause is not followed by mutable. 11436 DeclRefType = CaptureType.getNonReferenceType(); 11437 if (!LSI->Mutable && !CaptureType->isReferenceType()) 11438 DeclRefType.addConst(); 11439 } 11440 11441 // Add the capture. 11442 if (BuildAndDiagnose) 11443 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc, 11444 EllipsisLoc, CaptureType, CopyExpr); 11445 Nested = true; 11446 } 11447 11448 return false; 11449} 11450 11451bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 11452 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 11453 QualType CaptureType; 11454 QualType DeclRefType; 11455 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 11456 /*BuildAndDiagnose=*/true, CaptureType, 11457 DeclRefType); 11458} 11459 11460QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 11461 QualType CaptureType; 11462 QualType DeclRefType; 11463 11464 // Determine whether we can capture this variable. 11465 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 11466 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType)) 11467 return QualType(); 11468 11469 return DeclRefType; 11470} 11471 11472static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var, 11473 SourceLocation Loc) { 11474 // Keep track of used but undefined variables. 11475 // FIXME: We shouldn't suppress this warning for static data members. 11476 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 11477 !Var->isExternallyVisible() && 11478 !(Var->isStaticDataMember() && Var->hasInit())) { 11479 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 11480 if (old.isInvalid()) old = Loc; 11481 } 11482 11483 SemaRef.tryCaptureVariable(Var, Loc); 11484 11485 Var->setUsed(true); 11486} 11487 11488void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 11489 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 11490 // an object that satisfies the requirements for appearing in a 11491 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 11492 // is immediately applied." This function handles the lvalue-to-rvalue 11493 // conversion part. 11494 MaybeODRUseExprs.erase(E->IgnoreParens()); 11495} 11496 11497ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 11498 if (!Res.isUsable()) 11499 return Res; 11500 11501 // If a constant-expression is a reference to a variable where we delay 11502 // deciding whether it is an odr-use, just assume we will apply the 11503 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 11504 // (a non-type template argument), we have special handling anyway. 11505 UpdateMarkingForLValueToRValue(Res.get()); 11506 return Res; 11507} 11508 11509void Sema::CleanupVarDeclMarking() { 11510 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(), 11511 e = MaybeODRUseExprs.end(); 11512 i != e; ++i) { 11513 VarDecl *Var; 11514 SourceLocation Loc; 11515 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) { 11516 Var = cast<VarDecl>(DRE->getDecl()); 11517 Loc = DRE->getLocation(); 11518 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) { 11519 Var = cast<VarDecl>(ME->getMemberDecl()); 11520 Loc = ME->getMemberLoc(); 11521 } else { 11522 llvm_unreachable("Unexpcted expression"); 11523 } 11524 11525 MarkVarDeclODRUsed(*this, Var, Loc); 11526 } 11527 11528 MaybeODRUseExprs.clear(); 11529} 11530 11531// Mark a VarDecl referenced, and perform the necessary handling to compute 11532// odr-uses. 11533static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 11534 VarDecl *Var, Expr *E) { 11535 Var->setReferenced(); 11536 11537 if (!IsPotentiallyEvaluatedContext(SemaRef)) 11538 return; 11539 11540 // Implicit instantiation of static data members of class templates. 11541 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) { 11542 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); 11543 assert(MSInfo && "Missing member specialization information?"); 11544 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid(); 11545 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation && 11546 (!AlreadyInstantiated || 11547 Var->isUsableInConstantExpressions(SemaRef.Context))) { 11548 if (!AlreadyInstantiated) { 11549 // This is a modification of an existing AST node. Notify listeners. 11550 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 11551 L->StaticDataMemberInstantiated(Var); 11552 MSInfo->setPointOfInstantiation(Loc); 11553 } 11554 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation(); 11555 if (Var->isUsableInConstantExpressions(SemaRef.Context)) 11556 // Do not defer instantiations of variables which could be used in a 11557 // constant expression. 11558 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var); 11559 else 11560 SemaRef.PendingInstantiations.push_back( 11561 std::make_pair(Var, PointOfInstantiation)); 11562 } 11563 } 11564 11565 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 11566 // the requirements for appearing in a constant expression (5.19) and, if 11567 // it is an object, the lvalue-to-rvalue conversion (4.1) 11568 // is immediately applied." We check the first part here, and 11569 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 11570 // Note that we use the C++11 definition everywhere because nothing in 11571 // C++03 depends on whether we get the C++03 version correct. The second 11572 // part does not apply to references, since they are not objects. 11573 const VarDecl *DefVD; 11574 if (E && !isa<ParmVarDecl>(Var) && 11575 Var->isUsableInConstantExpressions(SemaRef.Context) && 11576 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) { 11577 if (!Var->getType()->isReferenceType()) 11578 SemaRef.MaybeODRUseExprs.insert(E); 11579 } else 11580 MarkVarDeclODRUsed(SemaRef, Var, Loc); 11581} 11582 11583/// \brief Mark a variable referenced, and check whether it is odr-used 11584/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 11585/// used directly for normal expressions referring to VarDecl. 11586void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 11587 DoMarkVarDeclReferenced(*this, Loc, Var, 0); 11588} 11589 11590static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 11591 Decl *D, Expr *E, bool OdrUse) { 11592 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 11593 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 11594 return; 11595 } 11596 11597 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse); 11598 11599 // If this is a call to a method via a cast, also mark the method in the 11600 // derived class used in case codegen can devirtualize the call. 11601 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 11602 if (!ME) 11603 return; 11604 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 11605 if (!MD) 11606 return; 11607 const Expr *Base = ME->getBase(); 11608 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 11609 if (!MostDerivedClassDecl) 11610 return; 11611 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 11612 if (!DM || DM->isPure()) 11613 return; 11614 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse); 11615} 11616 11617/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 11618void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 11619 // TODO: update this with DR# once a defect report is filed. 11620 // C++11 defect. The address of a pure member should not be an ODR use, even 11621 // if it's a qualified reference. 11622 bool OdrUse = true; 11623 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 11624 if (Method->isVirtual()) 11625 OdrUse = false; 11626 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 11627} 11628 11629/// \brief Perform reference-marking and odr-use handling for a MemberExpr. 11630void Sema::MarkMemberReferenced(MemberExpr *E) { 11631 // C++11 [basic.def.odr]p2: 11632 // A non-overloaded function whose name appears as a potentially-evaluated 11633 // expression or a member of a set of candidate functions, if selected by 11634 // overload resolution when referred to from a potentially-evaluated 11635 // expression, is odr-used, unless it is a pure virtual function and its 11636 // name is not explicitly qualified. 11637 bool OdrUse = true; 11638 if (!E->hasQualifier()) { 11639 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 11640 if (Method->isPure()) 11641 OdrUse = false; 11642 } 11643 SourceLocation Loc = E->getMemberLoc().isValid() ? 11644 E->getMemberLoc() : E->getLocStart(); 11645 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse); 11646} 11647 11648/// \brief Perform marking for a reference to an arbitrary declaration. It 11649/// marks the declaration referenced, and performs odr-use checking for functions 11650/// and variables. This method should not be used when building an normal 11651/// expression which refers to a variable. 11652void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) { 11653 if (OdrUse) { 11654 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 11655 MarkVariableReferenced(Loc, VD); 11656 return; 11657 } 11658 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 11659 MarkFunctionReferenced(Loc, FD); 11660 return; 11661 } 11662 } 11663 D->setReferenced(); 11664} 11665 11666namespace { 11667 // Mark all of the declarations referenced 11668 // FIXME: Not fully implemented yet! We need to have a better understanding 11669 // of when we're entering 11670 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 11671 Sema &S; 11672 SourceLocation Loc; 11673 11674 public: 11675 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 11676 11677 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 11678 11679 bool TraverseTemplateArgument(const TemplateArgument &Arg); 11680 bool TraverseRecordType(RecordType *T); 11681 }; 11682} 11683 11684bool MarkReferencedDecls::TraverseTemplateArgument( 11685 const TemplateArgument &Arg) { 11686 if (Arg.getKind() == TemplateArgument::Declaration) { 11687 if (Decl *D = Arg.getAsDecl()) 11688 S.MarkAnyDeclReferenced(Loc, D, true); 11689 } 11690 11691 return Inherited::TraverseTemplateArgument(Arg); 11692} 11693 11694bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 11695 if (ClassTemplateSpecializationDecl *Spec 11696 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 11697 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 11698 return TraverseTemplateArguments(Args.data(), Args.size()); 11699 } 11700 11701 return true; 11702} 11703 11704void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 11705 MarkReferencedDecls Marker(*this, Loc); 11706 Marker.TraverseType(Context.getCanonicalType(T)); 11707} 11708 11709namespace { 11710 /// \brief Helper class that marks all of the declarations referenced by 11711 /// potentially-evaluated subexpressions as "referenced". 11712 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 11713 Sema &S; 11714 bool SkipLocalVariables; 11715 11716 public: 11717 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 11718 11719 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 11720 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 11721 11722 void VisitDeclRefExpr(DeclRefExpr *E) { 11723 // If we were asked not to visit local variables, don't. 11724 if (SkipLocalVariables) { 11725 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 11726 if (VD->hasLocalStorage()) 11727 return; 11728 } 11729 11730 S.MarkDeclRefReferenced(E); 11731 } 11732 11733 void VisitMemberExpr(MemberExpr *E) { 11734 S.MarkMemberReferenced(E); 11735 Inherited::VisitMemberExpr(E); 11736 } 11737 11738 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 11739 S.MarkFunctionReferenced(E->getLocStart(), 11740 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 11741 Visit(E->getSubExpr()); 11742 } 11743 11744 void VisitCXXNewExpr(CXXNewExpr *E) { 11745 if (E->getOperatorNew()) 11746 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 11747 if (E->getOperatorDelete()) 11748 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 11749 Inherited::VisitCXXNewExpr(E); 11750 } 11751 11752 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 11753 if (E->getOperatorDelete()) 11754 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 11755 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 11756 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 11757 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 11758 S.MarkFunctionReferenced(E->getLocStart(), 11759 S.LookupDestructor(Record)); 11760 } 11761 11762 Inherited::VisitCXXDeleteExpr(E); 11763 } 11764 11765 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11766 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 11767 Inherited::VisitCXXConstructExpr(E); 11768 } 11769 11770 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 11771 Visit(E->getExpr()); 11772 } 11773 11774 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11775 Inherited::VisitImplicitCastExpr(E); 11776 11777 if (E->getCastKind() == CK_LValueToRValue) 11778 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 11779 } 11780 }; 11781} 11782 11783/// \brief Mark any declarations that appear within this expression or any 11784/// potentially-evaluated subexpressions as "referenced". 11785/// 11786/// \param SkipLocalVariables If true, don't mark local variables as 11787/// 'referenced'. 11788void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 11789 bool SkipLocalVariables) { 11790 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 11791} 11792 11793/// \brief Emit a diagnostic that describes an effect on the run-time behavior 11794/// of the program being compiled. 11795/// 11796/// This routine emits the given diagnostic when the code currently being 11797/// type-checked is "potentially evaluated", meaning that there is a 11798/// possibility that the code will actually be executable. Code in sizeof() 11799/// expressions, code used only during overload resolution, etc., are not 11800/// potentially evaluated. This routine will suppress such diagnostics or, 11801/// in the absolutely nutty case of potentially potentially evaluated 11802/// expressions (C++ typeid), queue the diagnostic to potentially emit it 11803/// later. 11804/// 11805/// This routine should be used for all diagnostics that describe the run-time 11806/// behavior of a program, such as passing a non-POD value through an ellipsis. 11807/// Failure to do so will likely result in spurious diagnostics or failures 11808/// during overload resolution or within sizeof/alignof/typeof/typeid. 11809bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 11810 const PartialDiagnostic &PD) { 11811 switch (ExprEvalContexts.back().Context) { 11812 case Unevaluated: 11813 case UnevaluatedAbstract: 11814 // The argument will never be evaluated, so don't complain. 11815 break; 11816 11817 case ConstantEvaluated: 11818 // Relevant diagnostics should be produced by constant evaluation. 11819 break; 11820 11821 case PotentiallyEvaluated: 11822 case PotentiallyEvaluatedIfUsed: 11823 if (Statement && getCurFunctionOrMethodDecl()) { 11824 FunctionScopes.back()->PossiblyUnreachableDiags. 11825 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 11826 } 11827 else 11828 Diag(Loc, PD); 11829 11830 return true; 11831 } 11832 11833 return false; 11834} 11835 11836bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 11837 CallExpr *CE, FunctionDecl *FD) { 11838 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 11839 return false; 11840 11841 // If we're inside a decltype's expression, don't check for a valid return 11842 // type or construct temporaries until we know whether this is the last call. 11843 if (ExprEvalContexts.back().IsDecltype) { 11844 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 11845 return false; 11846 } 11847 11848 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 11849 FunctionDecl *FD; 11850 CallExpr *CE; 11851 11852 public: 11853 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 11854 : FD(FD), CE(CE) { } 11855 11856 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 11857 if (!FD) { 11858 S.Diag(Loc, diag::err_call_incomplete_return) 11859 << T << CE->getSourceRange(); 11860 return; 11861 } 11862 11863 S.Diag(Loc, diag::err_call_function_incomplete_return) 11864 << CE->getSourceRange() << FD->getDeclName() << T; 11865 S.Diag(FD->getLocation(), 11866 diag::note_function_with_incomplete_return_type_declared_here) 11867 << FD->getDeclName(); 11868 } 11869 } Diagnoser(FD, CE); 11870 11871 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 11872 return true; 11873 11874 return false; 11875} 11876 11877// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 11878// will prevent this condition from triggering, which is what we want. 11879void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 11880 SourceLocation Loc; 11881 11882 unsigned diagnostic = diag::warn_condition_is_assignment; 11883 bool IsOrAssign = false; 11884 11885 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 11886 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 11887 return; 11888 11889 IsOrAssign = Op->getOpcode() == BO_OrAssign; 11890 11891 // Greylist some idioms by putting them into a warning subcategory. 11892 if (ObjCMessageExpr *ME 11893 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 11894 Selector Sel = ME->getSelector(); 11895 11896 // self = [<foo> init...] 11897 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init")) 11898 diagnostic = diag::warn_condition_is_idiomatic_assignment; 11899 11900 // <foo> = [<bar> nextObject] 11901 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 11902 diagnostic = diag::warn_condition_is_idiomatic_assignment; 11903 } 11904 11905 Loc = Op->getOperatorLoc(); 11906 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 11907 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 11908 return; 11909 11910 IsOrAssign = Op->getOperator() == OO_PipeEqual; 11911 Loc = Op->getOperatorLoc(); 11912 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 11913 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 11914 else { 11915 // Not an assignment. 11916 return; 11917 } 11918 11919 Diag(Loc, diagnostic) << E->getSourceRange(); 11920 11921 SourceLocation Open = E->getLocStart(); 11922 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 11923 Diag(Loc, diag::note_condition_assign_silence) 11924 << FixItHint::CreateInsertion(Open, "(") 11925 << FixItHint::CreateInsertion(Close, ")"); 11926 11927 if (IsOrAssign) 11928 Diag(Loc, diag::note_condition_or_assign_to_comparison) 11929 << FixItHint::CreateReplacement(Loc, "!="); 11930 else 11931 Diag(Loc, diag::note_condition_assign_to_comparison) 11932 << FixItHint::CreateReplacement(Loc, "=="); 11933} 11934 11935/// \brief Redundant parentheses over an equality comparison can indicate 11936/// that the user intended an assignment used as condition. 11937void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 11938 // Don't warn if the parens came from a macro. 11939 SourceLocation parenLoc = ParenE->getLocStart(); 11940 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 11941 return; 11942 // Don't warn for dependent expressions. 11943 if (ParenE->isTypeDependent()) 11944 return; 11945 11946 Expr *E = ParenE->IgnoreParens(); 11947 11948 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 11949 if (opE->getOpcode() == BO_EQ && 11950 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 11951 == Expr::MLV_Valid) { 11952 SourceLocation Loc = opE->getOperatorLoc(); 11953 11954 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 11955 SourceRange ParenERange = ParenE->getSourceRange(); 11956 Diag(Loc, diag::note_equality_comparison_silence) 11957 << FixItHint::CreateRemoval(ParenERange.getBegin()) 11958 << FixItHint::CreateRemoval(ParenERange.getEnd()); 11959 Diag(Loc, diag::note_equality_comparison_to_assign) 11960 << FixItHint::CreateReplacement(Loc, "="); 11961 } 11962} 11963 11964ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 11965 DiagnoseAssignmentAsCondition(E); 11966 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 11967 DiagnoseEqualityWithExtraParens(parenE); 11968 11969 ExprResult result = CheckPlaceholderExpr(E); 11970 if (result.isInvalid()) return ExprError(); 11971 E = result.take(); 11972 11973 if (!E->isTypeDependent()) { 11974 if (getLangOpts().CPlusPlus) 11975 return CheckCXXBooleanCondition(E); // C++ 6.4p4 11976 11977 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 11978 if (ERes.isInvalid()) 11979 return ExprError(); 11980 E = ERes.take(); 11981 11982 QualType T = E->getType(); 11983 if (!T->isScalarType()) { // C99 6.8.4.1p1 11984 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 11985 << T << E->getSourceRange(); 11986 return ExprError(); 11987 } 11988 } 11989 11990 return Owned(E); 11991} 11992 11993ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 11994 Expr *SubExpr) { 11995 if (!SubExpr) 11996 return ExprError(); 11997 11998 return CheckBooleanCondition(SubExpr, Loc); 11999} 12000 12001namespace { 12002 /// A visitor for rebuilding a call to an __unknown_any expression 12003 /// to have an appropriate type. 12004 struct RebuildUnknownAnyFunction 12005 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 12006 12007 Sema &S; 12008 12009 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 12010 12011 ExprResult VisitStmt(Stmt *S) { 12012 llvm_unreachable("unexpected statement!"); 12013 } 12014 12015 ExprResult VisitExpr(Expr *E) { 12016 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 12017 << E->getSourceRange(); 12018 return ExprError(); 12019 } 12020 12021 /// Rebuild an expression which simply semantically wraps another 12022 /// expression which it shares the type and value kind of. 12023 template <class T> ExprResult rebuildSugarExpr(T *E) { 12024 ExprResult SubResult = Visit(E->getSubExpr()); 12025 if (SubResult.isInvalid()) return ExprError(); 12026 12027 Expr *SubExpr = SubResult.take(); 12028 E->setSubExpr(SubExpr); 12029 E->setType(SubExpr->getType()); 12030 E->setValueKind(SubExpr->getValueKind()); 12031 assert(E->getObjectKind() == OK_Ordinary); 12032 return E; 12033 } 12034 12035 ExprResult VisitParenExpr(ParenExpr *E) { 12036 return rebuildSugarExpr(E); 12037 } 12038 12039 ExprResult VisitUnaryExtension(UnaryOperator *E) { 12040 return rebuildSugarExpr(E); 12041 } 12042 12043 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 12044 ExprResult SubResult = Visit(E->getSubExpr()); 12045 if (SubResult.isInvalid()) return ExprError(); 12046 12047 Expr *SubExpr = SubResult.take(); 12048 E->setSubExpr(SubExpr); 12049 E->setType(S.Context.getPointerType(SubExpr->getType())); 12050 assert(E->getValueKind() == VK_RValue); 12051 assert(E->getObjectKind() == OK_Ordinary); 12052 return E; 12053 } 12054 12055 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 12056 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 12057 12058 E->setType(VD->getType()); 12059 12060 assert(E->getValueKind() == VK_RValue); 12061 if (S.getLangOpts().CPlusPlus && 12062 !(isa<CXXMethodDecl>(VD) && 12063 cast<CXXMethodDecl>(VD)->isInstance())) 12064 E->setValueKind(VK_LValue); 12065 12066 return E; 12067 } 12068 12069 ExprResult VisitMemberExpr(MemberExpr *E) { 12070 return resolveDecl(E, E->getMemberDecl()); 12071 } 12072 12073 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 12074 return resolveDecl(E, E->getDecl()); 12075 } 12076 }; 12077} 12078 12079/// Given a function expression of unknown-any type, try to rebuild it 12080/// to have a function type. 12081static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 12082 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 12083 if (Result.isInvalid()) return ExprError(); 12084 return S.DefaultFunctionArrayConversion(Result.take()); 12085} 12086 12087namespace { 12088 /// A visitor for rebuilding an expression of type __unknown_anytype 12089 /// into one which resolves the type directly on the referring 12090 /// expression. Strict preservation of the original source 12091 /// structure is not a goal. 12092 struct RebuildUnknownAnyExpr 12093 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 12094 12095 Sema &S; 12096 12097 /// The current destination type. 12098 QualType DestType; 12099 12100 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 12101 : S(S), DestType(CastType) {} 12102 12103 ExprResult VisitStmt(Stmt *S) { 12104 llvm_unreachable("unexpected statement!"); 12105 } 12106 12107 ExprResult VisitExpr(Expr *E) { 12108 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 12109 << E->getSourceRange(); 12110 return ExprError(); 12111 } 12112 12113 ExprResult VisitCallExpr(CallExpr *E); 12114 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 12115 12116 /// Rebuild an expression which simply semantically wraps another 12117 /// expression which it shares the type and value kind of. 12118 template <class T> ExprResult rebuildSugarExpr(T *E) { 12119 ExprResult SubResult = Visit(E->getSubExpr()); 12120 if (SubResult.isInvalid()) return ExprError(); 12121 Expr *SubExpr = SubResult.take(); 12122 E->setSubExpr(SubExpr); 12123 E->setType(SubExpr->getType()); 12124 E->setValueKind(SubExpr->getValueKind()); 12125 assert(E->getObjectKind() == OK_Ordinary); 12126 return E; 12127 } 12128 12129 ExprResult VisitParenExpr(ParenExpr *E) { 12130 return rebuildSugarExpr(E); 12131 } 12132 12133 ExprResult VisitUnaryExtension(UnaryOperator *E) { 12134 return rebuildSugarExpr(E); 12135 } 12136 12137 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 12138 const PointerType *Ptr = DestType->getAs<PointerType>(); 12139 if (!Ptr) { 12140 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 12141 << E->getSourceRange(); 12142 return ExprError(); 12143 } 12144 assert(E->getValueKind() == VK_RValue); 12145 assert(E->getObjectKind() == OK_Ordinary); 12146 E->setType(DestType); 12147 12148 // Build the sub-expression as if it were an object of the pointee type. 12149 DestType = Ptr->getPointeeType(); 12150 ExprResult SubResult = Visit(E->getSubExpr()); 12151 if (SubResult.isInvalid()) return ExprError(); 12152 E->setSubExpr(SubResult.take()); 12153 return E; 12154 } 12155 12156 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 12157 12158 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 12159 12160 ExprResult VisitMemberExpr(MemberExpr *E) { 12161 return resolveDecl(E, E->getMemberDecl()); 12162 } 12163 12164 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 12165 return resolveDecl(E, E->getDecl()); 12166 } 12167 }; 12168} 12169 12170/// Rebuilds a call expression which yielded __unknown_anytype. 12171ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 12172 Expr *CalleeExpr = E->getCallee(); 12173 12174 enum FnKind { 12175 FK_MemberFunction, 12176 FK_FunctionPointer, 12177 FK_BlockPointer 12178 }; 12179 12180 FnKind Kind; 12181 QualType CalleeType = CalleeExpr->getType(); 12182 if (CalleeType == S.Context.BoundMemberTy) { 12183 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 12184 Kind = FK_MemberFunction; 12185 CalleeType = Expr::findBoundMemberType(CalleeExpr); 12186 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 12187 CalleeType = Ptr->getPointeeType(); 12188 Kind = FK_FunctionPointer; 12189 } else { 12190 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 12191 Kind = FK_BlockPointer; 12192 } 12193 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 12194 12195 // Verify that this is a legal result type of a function. 12196 if (DestType->isArrayType() || DestType->isFunctionType()) { 12197 unsigned diagID = diag::err_func_returning_array_function; 12198 if (Kind == FK_BlockPointer) 12199 diagID = diag::err_block_returning_array_function; 12200 12201 S.Diag(E->getExprLoc(), diagID) 12202 << DestType->isFunctionType() << DestType; 12203 return ExprError(); 12204 } 12205 12206 // Otherwise, go ahead and set DestType as the call's result. 12207 E->setType(DestType.getNonLValueExprType(S.Context)); 12208 E->setValueKind(Expr::getValueKindForType(DestType)); 12209 assert(E->getObjectKind() == OK_Ordinary); 12210 12211 // Rebuild the function type, replacing the result type with DestType. 12212 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 12213 if (Proto) { 12214 // __unknown_anytype(...) is a special case used by the debugger when 12215 // it has no idea what a function's signature is. 12216 // 12217 // We want to build this call essentially under the K&R 12218 // unprototyped rules, but making a FunctionNoProtoType in C++ 12219 // would foul up all sorts of assumptions. However, we cannot 12220 // simply pass all arguments as variadic arguments, nor can we 12221 // portably just call the function under a non-variadic type; see 12222 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 12223 // However, it turns out that in practice it is generally safe to 12224 // call a function declared as "A foo(B,C,D);" under the prototype 12225 // "A foo(B,C,D,...);". The only known exception is with the 12226 // Windows ABI, where any variadic function is implicitly cdecl 12227 // regardless of its normal CC. Therefore we change the parameter 12228 // types to match the types of the arguments. 12229 // 12230 // This is a hack, but it is far superior to moving the 12231 // corresponding target-specific code from IR-gen to Sema/AST. 12232 12233 ArrayRef<QualType> ParamTypes = Proto->getArgTypes(); 12234 SmallVector<QualType, 8> ArgTypes; 12235 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 12236 ArgTypes.reserve(E->getNumArgs()); 12237 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 12238 Expr *Arg = E->getArg(i); 12239 QualType ArgType = Arg->getType(); 12240 if (E->isLValue()) { 12241 ArgType = S.Context.getLValueReferenceType(ArgType); 12242 } else if (E->isXValue()) { 12243 ArgType = S.Context.getRValueReferenceType(ArgType); 12244 } 12245 ArgTypes.push_back(ArgType); 12246 } 12247 ParamTypes = ArgTypes; 12248 } 12249 DestType = S.Context.getFunctionType(DestType, ParamTypes, 12250 Proto->getExtProtoInfo()); 12251 } else { 12252 DestType = S.Context.getFunctionNoProtoType(DestType, 12253 FnType->getExtInfo()); 12254 } 12255 12256 // Rebuild the appropriate pointer-to-function type. 12257 switch (Kind) { 12258 case FK_MemberFunction: 12259 // Nothing to do. 12260 break; 12261 12262 case FK_FunctionPointer: 12263 DestType = S.Context.getPointerType(DestType); 12264 break; 12265 12266 case FK_BlockPointer: 12267 DestType = S.Context.getBlockPointerType(DestType); 12268 break; 12269 } 12270 12271 // Finally, we can recurse. 12272 ExprResult CalleeResult = Visit(CalleeExpr); 12273 if (!CalleeResult.isUsable()) return ExprError(); 12274 E->setCallee(CalleeResult.take()); 12275 12276 // Bind a temporary if necessary. 12277 return S.MaybeBindToTemporary(E); 12278} 12279 12280ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 12281 // Verify that this is a legal result type of a call. 12282 if (DestType->isArrayType() || DestType->isFunctionType()) { 12283 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 12284 << DestType->isFunctionType() << DestType; 12285 return ExprError(); 12286 } 12287 12288 // Rewrite the method result type if available. 12289 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 12290 assert(Method->getResultType() == S.Context.UnknownAnyTy); 12291 Method->setResultType(DestType); 12292 } 12293 12294 // Change the type of the message. 12295 E->setType(DestType.getNonReferenceType()); 12296 E->setValueKind(Expr::getValueKindForType(DestType)); 12297 12298 return S.MaybeBindToTemporary(E); 12299} 12300 12301ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 12302 // The only case we should ever see here is a function-to-pointer decay. 12303 if (E->getCastKind() == CK_FunctionToPointerDecay) { 12304 assert(E->getValueKind() == VK_RValue); 12305 assert(E->getObjectKind() == OK_Ordinary); 12306 12307 E->setType(DestType); 12308 12309 // Rebuild the sub-expression as the pointee (function) type. 12310 DestType = DestType->castAs<PointerType>()->getPointeeType(); 12311 12312 ExprResult Result = Visit(E->getSubExpr()); 12313 if (!Result.isUsable()) return ExprError(); 12314 12315 E->setSubExpr(Result.take()); 12316 return S.Owned(E); 12317 } else if (E->getCastKind() == CK_LValueToRValue) { 12318 assert(E->getValueKind() == VK_RValue); 12319 assert(E->getObjectKind() == OK_Ordinary); 12320 12321 assert(isa<BlockPointerType>(E->getType())); 12322 12323 E->setType(DestType); 12324 12325 // The sub-expression has to be a lvalue reference, so rebuild it as such. 12326 DestType = S.Context.getLValueReferenceType(DestType); 12327 12328 ExprResult Result = Visit(E->getSubExpr()); 12329 if (!Result.isUsable()) return ExprError(); 12330 12331 E->setSubExpr(Result.take()); 12332 return S.Owned(E); 12333 } else { 12334 llvm_unreachable("Unhandled cast type!"); 12335 } 12336} 12337 12338ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 12339 ExprValueKind ValueKind = VK_LValue; 12340 QualType Type = DestType; 12341 12342 // We know how to make this work for certain kinds of decls: 12343 12344 // - functions 12345 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 12346 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 12347 DestType = Ptr->getPointeeType(); 12348 ExprResult Result = resolveDecl(E, VD); 12349 if (Result.isInvalid()) return ExprError(); 12350 return S.ImpCastExprToType(Result.take(), Type, 12351 CK_FunctionToPointerDecay, VK_RValue); 12352 } 12353 12354 if (!Type->isFunctionType()) { 12355 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 12356 << VD << E->getSourceRange(); 12357 return ExprError(); 12358 } 12359 12360 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 12361 if (MD->isInstance()) { 12362 ValueKind = VK_RValue; 12363 Type = S.Context.BoundMemberTy; 12364 } 12365 12366 // Function references aren't l-values in C. 12367 if (!S.getLangOpts().CPlusPlus) 12368 ValueKind = VK_RValue; 12369 12370 // - variables 12371 } else if (isa<VarDecl>(VD)) { 12372 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 12373 Type = RefTy->getPointeeType(); 12374 } else if (Type->isFunctionType()) { 12375 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 12376 << VD << E->getSourceRange(); 12377 return ExprError(); 12378 } 12379 12380 // - nothing else 12381 } else { 12382 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 12383 << VD << E->getSourceRange(); 12384 return ExprError(); 12385 } 12386 12387 // Modifying the declaration like this is friendly to IR-gen but 12388 // also really dangerous. 12389 VD->setType(DestType); 12390 E->setType(Type); 12391 E->setValueKind(ValueKind); 12392 return S.Owned(E); 12393} 12394 12395/// Check a cast of an unknown-any type. We intentionally only 12396/// trigger this for C-style casts. 12397ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 12398 Expr *CastExpr, CastKind &CastKind, 12399 ExprValueKind &VK, CXXCastPath &Path) { 12400 // Rewrite the casted expression from scratch. 12401 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 12402 if (!result.isUsable()) return ExprError(); 12403 12404 CastExpr = result.take(); 12405 VK = CastExpr->getValueKind(); 12406 CastKind = CK_NoOp; 12407 12408 return CastExpr; 12409} 12410 12411ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 12412 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 12413} 12414 12415ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 12416 Expr *arg, QualType ¶mType) { 12417 // If the syntactic form of the argument is not an explicit cast of 12418 // any sort, just do default argument promotion. 12419 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 12420 if (!castArg) { 12421 ExprResult result = DefaultArgumentPromotion(arg); 12422 if (result.isInvalid()) return ExprError(); 12423 paramType = result.get()->getType(); 12424 return result; 12425 } 12426 12427 // Otherwise, use the type that was written in the explicit cast. 12428 assert(!arg->hasPlaceholderType()); 12429 paramType = castArg->getTypeAsWritten(); 12430 12431 // Copy-initialize a parameter of that type. 12432 InitializedEntity entity = 12433 InitializedEntity::InitializeParameter(Context, paramType, 12434 /*consumed*/ false); 12435 return PerformCopyInitialization(entity, callLoc, Owned(arg)); 12436} 12437 12438static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 12439 Expr *orig = E; 12440 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 12441 while (true) { 12442 E = E->IgnoreParenImpCasts(); 12443 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 12444 E = call->getCallee(); 12445 diagID = diag::err_uncasted_call_of_unknown_any; 12446 } else { 12447 break; 12448 } 12449 } 12450 12451 SourceLocation loc; 12452 NamedDecl *d; 12453 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 12454 loc = ref->getLocation(); 12455 d = ref->getDecl(); 12456 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 12457 loc = mem->getMemberLoc(); 12458 d = mem->getMemberDecl(); 12459 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 12460 diagID = diag::err_uncasted_call_of_unknown_any; 12461 loc = msg->getSelectorStartLoc(); 12462 d = msg->getMethodDecl(); 12463 if (!d) { 12464 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 12465 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 12466 << orig->getSourceRange(); 12467 return ExprError(); 12468 } 12469 } else { 12470 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 12471 << E->getSourceRange(); 12472 return ExprError(); 12473 } 12474 12475 S.Diag(loc, diagID) << d << orig->getSourceRange(); 12476 12477 // Never recoverable. 12478 return ExprError(); 12479} 12480 12481/// Check for operands with placeholder types and complain if found. 12482/// Returns true if there was an error and no recovery was possible. 12483ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 12484 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 12485 if (!placeholderType) return Owned(E); 12486 12487 switch (placeholderType->getKind()) { 12488 12489 // Overloaded expressions. 12490 case BuiltinType::Overload: { 12491 // Try to resolve a single function template specialization. 12492 // This is obligatory. 12493 ExprResult result = Owned(E); 12494 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 12495 return result; 12496 12497 // If that failed, try to recover with a call. 12498 } else { 12499 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 12500 /*complain*/ true); 12501 return result; 12502 } 12503 } 12504 12505 // Bound member functions. 12506 case BuiltinType::BoundMember: { 12507 ExprResult result = Owned(E); 12508 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function), 12509 /*complain*/ true); 12510 return result; 12511 } 12512 12513 // ARC unbridged casts. 12514 case BuiltinType::ARCUnbridgedCast: { 12515 Expr *realCast = stripARCUnbridgedCast(E); 12516 diagnoseARCUnbridgedCast(realCast); 12517 return Owned(realCast); 12518 } 12519 12520 // Expressions of unknown type. 12521 case BuiltinType::UnknownAny: 12522 return diagnoseUnknownAnyExpr(*this, E); 12523 12524 // Pseudo-objects. 12525 case BuiltinType::PseudoObject: 12526 return checkPseudoObjectRValue(E); 12527 12528 case BuiltinType::BuiltinFn: 12529 Diag(E->getLocStart(), diag::err_builtin_fn_use); 12530 return ExprError(); 12531 12532 // Everything else should be impossible. 12533#define BUILTIN_TYPE(Id, SingletonId) \ 12534 case BuiltinType::Id: 12535#define PLACEHOLDER_TYPE(Id, SingletonId) 12536#include "clang/AST/BuiltinTypes.def" 12537 break; 12538 } 12539 12540 llvm_unreachable("invalid placeholder type!"); 12541} 12542 12543bool Sema::CheckCaseExpression(Expr *E) { 12544 if (E->isTypeDependent()) 12545 return true; 12546 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 12547 return E->getType()->isIntegralOrEnumerationType(); 12548 return false; 12549} 12550 12551/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 12552ExprResult 12553Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 12554 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 12555 "Unknown Objective-C Boolean value!"); 12556 QualType BoolT = Context.ObjCBuiltinBoolTy; 12557 if (!Context.getBOOLDecl()) { 12558 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 12559 Sema::LookupOrdinaryName); 12560 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 12561 NamedDecl *ND = Result.getFoundDecl(); 12562 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 12563 Context.setBOOLDecl(TD); 12564 } 12565 } 12566 if (Context.getBOOLDecl()) 12567 BoolT = Context.getBOOLType(); 12568 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, 12569 BoolT, OpLoc)); 12570} 12571