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/ASTLambda.h" 19 #include "clang/AST/ASTMutationListener.h" 20 #include "clang/AST/CXXInheritance.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/EvaluatedExprVisitor.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/ExprObjC.h" 27 #include "clang/AST/RecursiveASTVisitor.h" 28 #include "clang/AST/TypeLoc.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/LiteralSupport.h" 33 #include "clang/Lex/Preprocessor.h" 34 #include "clang/Sema/AnalysisBasedWarnings.h" 35 #include "clang/Sema/DeclSpec.h" 36 #include "clang/Sema/DelayedDiagnostic.h" 37 #include "clang/Sema/Designator.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaFixItUtils.h" 44 #include "clang/Sema/Template.h" 45 using namespace clang; 46 using namespace sema; 47 48 /// \brief Determine whether the use of this declaration is valid, without 49 /// emitting diagnostics. 50 bool Sema::CanUseDecl(NamedDecl *D) { 51 // See if this is an auto-typed variable whose initializer we are parsing. 52 if (ParsingInitForAutoVars.count(D)) 53 return false; 54 55 // See if this is a deleted function. 56 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 57 if (FD->isDeleted()) 58 return false; 59 60 // If the function has a deduced return type, and we can't deduce it, 61 // then we can't use it either. 62 if (getLangOpts().CPlusPlus1y && FD->getReturnType()->isUndeducedType() && 63 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 64 return false; 65 } 66 67 // See if this function is unavailable. 68 if (D->getAvailability() == AR_Unavailable && 69 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 70 return false; 71 72 return true; 73 } 74 75 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 76 // Warn if this is used but marked unused. 77 if (D->hasAttr<UnusedAttr>()) { 78 const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext()); 79 if (!DC->hasAttr<UnusedAttr>()) 80 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 81 } 82 } 83 84 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S, 85 NamedDecl *D, SourceLocation Loc, 86 const ObjCInterfaceDecl *UnknownObjCClass) { 87 // See if this declaration is unavailable or deprecated. 88 std::string Message; 89 AvailabilityResult Result = D->getAvailability(&Message); 90 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 91 if (Result == AR_Available) { 92 const DeclContext *DC = ECD->getDeclContext(); 93 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 94 Result = TheEnumDecl->getAvailability(&Message); 95 } 96 97 const ObjCPropertyDecl *ObjCPDecl = 0; 98 if (Result == AR_Deprecated || Result == AR_Unavailable) { 99 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 100 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 101 AvailabilityResult PDeclResult = PD->getAvailability(0); 102 if (PDeclResult == Result) 103 ObjCPDecl = PD; 104 } 105 } 106 } 107 108 switch (Result) { 109 case AR_Available: 110 case AR_NotYetIntroduced: 111 break; 112 113 case AR_Deprecated: 114 if (S.getCurContextAvailability() != AR_Deprecated) 115 S.EmitAvailabilityWarning(Sema::AD_Deprecation, 116 D, Message, Loc, UnknownObjCClass, ObjCPDecl); 117 break; 118 119 case AR_Unavailable: 120 if (S.getCurContextAvailability() != AR_Unavailable) 121 S.EmitAvailabilityWarning(Sema::AD_Unavailable, 122 D, Message, Loc, UnknownObjCClass, ObjCPDecl); 123 break; 124 125 } 126 return Result; 127 } 128 129 /// \brief Emit a note explaining that this function is deleted. 130 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 131 assert(Decl->isDeleted()); 132 133 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 134 135 if (Method && Method->isDeleted() && Method->isDefaulted()) { 136 // If the method was explicitly defaulted, point at that declaration. 137 if (!Method->isImplicit()) 138 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 139 140 // Try to diagnose why this special member function was implicitly 141 // deleted. This might fail, if that reason no longer applies. 142 CXXSpecialMember CSM = getSpecialMember(Method); 143 if (CSM != CXXInvalid) 144 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true); 145 146 return; 147 } 148 149 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) { 150 if (CXXConstructorDecl *BaseCD = 151 const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) { 152 Diag(Decl->getLocation(), diag::note_inherited_deleted_here); 153 if (BaseCD->isDeleted()) { 154 NoteDeletedFunction(BaseCD); 155 } else { 156 // FIXME: An explanation of why exactly it can't be inherited 157 // would be nice. 158 Diag(BaseCD->getLocation(), diag::note_cannot_inherit); 159 } 160 return; 161 } 162 } 163 164 Diag(Decl->getLocation(), diag::note_availability_specified_here) 165 << Decl << true; 166 } 167 168 /// \brief Determine whether a FunctionDecl was ever declared with an 169 /// explicit storage class. 170 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 171 for (auto I : D->redecls()) { 172 if (I->getStorageClass() != SC_None) 173 return true; 174 } 175 return false; 176 } 177 178 /// \brief Check whether we're in an extern inline function and referring to a 179 /// variable or function with internal linkage (C11 6.7.4p3). 180 /// 181 /// This is only a warning because we used to silently accept this code, but 182 /// in many cases it will not behave correctly. This is not enabled in C++ mode 183 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 184 /// and so while there may still be user mistakes, most of the time we can't 185 /// prove that there are errors. 186 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 187 const NamedDecl *D, 188 SourceLocation Loc) { 189 // This is disabled under C++; there are too many ways for this to fire in 190 // contexts where the warning is a false positive, or where it is technically 191 // correct but benign. 192 if (S.getLangOpts().CPlusPlus) 193 return; 194 195 // Check if this is an inlined function or method. 196 FunctionDecl *Current = S.getCurFunctionDecl(); 197 if (!Current) 198 return; 199 if (!Current->isInlined()) 200 return; 201 if (!Current->isExternallyVisible()) 202 return; 203 204 // Check if the decl has internal linkage. 205 if (D->getFormalLinkage() != InternalLinkage) 206 return; 207 208 // Downgrade from ExtWarn to Extension if 209 // (1) the supposedly external inline function is in the main file, 210 // and probably won't be included anywhere else. 211 // (2) the thing we're referencing is a pure function. 212 // (3) the thing we're referencing is another inline function. 213 // This last can give us false negatives, but it's better than warning on 214 // wrappers for simple C library functions. 215 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 216 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 217 if (!DowngradeWarning && UsedFn) 218 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 219 220 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline 221 : diag::warn_internal_in_extern_inline) 222 << /*IsVar=*/!UsedFn << D; 223 224 S.MaybeSuggestAddingStaticToDecl(Current); 225 226 S.Diag(D->getCanonicalDecl()->getLocation(), 227 diag::note_internal_decl_declared_here) 228 << D; 229 } 230 231 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 232 const FunctionDecl *First = Cur->getFirstDecl(); 233 234 // Suggest "static" on the function, if possible. 235 if (!hasAnyExplicitStorageClass(First)) { 236 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 237 Diag(DeclBegin, diag::note_convert_inline_to_static) 238 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 239 } 240 } 241 242 /// \brief Determine whether the use of this declaration is valid, and 243 /// emit any corresponding diagnostics. 244 /// 245 /// This routine diagnoses various problems with referencing 246 /// declarations that can occur when using a declaration. For example, 247 /// it might warn if a deprecated or unavailable declaration is being 248 /// used, or produce an error (and return true) if a C++0x deleted 249 /// function is being used. 250 /// 251 /// \returns true if there was an error (this declaration cannot be 252 /// referenced), false otherwise. 253 /// 254 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 255 const ObjCInterfaceDecl *UnknownObjCClass) { 256 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 257 // If there were any diagnostics suppressed by template argument deduction, 258 // emit them now. 259 SuppressedDiagnosticsMap::iterator 260 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 261 if (Pos != SuppressedDiagnostics.end()) { 262 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second; 263 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I) 264 Diag(Suppressed[I].first, Suppressed[I].second); 265 266 // Clear out the list of suppressed diagnostics, so that we don't emit 267 // them again for this specialization. However, we don't obsolete this 268 // entry from the table, because we want to avoid ever emitting these 269 // diagnostics again. 270 Suppressed.clear(); 271 } 272 273 // C++ [basic.start.main]p3: 274 // The function 'main' shall not be used within a program. 275 if (cast<FunctionDecl>(D)->isMain()) 276 Diag(Loc, diag::ext_main_used); 277 } 278 279 // See if this is an auto-typed variable whose initializer we are parsing. 280 if (ParsingInitForAutoVars.count(D)) { 281 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 282 << D->getDeclName(); 283 return true; 284 } 285 286 // See if this is a deleted function. 287 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 288 if (FD->isDeleted()) { 289 Diag(Loc, diag::err_deleted_function_use); 290 NoteDeletedFunction(FD); 291 return true; 292 } 293 294 // If the function has a deduced return type, and we can't deduce it, 295 // then we can't use it either. 296 if (getLangOpts().CPlusPlus1y && FD->getReturnType()->isUndeducedType() && 297 DeduceReturnType(FD, Loc)) 298 return true; 299 } 300 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass); 301 302 DiagnoseUnusedOfDecl(*this, D, Loc); 303 304 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 305 306 return false; 307 } 308 309 /// \brief Retrieve the message suffix that should be added to a 310 /// diagnostic complaining about the given function being deleted or 311 /// unavailable. 312 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 313 std::string Message; 314 if (FD->getAvailability(&Message)) 315 return ": " + Message; 316 317 return std::string(); 318 } 319 320 /// DiagnoseSentinelCalls - This routine checks whether a call or 321 /// message-send is to a declaration with the sentinel attribute, and 322 /// if so, it checks that the requirements of the sentinel are 323 /// satisfied. 324 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 325 ArrayRef<Expr *> Args) { 326 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 327 if (!attr) 328 return; 329 330 // The number of formal parameters of the declaration. 331 unsigned numFormalParams; 332 333 // The kind of declaration. This is also an index into a %select in 334 // the diagnostic. 335 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 336 337 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 338 numFormalParams = MD->param_size(); 339 calleeType = CT_Method; 340 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 341 numFormalParams = FD->param_size(); 342 calleeType = CT_Function; 343 } else if (isa<VarDecl>(D)) { 344 QualType type = cast<ValueDecl>(D)->getType(); 345 const FunctionType *fn = 0; 346 if (const PointerType *ptr = type->getAs<PointerType>()) { 347 fn = ptr->getPointeeType()->getAs<FunctionType>(); 348 if (!fn) return; 349 calleeType = CT_Function; 350 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 351 fn = ptr->getPointeeType()->castAs<FunctionType>(); 352 calleeType = CT_Block; 353 } else { 354 return; 355 } 356 357 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 358 numFormalParams = proto->getNumParams(); 359 } else { 360 numFormalParams = 0; 361 } 362 } else { 363 return; 364 } 365 366 // "nullPos" is the number of formal parameters at the end which 367 // effectively count as part of the variadic arguments. This is 368 // useful if you would prefer to not have *any* formal parameters, 369 // but the language forces you to have at least one. 370 unsigned nullPos = attr->getNullPos(); 371 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 372 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 373 374 // The number of arguments which should follow the sentinel. 375 unsigned numArgsAfterSentinel = attr->getSentinel(); 376 377 // If there aren't enough arguments for all the formal parameters, 378 // the sentinel, and the args after the sentinel, complain. 379 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 380 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 381 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 382 return; 383 } 384 385 // Otherwise, find the sentinel expression. 386 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 387 if (!sentinelExpr) return; 388 if (sentinelExpr->isValueDependent()) return; 389 if (Context.isSentinelNullExpr(sentinelExpr)) return; 390 391 // Pick a reasonable string to insert. Optimistically use 'nil' or 392 // 'NULL' if those are actually defined in the context. Only use 393 // 'nil' for ObjC methods, where it's much more likely that the 394 // variadic arguments form a list of object pointers. 395 SourceLocation MissingNilLoc 396 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd()); 397 std::string NullValue; 398 if (calleeType == CT_Method && 399 PP.getIdentifierInfo("nil")->hasMacroDefinition()) 400 NullValue = "nil"; 401 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition()) 402 NullValue = "NULL"; 403 else 404 NullValue = "(void*) 0"; 405 406 if (MissingNilLoc.isInvalid()) 407 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 408 else 409 Diag(MissingNilLoc, diag::warn_missing_sentinel) 410 << int(calleeType) 411 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 412 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 413 } 414 415 SourceRange Sema::getExprRange(Expr *E) const { 416 return E ? E->getSourceRange() : SourceRange(); 417 } 418 419 //===----------------------------------------------------------------------===// 420 // Standard Promotions and Conversions 421 //===----------------------------------------------------------------------===// 422 423 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 424 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) { 425 // Handle any placeholder expressions which made it here. 426 if (E->getType()->isPlaceholderType()) { 427 ExprResult result = CheckPlaceholderExpr(E); 428 if (result.isInvalid()) return ExprError(); 429 E = result.take(); 430 } 431 432 QualType Ty = E->getType(); 433 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 434 435 if (Ty->isFunctionType()) { 436 // If we are here, we are not calling a function but taking 437 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 438 if (getLangOpts().OpenCL) { 439 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 440 return ExprError(); 441 } 442 E = ImpCastExprToType(E, Context.getPointerType(Ty), 443 CK_FunctionToPointerDecay).take(); 444 } else if (Ty->isArrayType()) { 445 // In C90 mode, arrays only promote to pointers if the array expression is 446 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 447 // type 'array of type' is converted to an expression that has type 'pointer 448 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 449 // that has type 'array of type' ...". The relevant change is "an lvalue" 450 // (C90) to "an expression" (C99). 451 // 452 // C++ 4.2p1: 453 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 454 // T" can be converted to an rvalue of type "pointer to T". 455 // 456 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 457 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 458 CK_ArrayToPointerDecay).take(); 459 } 460 return Owned(E); 461 } 462 463 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 464 // Check to see if we are dereferencing a null pointer. If so, 465 // and if not volatile-qualified, this is undefined behavior that the 466 // optimizer will delete, so warn about it. People sometimes try to use this 467 // to get a deterministic trap and are surprised by clang's behavior. This 468 // only handles the pattern "*null", which is a very syntactic check. 469 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 470 if (UO->getOpcode() == UO_Deref && 471 UO->getSubExpr()->IgnoreParenCasts()-> 472 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 473 !UO->getType().isVolatileQualified()) { 474 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 475 S.PDiag(diag::warn_indirection_through_null) 476 << UO->getSubExpr()->getSourceRange()); 477 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 478 S.PDiag(diag::note_indirection_through_null)); 479 } 480 } 481 482 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 483 SourceLocation AssignLoc, 484 const Expr* RHS) { 485 const ObjCIvarDecl *IV = OIRE->getDecl(); 486 if (!IV) 487 return; 488 489 DeclarationName MemberName = IV->getDeclName(); 490 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 491 if (!Member || !Member->isStr("isa")) 492 return; 493 494 const Expr *Base = OIRE->getBase(); 495 QualType BaseType = Base->getType(); 496 if (OIRE->isArrow()) 497 BaseType = BaseType->getPointeeType(); 498 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 499 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 500 ObjCInterfaceDecl *ClassDeclared = 0; 501 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 502 if (!ClassDeclared->getSuperClass() 503 && (*ClassDeclared->ivar_begin()) == IV) { 504 if (RHS) { 505 NamedDecl *ObjectSetClass = 506 S.LookupSingleName(S.TUScope, 507 &S.Context.Idents.get("object_setClass"), 508 SourceLocation(), S.LookupOrdinaryName); 509 if (ObjectSetClass) { 510 SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd()); 511 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 512 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 513 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 514 AssignLoc), ",") << 515 FixItHint::CreateInsertion(RHSLocEnd, ")"); 516 } 517 else 518 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 519 } else { 520 NamedDecl *ObjectGetClass = 521 S.LookupSingleName(S.TUScope, 522 &S.Context.Idents.get("object_getClass"), 523 SourceLocation(), S.LookupOrdinaryName); 524 if (ObjectGetClass) 525 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 526 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 527 FixItHint::CreateReplacement( 528 SourceRange(OIRE->getOpLoc(), 529 OIRE->getLocEnd()), ")"); 530 else 531 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 532 } 533 S.Diag(IV->getLocation(), diag::note_ivar_decl); 534 } 535 } 536 } 537 538 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 539 // Handle any placeholder expressions which made it here. 540 if (E->getType()->isPlaceholderType()) { 541 ExprResult result = CheckPlaceholderExpr(E); 542 if (result.isInvalid()) return ExprError(); 543 E = result.take(); 544 } 545 546 // C++ [conv.lval]p1: 547 // A glvalue of a non-function, non-array type T can be 548 // converted to a prvalue. 549 if (!E->isGLValue()) return Owned(E); 550 551 QualType T = E->getType(); 552 assert(!T.isNull() && "r-value conversion on typeless expression?"); 553 554 // We don't want to throw lvalue-to-rvalue casts on top of 555 // expressions of certain types in C++. 556 if (getLangOpts().CPlusPlus && 557 (E->getType() == Context.OverloadTy || 558 T->isDependentType() || 559 T->isRecordType())) 560 return Owned(E); 561 562 // The C standard is actually really unclear on this point, and 563 // DR106 tells us what the result should be but not why. It's 564 // generally best to say that void types just doesn't undergo 565 // lvalue-to-rvalue at all. Note that expressions of unqualified 566 // 'void' type are never l-values, but qualified void can be. 567 if (T->isVoidType()) 568 return Owned(E); 569 570 // OpenCL usually rejects direct accesses to values of 'half' type. 571 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 572 T->isHalfType()) { 573 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 574 << 0 << T; 575 return ExprError(); 576 } 577 578 CheckForNullPointerDereference(*this, E); 579 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 580 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 581 &Context.Idents.get("object_getClass"), 582 SourceLocation(), LookupOrdinaryName); 583 if (ObjectGetClass) 584 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 585 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 586 FixItHint::CreateReplacement( 587 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 588 else 589 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 590 } 591 else if (const ObjCIvarRefExpr *OIRE = 592 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 593 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/0); 594 595 // C++ [conv.lval]p1: 596 // [...] If T is a non-class type, the type of the prvalue is the 597 // cv-unqualified version of T. Otherwise, the type of the 598 // rvalue is T. 599 // 600 // C99 6.3.2.1p2: 601 // If the lvalue has qualified type, the value has the unqualified 602 // version of the type of the lvalue; otherwise, the value has the 603 // type of the lvalue. 604 if (T.hasQualifiers()) 605 T = T.getUnqualifiedType(); 606 607 UpdateMarkingForLValueToRValue(E); 608 609 // Loading a __weak object implicitly retains the value, so we need a cleanup to 610 // balance that. 611 if (getLangOpts().ObjCAutoRefCount && 612 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 613 ExprNeedsCleanups = true; 614 615 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, 616 E, 0, VK_RValue)); 617 618 // C11 6.3.2.1p2: 619 // ... if the lvalue has atomic type, the value has the non-atomic version 620 // of the type of the lvalue ... 621 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 622 T = Atomic->getValueType().getUnqualifiedType(); 623 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, 624 Res.get(), 0, VK_RValue)); 625 } 626 627 return Res; 628 } 629 630 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 631 ExprResult Res = DefaultFunctionArrayConversion(E); 632 if (Res.isInvalid()) 633 return ExprError(); 634 Res = DefaultLvalueConversion(Res.take()); 635 if (Res.isInvalid()) 636 return ExprError(); 637 return Res; 638 } 639 640 /// CallExprUnaryConversions - a special case of an unary conversion 641 /// performed on a function designator of a call expression. 642 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 643 QualType Ty = E->getType(); 644 ExprResult Res = E; 645 // Only do implicit cast for a function type, but not for a pointer 646 // to function type. 647 if (Ty->isFunctionType()) { 648 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 649 CK_FunctionToPointerDecay).take(); 650 if (Res.isInvalid()) 651 return ExprError(); 652 } 653 Res = DefaultLvalueConversion(Res.take()); 654 if (Res.isInvalid()) 655 return ExprError(); 656 return Owned(Res.take()); 657 } 658 659 /// UsualUnaryConversions - Performs various conversions that are common to most 660 /// operators (C99 6.3). The conversions of array and function types are 661 /// sometimes suppressed. For example, the array->pointer conversion doesn't 662 /// apply if the array is an argument to the sizeof or address (&) operators. 663 /// In these instances, this routine should *not* be called. 664 ExprResult Sema::UsualUnaryConversions(Expr *E) { 665 // First, convert to an r-value. 666 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 667 if (Res.isInvalid()) 668 return ExprError(); 669 E = Res.take(); 670 671 QualType Ty = E->getType(); 672 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 673 674 // Half FP have to be promoted to float unless it is natively supported 675 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 676 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast); 677 678 // Try to perform integral promotions if the object has a theoretically 679 // promotable type. 680 if (Ty->isIntegralOrUnscopedEnumerationType()) { 681 // C99 6.3.1.1p2: 682 // 683 // The following may be used in an expression wherever an int or 684 // unsigned int may be used: 685 // - an object or expression with an integer type whose integer 686 // conversion rank is less than or equal to the rank of int 687 // and unsigned int. 688 // - A bit-field of type _Bool, int, signed int, or unsigned int. 689 // 690 // If an int can represent all values of the original type, the 691 // value is converted to an int; otherwise, it is converted to an 692 // unsigned int. These are called the integer promotions. All 693 // other types are unchanged by the integer promotions. 694 695 QualType PTy = Context.isPromotableBitField(E); 696 if (!PTy.isNull()) { 697 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take(); 698 return Owned(E); 699 } 700 if (Ty->isPromotableIntegerType()) { 701 QualType PT = Context.getPromotedIntegerType(Ty); 702 E = ImpCastExprToType(E, PT, CK_IntegralCast).take(); 703 return Owned(E); 704 } 705 } 706 return Owned(E); 707 } 708 709 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 710 /// do not have a prototype. Arguments that have type float or __fp16 711 /// are promoted to double. All other argument types are converted by 712 /// UsualUnaryConversions(). 713 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 714 QualType Ty = E->getType(); 715 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 716 717 ExprResult Res = UsualUnaryConversions(E); 718 if (Res.isInvalid()) 719 return ExprError(); 720 E = Res.take(); 721 722 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 723 // double. 724 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 725 if (BTy && (BTy->getKind() == BuiltinType::Half || 726 BTy->getKind() == BuiltinType::Float)) 727 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take(); 728 729 // C++ performs lvalue-to-rvalue conversion as a default argument 730 // promotion, even on class types, but note: 731 // C++11 [conv.lval]p2: 732 // When an lvalue-to-rvalue conversion occurs in an unevaluated 733 // operand or a subexpression thereof the value contained in the 734 // referenced object is not accessed. Otherwise, if the glvalue 735 // has a class type, the conversion copy-initializes a temporary 736 // of type T from the glvalue and the result of the conversion 737 // is a prvalue for the temporary. 738 // FIXME: add some way to gate this entire thing for correctness in 739 // potentially potentially evaluated contexts. 740 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 741 ExprResult Temp = PerformCopyInitialization( 742 InitializedEntity::InitializeTemporary(E->getType()), 743 E->getExprLoc(), 744 Owned(E)); 745 if (Temp.isInvalid()) 746 return ExprError(); 747 E = Temp.get(); 748 } 749 750 return Owned(E); 751 } 752 753 /// Determine the degree of POD-ness for an expression. 754 /// Incomplete types are considered POD, since this check can be performed 755 /// when we're in an unevaluated context. 756 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 757 if (Ty->isIncompleteType()) { 758 // C++11 [expr.call]p7: 759 // After these conversions, if the argument does not have arithmetic, 760 // enumeration, pointer, pointer to member, or class type, the program 761 // is ill-formed. 762 // 763 // Since we've already performed array-to-pointer and function-to-pointer 764 // decay, the only such type in C++ is cv void. This also handles 765 // initializer lists as variadic arguments. 766 if (Ty->isVoidType()) 767 return VAK_Invalid; 768 769 if (Ty->isObjCObjectType()) 770 return VAK_Invalid; 771 return VAK_Valid; 772 } 773 774 if (Ty.isCXX98PODType(Context)) 775 return VAK_Valid; 776 777 // C++11 [expr.call]p7: 778 // Passing a potentially-evaluated argument of class type (Clause 9) 779 // having a non-trivial copy constructor, a non-trivial move constructor, 780 // or a non-trivial destructor, with no corresponding parameter, 781 // is conditionally-supported with implementation-defined semantics. 782 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 783 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 784 if (!Record->hasNonTrivialCopyConstructor() && 785 !Record->hasNonTrivialMoveConstructor() && 786 !Record->hasNonTrivialDestructor()) 787 return VAK_ValidInCXX11; 788 789 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 790 return VAK_Valid; 791 792 if (Ty->isObjCObjectType()) 793 return VAK_Invalid; 794 795 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 796 // permitted to reject them. We should consider doing so. 797 return VAK_Undefined; 798 } 799 800 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 801 // Don't allow one to pass an Objective-C interface to a vararg. 802 const QualType &Ty = E->getType(); 803 VarArgKind VAK = isValidVarArgType(Ty); 804 805 // Complain about passing non-POD types through varargs. 806 switch (VAK) { 807 case VAK_ValidInCXX11: 808 DiagRuntimeBehavior( 809 E->getLocStart(), 0, 810 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 811 << Ty << CT); 812 // Fall through. 813 case VAK_Valid: 814 if (Ty->isRecordType()) { 815 // This is unlikely to be what the user intended. If the class has a 816 // 'c_str' member function, the user probably meant to call that. 817 DiagRuntimeBehavior(E->getLocStart(), 0, 818 PDiag(diag::warn_pass_class_arg_to_vararg) 819 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 820 } 821 break; 822 823 case VAK_Undefined: 824 DiagRuntimeBehavior( 825 E->getLocStart(), 0, 826 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 827 << getLangOpts().CPlusPlus11 << Ty << CT); 828 break; 829 830 case VAK_Invalid: 831 if (Ty->isObjCObjectType()) 832 DiagRuntimeBehavior( 833 E->getLocStart(), 0, 834 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 835 << Ty << CT); 836 else 837 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 838 << isa<InitListExpr>(E) << Ty << CT; 839 break; 840 } 841 } 842 843 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 844 /// will create a trap if the resulting type is not a POD type. 845 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 846 FunctionDecl *FDecl) { 847 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 848 // Strip the unbridged-cast placeholder expression off, if applicable. 849 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 850 (CT == VariadicMethod || 851 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 852 E = stripARCUnbridgedCast(E); 853 854 // Otherwise, do normal placeholder checking. 855 } else { 856 ExprResult ExprRes = CheckPlaceholderExpr(E); 857 if (ExprRes.isInvalid()) 858 return ExprError(); 859 E = ExprRes.take(); 860 } 861 } 862 863 ExprResult ExprRes = DefaultArgumentPromotion(E); 864 if (ExprRes.isInvalid()) 865 return ExprError(); 866 E = ExprRes.take(); 867 868 // Diagnostics regarding non-POD argument types are 869 // emitted along with format string checking in Sema::CheckFunctionCall(). 870 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 871 // Turn this into a trap. 872 CXXScopeSpec SS; 873 SourceLocation TemplateKWLoc; 874 UnqualifiedId Name; 875 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 876 E->getLocStart()); 877 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 878 Name, true, false); 879 if (TrapFn.isInvalid()) 880 return ExprError(); 881 882 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 883 E->getLocStart(), None, 884 E->getLocEnd()); 885 if (Call.isInvalid()) 886 return ExprError(); 887 888 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 889 Call.get(), E); 890 if (Comma.isInvalid()) 891 return ExprError(); 892 return Comma.get(); 893 } 894 895 if (!getLangOpts().CPlusPlus && 896 RequireCompleteType(E->getExprLoc(), E->getType(), 897 diag::err_call_incomplete_argument)) 898 return ExprError(); 899 900 return Owned(E); 901 } 902 903 /// \brief Converts an integer to complex float type. Helper function of 904 /// UsualArithmeticConversions() 905 /// 906 /// \return false if the integer expression is an integer type and is 907 /// successfully converted to the complex type. 908 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 909 ExprResult &ComplexExpr, 910 QualType IntTy, 911 QualType ComplexTy, 912 bool SkipCast) { 913 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 914 if (SkipCast) return false; 915 if (IntTy->isIntegerType()) { 916 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 917 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating); 918 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 919 CK_FloatingRealToComplex); 920 } else { 921 assert(IntTy->isComplexIntegerType()); 922 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy, 923 CK_IntegralComplexToFloatingComplex); 924 } 925 return false; 926 } 927 928 /// \brief Takes two complex float types and converts them to the same type. 929 /// Helper function of UsualArithmeticConversions() 930 static QualType 931 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS, 932 ExprResult &RHS, QualType LHSType, 933 QualType RHSType, 934 bool IsCompAssign) { 935 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 936 937 if (order < 0) { 938 // _Complex float -> _Complex double 939 if (!IsCompAssign) 940 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast); 941 return RHSType; 942 } 943 if (order > 0) 944 // _Complex float -> _Complex double 945 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast); 946 return LHSType; 947 } 948 949 /// \brief Converts otherExpr to complex float and promotes complexExpr if 950 /// necessary. Helper function of UsualArithmeticConversions() 951 static QualType handleOtherComplexFloatConversion(Sema &S, 952 ExprResult &ComplexExpr, 953 ExprResult &OtherExpr, 954 QualType ComplexTy, 955 QualType OtherTy, 956 bool ConvertComplexExpr, 957 bool ConvertOtherExpr) { 958 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy); 959 960 // If just the complexExpr is complex, the otherExpr needs to be converted, 961 // and the complexExpr might need to be promoted. 962 if (order > 0) { // complexExpr is wider 963 // float -> _Complex double 964 if (ConvertOtherExpr) { 965 QualType fp = cast<ComplexType>(ComplexTy)->getElementType(); 966 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast); 967 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy, 968 CK_FloatingRealToComplex); 969 } 970 return ComplexTy; 971 } 972 973 // otherTy is at least as wide. Find its corresponding complex type. 974 QualType result = (order == 0 ? ComplexTy : 975 S.Context.getComplexType(OtherTy)); 976 977 // double -> _Complex double 978 if (ConvertOtherExpr) 979 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result, 980 CK_FloatingRealToComplex); 981 982 // _Complex float -> _Complex double 983 if (ConvertComplexExpr && order < 0) 984 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result, 985 CK_FloatingComplexCast); 986 987 return result; 988 } 989 990 /// \brief Handle arithmetic conversion with complex types. Helper function of 991 /// UsualArithmeticConversions() 992 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 993 ExprResult &RHS, QualType LHSType, 994 QualType RHSType, 995 bool IsCompAssign) { 996 // if we have an integer operand, the result is the complex type. 997 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 998 /*skipCast*/false)) 999 return LHSType; 1000 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1001 /*skipCast*/IsCompAssign)) 1002 return RHSType; 1003 1004 // This handles complex/complex, complex/float, or float/complex. 1005 // When both operands are complex, the shorter operand is converted to the 1006 // type of the longer, and that is the type of the result. This corresponds 1007 // to what is done when combining two real floating-point operands. 1008 // The fun begins when size promotion occur across type domains. 1009 // From H&S 6.3.4: When one operand is complex and the other is a real 1010 // floating-point type, the less precise type is converted, within it's 1011 // real or complex domain, to the precision of the other type. For example, 1012 // when combining a "long double" with a "double _Complex", the 1013 // "double _Complex" is promoted to "long double _Complex". 1014 1015 bool LHSComplexFloat = LHSType->isComplexType(); 1016 bool RHSComplexFloat = RHSType->isComplexType(); 1017 1018 // If both are complex, just cast to the more precise type. 1019 if (LHSComplexFloat && RHSComplexFloat) 1020 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS, 1021 LHSType, RHSType, 1022 IsCompAssign); 1023 1024 // If only one operand is complex, promote it if necessary and convert the 1025 // other operand to complex. 1026 if (LHSComplexFloat) 1027 return handleOtherComplexFloatConversion( 1028 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign, 1029 /*convertOtherExpr*/ true); 1030 1031 assert(RHSComplexFloat); 1032 return handleOtherComplexFloatConversion( 1033 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true, 1034 /*convertOtherExpr*/ !IsCompAssign); 1035 } 1036 1037 /// \brief Hande arithmetic conversion from integer to float. Helper function 1038 /// of UsualArithmeticConversions() 1039 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1040 ExprResult &IntExpr, 1041 QualType FloatTy, QualType IntTy, 1042 bool ConvertFloat, bool ConvertInt) { 1043 if (IntTy->isIntegerType()) { 1044 if (ConvertInt) 1045 // Convert intExpr to the lhs floating point type. 1046 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy, 1047 CK_IntegralToFloating); 1048 return FloatTy; 1049 } 1050 1051 // Convert both sides to the appropriate complex float. 1052 assert(IntTy->isComplexIntegerType()); 1053 QualType result = S.Context.getComplexType(FloatTy); 1054 1055 // _Complex int -> _Complex float 1056 if (ConvertInt) 1057 IntExpr = S.ImpCastExprToType(IntExpr.take(), result, 1058 CK_IntegralComplexToFloatingComplex); 1059 1060 // float -> _Complex float 1061 if (ConvertFloat) 1062 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result, 1063 CK_FloatingRealToComplex); 1064 1065 return result; 1066 } 1067 1068 /// \brief Handle arithmethic conversion with floating point types. Helper 1069 /// function of UsualArithmeticConversions() 1070 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1071 ExprResult &RHS, QualType LHSType, 1072 QualType RHSType, bool IsCompAssign) { 1073 bool LHSFloat = LHSType->isRealFloatingType(); 1074 bool RHSFloat = RHSType->isRealFloatingType(); 1075 1076 // If we have two real floating types, convert the smaller operand 1077 // to the bigger result. 1078 if (LHSFloat && RHSFloat) { 1079 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1080 if (order > 0) { 1081 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast); 1082 return LHSType; 1083 } 1084 1085 assert(order < 0 && "illegal float comparison"); 1086 if (!IsCompAssign) 1087 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast); 1088 return RHSType; 1089 } 1090 1091 if (LHSFloat) 1092 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1093 /*convertFloat=*/!IsCompAssign, 1094 /*convertInt=*/ true); 1095 assert(RHSFloat); 1096 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1097 /*convertInt=*/ true, 1098 /*convertFloat=*/!IsCompAssign); 1099 } 1100 1101 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1102 1103 namespace { 1104 /// These helper callbacks are placed in an anonymous namespace to 1105 /// permit their use as function template parameters. 1106 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1107 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1108 } 1109 1110 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1111 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1112 CK_IntegralComplexCast); 1113 } 1114 } 1115 1116 /// \brief Handle integer arithmetic conversions. Helper function of 1117 /// UsualArithmeticConversions() 1118 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1119 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1120 ExprResult &RHS, QualType LHSType, 1121 QualType RHSType, bool IsCompAssign) { 1122 // The rules for this case are in C99 6.3.1.8 1123 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1124 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1125 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1126 if (LHSSigned == RHSSigned) { 1127 // Same signedness; use the higher-ranked type 1128 if (order >= 0) { 1129 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1130 return LHSType; 1131 } else if (!IsCompAssign) 1132 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1133 return RHSType; 1134 } else if (order != (LHSSigned ? 1 : -1)) { 1135 // The unsigned type has greater than or equal rank to the 1136 // signed type, so use the unsigned type 1137 if (RHSSigned) { 1138 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1139 return LHSType; 1140 } else if (!IsCompAssign) 1141 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1142 return RHSType; 1143 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1144 // The two types are different widths; if we are here, that 1145 // means the signed type is larger than the unsigned type, so 1146 // use the signed type. 1147 if (LHSSigned) { 1148 RHS = (*doRHSCast)(S, RHS.take(), LHSType); 1149 return LHSType; 1150 } else if (!IsCompAssign) 1151 LHS = (*doLHSCast)(S, LHS.take(), RHSType); 1152 return RHSType; 1153 } else { 1154 // The signed type is higher-ranked than the unsigned type, 1155 // but isn't actually any bigger (like unsigned int and long 1156 // on most 32-bit systems). Use the unsigned type corresponding 1157 // to the signed type. 1158 QualType result = 1159 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1160 RHS = (*doRHSCast)(S, RHS.take(), result); 1161 if (!IsCompAssign) 1162 LHS = (*doLHSCast)(S, LHS.take(), result); 1163 return result; 1164 } 1165 } 1166 1167 /// \brief Handle conversions with GCC complex int extension. Helper function 1168 /// of UsualArithmeticConversions() 1169 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1170 ExprResult &RHS, QualType LHSType, 1171 QualType RHSType, 1172 bool IsCompAssign) { 1173 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1174 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1175 1176 if (LHSComplexInt && RHSComplexInt) { 1177 QualType LHSEltType = LHSComplexInt->getElementType(); 1178 QualType RHSEltType = RHSComplexInt->getElementType(); 1179 QualType ScalarType = 1180 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1181 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1182 1183 return S.Context.getComplexType(ScalarType); 1184 } 1185 1186 if (LHSComplexInt) { 1187 QualType LHSEltType = LHSComplexInt->getElementType(); 1188 QualType ScalarType = 1189 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1190 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1191 QualType ComplexType = S.Context.getComplexType(ScalarType); 1192 RHS = S.ImpCastExprToType(RHS.take(), ComplexType, 1193 CK_IntegralRealToComplex); 1194 1195 return ComplexType; 1196 } 1197 1198 assert(RHSComplexInt); 1199 1200 QualType RHSEltType = RHSComplexInt->getElementType(); 1201 QualType ScalarType = 1202 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1203 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1204 QualType ComplexType = S.Context.getComplexType(ScalarType); 1205 1206 if (!IsCompAssign) 1207 LHS = S.ImpCastExprToType(LHS.take(), ComplexType, 1208 CK_IntegralRealToComplex); 1209 return ComplexType; 1210 } 1211 1212 /// UsualArithmeticConversions - Performs various conversions that are common to 1213 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1214 /// routine returns the first non-arithmetic type found. The client is 1215 /// responsible for emitting appropriate error diagnostics. 1216 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1217 bool IsCompAssign) { 1218 if (!IsCompAssign) { 1219 LHS = UsualUnaryConversions(LHS.take()); 1220 if (LHS.isInvalid()) 1221 return QualType(); 1222 } 1223 1224 RHS = UsualUnaryConversions(RHS.take()); 1225 if (RHS.isInvalid()) 1226 return QualType(); 1227 1228 // For conversion purposes, we ignore any qualifiers. 1229 // For example, "const float" and "float" are equivalent. 1230 QualType LHSType = 1231 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1232 QualType RHSType = 1233 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1234 1235 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1236 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1237 LHSType = AtomicLHS->getValueType(); 1238 1239 // If both types are identical, no conversion is needed. 1240 if (LHSType == RHSType) 1241 return LHSType; 1242 1243 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1244 // The caller can deal with this (e.g. pointer + int). 1245 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1246 return QualType(); 1247 1248 // Apply unary and bitfield promotions to the LHS's type. 1249 QualType LHSUnpromotedType = LHSType; 1250 if (LHSType->isPromotableIntegerType()) 1251 LHSType = Context.getPromotedIntegerType(LHSType); 1252 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1253 if (!LHSBitfieldPromoteTy.isNull()) 1254 LHSType = LHSBitfieldPromoteTy; 1255 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1256 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast); 1257 1258 // If both types are identical, no conversion is needed. 1259 if (LHSType == RHSType) 1260 return LHSType; 1261 1262 // At this point, we have two different arithmetic types. 1263 1264 // Handle complex types first (C99 6.3.1.8p1). 1265 if (LHSType->isComplexType() || RHSType->isComplexType()) 1266 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1267 IsCompAssign); 1268 1269 // Now handle "real" floating types (i.e. float, double, long double). 1270 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1271 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1272 IsCompAssign); 1273 1274 // Handle GCC complex int extension. 1275 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1276 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1277 IsCompAssign); 1278 1279 // Finally, we have two differing integer types. 1280 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1281 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1282 } 1283 1284 1285 //===----------------------------------------------------------------------===// 1286 // Semantic Analysis for various Expression Types 1287 //===----------------------------------------------------------------------===// 1288 1289 1290 ExprResult 1291 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1292 SourceLocation DefaultLoc, 1293 SourceLocation RParenLoc, 1294 Expr *ControllingExpr, 1295 ArrayRef<ParsedType> ArgTypes, 1296 ArrayRef<Expr *> ArgExprs) { 1297 unsigned NumAssocs = ArgTypes.size(); 1298 assert(NumAssocs == ArgExprs.size()); 1299 1300 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1301 for (unsigned i = 0; i < NumAssocs; ++i) { 1302 if (ArgTypes[i]) 1303 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1304 else 1305 Types[i] = 0; 1306 } 1307 1308 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1309 ControllingExpr, 1310 llvm::makeArrayRef(Types, NumAssocs), 1311 ArgExprs); 1312 delete [] Types; 1313 return ER; 1314 } 1315 1316 ExprResult 1317 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1318 SourceLocation DefaultLoc, 1319 SourceLocation RParenLoc, 1320 Expr *ControllingExpr, 1321 ArrayRef<TypeSourceInfo *> Types, 1322 ArrayRef<Expr *> Exprs) { 1323 unsigned NumAssocs = Types.size(); 1324 assert(NumAssocs == Exprs.size()); 1325 if (ControllingExpr->getType()->isPlaceholderType()) { 1326 ExprResult result = CheckPlaceholderExpr(ControllingExpr); 1327 if (result.isInvalid()) return ExprError(); 1328 ControllingExpr = result.take(); 1329 } 1330 1331 bool TypeErrorFound = false, 1332 IsResultDependent = ControllingExpr->isTypeDependent(), 1333 ContainsUnexpandedParameterPack 1334 = ControllingExpr->containsUnexpandedParameterPack(); 1335 1336 for (unsigned i = 0; i < NumAssocs; ++i) { 1337 if (Exprs[i]->containsUnexpandedParameterPack()) 1338 ContainsUnexpandedParameterPack = true; 1339 1340 if (Types[i]) { 1341 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1342 ContainsUnexpandedParameterPack = true; 1343 1344 if (Types[i]->getType()->isDependentType()) { 1345 IsResultDependent = true; 1346 } else { 1347 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1348 // complete object type other than a variably modified type." 1349 unsigned D = 0; 1350 if (Types[i]->getType()->isIncompleteType()) 1351 D = diag::err_assoc_type_incomplete; 1352 else if (!Types[i]->getType()->isObjectType()) 1353 D = diag::err_assoc_type_nonobject; 1354 else if (Types[i]->getType()->isVariablyModifiedType()) 1355 D = diag::err_assoc_type_variably_modified; 1356 1357 if (D != 0) { 1358 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1359 << Types[i]->getTypeLoc().getSourceRange() 1360 << Types[i]->getType(); 1361 TypeErrorFound = true; 1362 } 1363 1364 // C11 6.5.1.1p2 "No two generic associations in the same generic 1365 // selection shall specify compatible types." 1366 for (unsigned j = i+1; j < NumAssocs; ++j) 1367 if (Types[j] && !Types[j]->getType()->isDependentType() && 1368 Context.typesAreCompatible(Types[i]->getType(), 1369 Types[j]->getType())) { 1370 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1371 diag::err_assoc_compatible_types) 1372 << Types[j]->getTypeLoc().getSourceRange() 1373 << Types[j]->getType() 1374 << Types[i]->getType(); 1375 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1376 diag::note_compat_assoc) 1377 << Types[i]->getTypeLoc().getSourceRange() 1378 << Types[i]->getType(); 1379 TypeErrorFound = true; 1380 } 1381 } 1382 } 1383 } 1384 if (TypeErrorFound) 1385 return ExprError(); 1386 1387 // If we determined that the generic selection is result-dependent, don't 1388 // try to compute the result expression. 1389 if (IsResultDependent) 1390 return Owned(new (Context) GenericSelectionExpr( 1391 Context, KeyLoc, ControllingExpr, 1392 Types, Exprs, 1393 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack)); 1394 1395 SmallVector<unsigned, 1> CompatIndices; 1396 unsigned DefaultIndex = -1U; 1397 for (unsigned i = 0; i < NumAssocs; ++i) { 1398 if (!Types[i]) 1399 DefaultIndex = i; 1400 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1401 Types[i]->getType())) 1402 CompatIndices.push_back(i); 1403 } 1404 1405 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1406 // type compatible with at most one of the types named in its generic 1407 // association list." 1408 if (CompatIndices.size() > 1) { 1409 // We strip parens here because the controlling expression is typically 1410 // parenthesized in macro definitions. 1411 ControllingExpr = ControllingExpr->IgnoreParens(); 1412 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1413 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1414 << (unsigned) CompatIndices.size(); 1415 for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(), 1416 E = CompatIndices.end(); I != E; ++I) { 1417 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1418 diag::note_compat_assoc) 1419 << Types[*I]->getTypeLoc().getSourceRange() 1420 << Types[*I]->getType(); 1421 } 1422 return ExprError(); 1423 } 1424 1425 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1426 // its controlling expression shall have type compatible with exactly one of 1427 // the types named in its generic association list." 1428 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1429 // We strip parens here because the controlling expression is typically 1430 // parenthesized in macro definitions. 1431 ControllingExpr = ControllingExpr->IgnoreParens(); 1432 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1433 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1434 return ExprError(); 1435 } 1436 1437 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1438 // type name that is compatible with the type of the controlling expression, 1439 // then the result expression of the generic selection is the expression 1440 // in that generic association. Otherwise, the result expression of the 1441 // generic selection is the expression in the default generic association." 1442 unsigned ResultIndex = 1443 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1444 1445 return Owned(new (Context) GenericSelectionExpr( 1446 Context, KeyLoc, ControllingExpr, 1447 Types, Exprs, 1448 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack, 1449 ResultIndex)); 1450 } 1451 1452 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1453 /// location of the token and the offset of the ud-suffix within it. 1454 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1455 unsigned Offset) { 1456 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1457 S.getLangOpts()); 1458 } 1459 1460 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1461 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1462 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1463 IdentifierInfo *UDSuffix, 1464 SourceLocation UDSuffixLoc, 1465 ArrayRef<Expr*> Args, 1466 SourceLocation LitEndLoc) { 1467 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1468 1469 QualType ArgTy[2]; 1470 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1471 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1472 if (ArgTy[ArgIdx]->isArrayType()) 1473 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1474 } 1475 1476 DeclarationName OpName = 1477 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1478 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1479 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1480 1481 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1482 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1483 /*AllowRaw*/false, /*AllowTemplate*/false, 1484 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1485 return ExprError(); 1486 1487 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1488 } 1489 1490 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1491 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1492 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1493 /// multiple tokens. However, the common case is that StringToks points to one 1494 /// string. 1495 /// 1496 ExprResult 1497 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks, 1498 Scope *UDLScope) { 1499 assert(NumStringToks && "Must have at least one string!"); 1500 1501 StringLiteralParser Literal(StringToks, NumStringToks, PP); 1502 if (Literal.hadError) 1503 return ExprError(); 1504 1505 SmallVector<SourceLocation, 4> StringTokLocs; 1506 for (unsigned i = 0; i != NumStringToks; ++i) 1507 StringTokLocs.push_back(StringToks[i].getLocation()); 1508 1509 QualType CharTy = Context.CharTy; 1510 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1511 if (Literal.isWide()) { 1512 CharTy = Context.getWideCharType(); 1513 Kind = StringLiteral::Wide; 1514 } else if (Literal.isUTF8()) { 1515 Kind = StringLiteral::UTF8; 1516 } else if (Literal.isUTF16()) { 1517 CharTy = Context.Char16Ty; 1518 Kind = StringLiteral::UTF16; 1519 } else if (Literal.isUTF32()) { 1520 CharTy = Context.Char32Ty; 1521 Kind = StringLiteral::UTF32; 1522 } else if (Literal.isPascal()) { 1523 CharTy = Context.UnsignedCharTy; 1524 } 1525 1526 QualType CharTyConst = CharTy; 1527 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1528 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1529 CharTyConst.addConst(); 1530 1531 // Get an array type for the string, according to C99 6.4.5. This includes 1532 // the nul terminator character as well as the string length for pascal 1533 // strings. 1534 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1535 llvm::APInt(32, Literal.GetNumStringChars()+1), 1536 ArrayType::Normal, 0); 1537 1538 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1539 if (getLangOpts().OpenCL) { 1540 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1541 } 1542 1543 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1544 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1545 Kind, Literal.Pascal, StrTy, 1546 &StringTokLocs[0], 1547 StringTokLocs.size()); 1548 if (Literal.getUDSuffix().empty()) 1549 return Owned(Lit); 1550 1551 // We're building a user-defined literal. 1552 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1553 SourceLocation UDSuffixLoc = 1554 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1555 Literal.getUDSuffixOffset()); 1556 1557 // Make sure we're allowed user-defined literals here. 1558 if (!UDLScope) 1559 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1560 1561 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1562 // operator "" X (str, len) 1563 QualType SizeType = Context.getSizeType(); 1564 1565 DeclarationName OpName = 1566 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1567 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1568 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1569 1570 QualType ArgTy[] = { 1571 Context.getArrayDecayedType(StrTy), SizeType 1572 }; 1573 1574 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1575 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1576 /*AllowRaw*/false, /*AllowTemplate*/false, 1577 /*AllowStringTemplate*/true)) { 1578 1579 case LOLR_Cooked: { 1580 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1581 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1582 StringTokLocs[0]); 1583 Expr *Args[] = { Lit, LenArg }; 1584 1585 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1586 } 1587 1588 case LOLR_StringTemplate: { 1589 TemplateArgumentListInfo ExplicitArgs; 1590 1591 unsigned CharBits = Context.getIntWidth(CharTy); 1592 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1593 llvm::APSInt Value(CharBits, CharIsUnsigned); 1594 1595 TemplateArgument TypeArg(CharTy); 1596 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1597 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1598 1599 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1600 Value = Lit->getCodeUnit(I); 1601 TemplateArgument Arg(Context, Value, CharTy); 1602 TemplateArgumentLocInfo ArgInfo; 1603 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1604 } 1605 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1606 &ExplicitArgs); 1607 } 1608 case LOLR_Raw: 1609 case LOLR_Template: 1610 llvm_unreachable("unexpected literal operator lookup result"); 1611 case LOLR_Error: 1612 return ExprError(); 1613 } 1614 llvm_unreachable("unexpected literal operator lookup result"); 1615 } 1616 1617 ExprResult 1618 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1619 SourceLocation Loc, 1620 const CXXScopeSpec *SS) { 1621 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1622 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1623 } 1624 1625 /// BuildDeclRefExpr - Build an expression that references a 1626 /// declaration that does not require a closure capture. 1627 ExprResult 1628 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1629 const DeclarationNameInfo &NameInfo, 1630 const CXXScopeSpec *SS, NamedDecl *FoundD, 1631 const TemplateArgumentListInfo *TemplateArgs) { 1632 if (getLangOpts().CUDA) 1633 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1634 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1635 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller), 1636 CalleeTarget = IdentifyCUDATarget(Callee); 1637 if (CheckCUDATarget(CallerTarget, CalleeTarget)) { 1638 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1639 << CalleeTarget << D->getIdentifier() << CallerTarget; 1640 Diag(D->getLocation(), diag::note_previous_decl) 1641 << D->getIdentifier(); 1642 return ExprError(); 1643 } 1644 } 1645 1646 bool refersToEnclosingScope = 1647 (CurContext != D->getDeclContext() && 1648 D->getDeclContext()->isFunctionOrMethod()) || 1649 (isa<VarDecl>(D) && 1650 cast<VarDecl>(D)->isInitCapture()); 1651 1652 DeclRefExpr *E; 1653 if (isa<VarTemplateSpecializationDecl>(D)) { 1654 VarTemplateSpecializationDecl *VarSpec = 1655 cast<VarTemplateSpecializationDecl>(D); 1656 1657 E = DeclRefExpr::Create( 1658 Context, 1659 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(), 1660 VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope, 1661 NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs); 1662 } else { 1663 assert(!TemplateArgs && "No template arguments for non-variable" 1664 " template specialization references"); 1665 E = DeclRefExpr::Create( 1666 Context, 1667 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(), 1668 SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD); 1669 } 1670 1671 MarkDeclRefReferenced(E); 1672 1673 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) && 1674 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) { 1675 DiagnosticsEngine::Level Level = 1676 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 1677 E->getLocStart()); 1678 if (Level != DiagnosticsEngine::Ignored) 1679 recordUseOfEvaluatedWeak(E); 1680 } 1681 1682 // Just in case we're building an illegal pointer-to-member. 1683 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1684 if (FD && FD->isBitField()) 1685 E->setObjectKind(OK_BitField); 1686 1687 return Owned(E); 1688 } 1689 1690 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1691 /// possibly a list of template arguments. 1692 /// 1693 /// If this produces template arguments, it is permitted to call 1694 /// DecomposeTemplateName. 1695 /// 1696 /// This actually loses a lot of source location information for 1697 /// non-standard name kinds; we should consider preserving that in 1698 /// some way. 1699 void 1700 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1701 TemplateArgumentListInfo &Buffer, 1702 DeclarationNameInfo &NameInfo, 1703 const TemplateArgumentListInfo *&TemplateArgs) { 1704 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1705 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1706 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1707 1708 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1709 Id.TemplateId->NumArgs); 1710 translateTemplateArguments(TemplateArgsPtr, Buffer); 1711 1712 TemplateName TName = Id.TemplateId->Template.get(); 1713 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1714 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1715 TemplateArgs = &Buffer; 1716 } else { 1717 NameInfo = GetNameFromUnqualifiedId(Id); 1718 TemplateArgs = 0; 1719 } 1720 } 1721 1722 /// Diagnose an empty lookup. 1723 /// 1724 /// \return false if new lookup candidates were found 1725 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1726 CorrectionCandidateCallback &CCC, 1727 TemplateArgumentListInfo *ExplicitTemplateArgs, 1728 ArrayRef<Expr *> Args) { 1729 DeclarationName Name = R.getLookupName(); 1730 1731 unsigned diagnostic = diag::err_undeclared_var_use; 1732 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1733 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1734 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1735 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1736 diagnostic = diag::err_undeclared_use; 1737 diagnostic_suggest = diag::err_undeclared_use_suggest; 1738 } 1739 1740 // If the original lookup was an unqualified lookup, fake an 1741 // unqualified lookup. This is useful when (for example) the 1742 // original lookup would not have found something because it was a 1743 // dependent name. 1744 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty()) 1745 ? CurContext : 0; 1746 while (DC) { 1747 if (isa<CXXRecordDecl>(DC)) { 1748 LookupQualifiedName(R, DC); 1749 1750 if (!R.empty()) { 1751 // Don't give errors about ambiguities in this lookup. 1752 R.suppressDiagnostics(); 1753 1754 // During a default argument instantiation the CurContext points 1755 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1756 // function parameter list, hence add an explicit check. 1757 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1758 ActiveTemplateInstantiations.back().Kind == 1759 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1760 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1761 bool isInstance = CurMethod && 1762 CurMethod->isInstance() && 1763 DC == CurMethod->getParent() && !isDefaultArgument; 1764 1765 1766 // Give a code modification hint to insert 'this->'. 1767 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1768 // Actually quite difficult! 1769 if (getLangOpts().MSVCCompat) 1770 diagnostic = diag::warn_found_via_dependent_bases_lookup; 1771 if (isInstance) { 1772 Diag(R.getNameLoc(), diagnostic) << Name 1773 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1774 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 1775 CallsUndergoingInstantiation.back()->getCallee()); 1776 1777 CXXMethodDecl *DepMethod; 1778 if (CurMethod->isDependentContext()) 1779 DepMethod = CurMethod; 1780 else if (CurMethod->getTemplatedKind() == 1781 FunctionDecl::TK_FunctionTemplateSpecialization) 1782 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()-> 1783 getInstantiatedFromMemberTemplate()->getTemplatedDecl()); 1784 else 1785 DepMethod = cast<CXXMethodDecl>( 1786 CurMethod->getInstantiatedFromMemberFunction()); 1787 assert(DepMethod && "No template pattern found"); 1788 1789 QualType DepThisType = DepMethod->getThisType(Context); 1790 CheckCXXThisCapture(R.getNameLoc()); 1791 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 1792 R.getNameLoc(), DepThisType, false); 1793 TemplateArgumentListInfo TList; 1794 if (ULE->hasExplicitTemplateArgs()) 1795 ULE->copyTemplateArgumentsInto(TList); 1796 1797 CXXScopeSpec SS; 1798 SS.Adopt(ULE->getQualifierLoc()); 1799 CXXDependentScopeMemberExpr *DepExpr = 1800 CXXDependentScopeMemberExpr::Create( 1801 Context, DepThis, DepThisType, true, SourceLocation(), 1802 SS.getWithLocInContext(Context), 1803 ULE->getTemplateKeywordLoc(), 0, 1804 R.getLookupNameInfo(), 1805 ULE->hasExplicitTemplateArgs() ? &TList : 0); 1806 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 1807 } else { 1808 Diag(R.getNameLoc(), diagnostic) << Name; 1809 } 1810 1811 // Do we really want to note all of these? 1812 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1813 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1814 1815 // Return true if we are inside a default argument instantiation 1816 // and the found name refers to an instance member function, otherwise 1817 // the function calling DiagnoseEmptyLookup will try to create an 1818 // implicit member call and this is wrong for default argument. 1819 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1820 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1821 return true; 1822 } 1823 1824 // Tell the callee to try to recover. 1825 return false; 1826 } 1827 1828 R.clear(); 1829 } 1830 1831 // In Microsoft mode, if we are performing lookup from within a friend 1832 // function definition declared at class scope then we must set 1833 // DC to the lexical parent to be able to search into the parent 1834 // class. 1835 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1836 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1837 DC->getLexicalParent()->isRecord()) 1838 DC = DC->getLexicalParent(); 1839 else 1840 DC = DC->getParent(); 1841 } 1842 1843 // We didn't find anything, so try to correct for a typo. 1844 TypoCorrection Corrected; 1845 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 1846 S, &SS, CCC))) { 1847 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1848 bool DroppedSpecifier = 1849 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1850 R.setLookupName(Corrected.getCorrection()); 1851 1852 bool AcceptableWithRecovery = false; 1853 bool AcceptableWithoutRecovery = false; 1854 NamedDecl *ND = Corrected.getCorrectionDecl(); 1855 if (ND) { 1856 if (Corrected.isOverloaded()) { 1857 OverloadCandidateSet OCS(R.getNameLoc()); 1858 OverloadCandidateSet::iterator Best; 1859 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1860 CDEnd = Corrected.end(); 1861 CD != CDEnd; ++CD) { 1862 if (FunctionTemplateDecl *FTD = 1863 dyn_cast<FunctionTemplateDecl>(*CD)) 1864 AddTemplateOverloadCandidate( 1865 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1866 Args, OCS); 1867 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1868 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1869 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1870 Args, OCS); 1871 } 1872 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1873 case OR_Success: 1874 ND = Best->Function; 1875 Corrected.setCorrectionDecl(ND); 1876 break; 1877 default: 1878 // FIXME: Arbitrarily pick the first declaration for the note. 1879 Corrected.setCorrectionDecl(ND); 1880 break; 1881 } 1882 } 1883 R.addDecl(ND); 1884 1885 AcceptableWithRecovery = 1886 isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND); 1887 // FIXME: If we ended up with a typo for a type name or 1888 // Objective-C class name, we're in trouble because the parser 1889 // is in the wrong place to recover. Suggest the typo 1890 // correction, but don't make it a fix-it since we're not going 1891 // to recover well anyway. 1892 AcceptableWithoutRecovery = 1893 isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 1894 } else { 1895 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1896 // because we aren't able to recover. 1897 AcceptableWithoutRecovery = true; 1898 } 1899 1900 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1901 unsigned NoteID = (Corrected.getCorrectionDecl() && 1902 isa<ImplicitParamDecl>(Corrected.getCorrectionDecl())) 1903 ? diag::note_implicit_param_decl 1904 : diag::note_previous_decl; 1905 if (SS.isEmpty()) 1906 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1907 PDiag(NoteID), AcceptableWithRecovery); 1908 else 1909 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1910 << Name << computeDeclContext(SS, false) 1911 << DroppedSpecifier << SS.getRange(), 1912 PDiag(NoteID), AcceptableWithRecovery); 1913 1914 // Tell the callee whether to try to recover. 1915 return !AcceptableWithRecovery; 1916 } 1917 } 1918 R.clear(); 1919 1920 // Emit a special diagnostic for failed member lookups. 1921 // FIXME: computing the declaration context might fail here (?) 1922 if (!SS.isEmpty()) { 1923 Diag(R.getNameLoc(), diag::err_no_member) 1924 << Name << computeDeclContext(SS, false) 1925 << SS.getRange(); 1926 return true; 1927 } 1928 1929 // Give up, we can't recover. 1930 Diag(R.getNameLoc(), diagnostic) << Name; 1931 return true; 1932 } 1933 1934 ExprResult Sema::ActOnIdExpression(Scope *S, 1935 CXXScopeSpec &SS, 1936 SourceLocation TemplateKWLoc, 1937 UnqualifiedId &Id, 1938 bool HasTrailingLParen, 1939 bool IsAddressOfOperand, 1940 CorrectionCandidateCallback *CCC, 1941 bool IsInlineAsmIdentifier) { 1942 assert(!(IsAddressOfOperand && HasTrailingLParen) && 1943 "cannot be direct & operand and have a trailing lparen"); 1944 if (SS.isInvalid()) 1945 return ExprError(); 1946 1947 TemplateArgumentListInfo TemplateArgsBuffer; 1948 1949 // Decompose the UnqualifiedId into the following data. 1950 DeclarationNameInfo NameInfo; 1951 const TemplateArgumentListInfo *TemplateArgs; 1952 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 1953 1954 DeclarationName Name = NameInfo.getName(); 1955 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1956 SourceLocation NameLoc = NameInfo.getLoc(); 1957 1958 // C++ [temp.dep.expr]p3: 1959 // An id-expression is type-dependent if it contains: 1960 // -- an identifier that was declared with a dependent type, 1961 // (note: handled after lookup) 1962 // -- a template-id that is dependent, 1963 // (note: handled in BuildTemplateIdExpr) 1964 // -- a conversion-function-id that specifies a dependent type, 1965 // -- a nested-name-specifier that contains a class-name that 1966 // names a dependent type. 1967 // Determine whether this is a member of an unknown specialization; 1968 // we need to handle these differently. 1969 bool DependentID = false; 1970 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 1971 Name.getCXXNameType()->isDependentType()) { 1972 DependentID = true; 1973 } else if (SS.isSet()) { 1974 if (DeclContext *DC = computeDeclContext(SS, false)) { 1975 if (RequireCompleteDeclContext(SS, DC)) 1976 return ExprError(); 1977 } else { 1978 DependentID = true; 1979 } 1980 } 1981 1982 if (DependentID) 1983 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1984 IsAddressOfOperand, TemplateArgs); 1985 1986 // Perform the required lookup. 1987 LookupResult R(*this, NameInfo, 1988 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 1989 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 1990 if (TemplateArgs) { 1991 // Lookup the template name again to correctly establish the context in 1992 // which it was found. This is really unfortunate as we already did the 1993 // lookup to determine that it was a template name in the first place. If 1994 // this becomes a performance hit, we can work harder to preserve those 1995 // results until we get here but it's likely not worth it. 1996 bool MemberOfUnknownSpecialization; 1997 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 1998 MemberOfUnknownSpecialization); 1999 2000 if (MemberOfUnknownSpecialization || 2001 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2002 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2003 IsAddressOfOperand, TemplateArgs); 2004 } else { 2005 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2006 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2007 2008 // If the result might be in a dependent base class, this is a dependent 2009 // id-expression. 2010 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2011 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2012 IsAddressOfOperand, TemplateArgs); 2013 2014 // If this reference is in an Objective-C method, then we need to do 2015 // some special Objective-C lookup, too. 2016 if (IvarLookupFollowUp) { 2017 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2018 if (E.isInvalid()) 2019 return ExprError(); 2020 2021 if (Expr *Ex = E.takeAs<Expr>()) 2022 return Owned(Ex); 2023 } 2024 } 2025 2026 if (R.isAmbiguous()) 2027 return ExprError(); 2028 2029 // Determine whether this name might be a candidate for 2030 // argument-dependent lookup. 2031 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2032 2033 if (R.empty() && !ADL) { 2034 2035 // Otherwise, this could be an implicitly declared function reference (legal 2036 // in C90, extension in C99, forbidden in C++). 2037 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2038 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2039 if (D) R.addDecl(D); 2040 } 2041 2042 // If this name wasn't predeclared and if this is not a function 2043 // call, diagnose the problem. 2044 if (R.empty()) { 2045 // In Microsoft mode, if we are inside a template class member function 2046 // whose parent class has dependent base classes, and we can't resolve 2047 // an unqualified identifier, then assume the identifier is a member of a 2048 // dependent base class. The goal is to postpone name lookup to 2049 // instantiation time to be able to search into the type dependent base 2050 // classes. 2051 // FIXME: If we want 100% compatibility with MSVC, we will have delay all 2052 // unqualified name lookup. Any name lookup during template parsing means 2053 // clang might find something that MSVC doesn't. For now, we only handle 2054 // the common case of members of a dependent base class. 2055 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2056 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext); 2057 if (MD && MD->isInstance() && MD->getParent()->hasAnyDependentBases()) { 2058 QualType ThisType = MD->getThisType(Context); 2059 // Since the 'this' expression is synthesized, we don't need to 2060 // perform the double-lookup check. 2061 NamedDecl *FirstQualifierInScope = 0; 2062 return Owned(CXXDependentScopeMemberExpr::Create( 2063 Context, /*This=*/0, ThisType, /*IsArrow=*/true, 2064 /*Op=*/SourceLocation(), SS.getWithLocInContext(Context), 2065 TemplateKWLoc, FirstQualifierInScope, NameInfo, TemplateArgs)); 2066 } 2067 } 2068 2069 // Don't diagnose an empty lookup for inline assmebly. 2070 if (IsInlineAsmIdentifier) 2071 return ExprError(); 2072 2073 CorrectionCandidateCallback DefaultValidator; 2074 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator)) 2075 return ExprError(); 2076 2077 assert(!R.empty() && 2078 "DiagnoseEmptyLookup returned false but added no results"); 2079 2080 // If we found an Objective-C instance variable, let 2081 // LookupInObjCMethod build the appropriate expression to 2082 // reference the ivar. 2083 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2084 R.clear(); 2085 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2086 // In a hopelessly buggy code, Objective-C instance variable 2087 // lookup fails and no expression will be built to reference it. 2088 if (!E.isInvalid() && !E.get()) 2089 return ExprError(); 2090 return E; 2091 } 2092 } 2093 } 2094 2095 // This is guaranteed from this point on. 2096 assert(!R.empty() || ADL); 2097 2098 // Check whether this might be a C++ implicit instance member access. 2099 // C++ [class.mfct.non-static]p3: 2100 // When an id-expression that is not part of a class member access 2101 // syntax and not used to form a pointer to member is used in the 2102 // body of a non-static member function of class X, if name lookup 2103 // resolves the name in the id-expression to a non-static non-type 2104 // member of some class C, the id-expression is transformed into a 2105 // class member access expression using (*this) as the 2106 // postfix-expression to the left of the . operator. 2107 // 2108 // But we don't actually need to do this for '&' operands if R 2109 // resolved to a function or overloaded function set, because the 2110 // expression is ill-formed if it actually works out to be a 2111 // non-static member function: 2112 // 2113 // C++ [expr.ref]p4: 2114 // Otherwise, if E1.E2 refers to a non-static member function. . . 2115 // [t]he expression can be used only as the left-hand operand of a 2116 // member function call. 2117 // 2118 // There are other safeguards against such uses, but it's important 2119 // to get this right here so that we don't end up making a 2120 // spuriously dependent expression if we're inside a dependent 2121 // instance method. 2122 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2123 bool MightBeImplicitMember; 2124 if (!IsAddressOfOperand) 2125 MightBeImplicitMember = true; 2126 else if (!SS.isEmpty()) 2127 MightBeImplicitMember = false; 2128 else if (R.isOverloadedResult()) 2129 MightBeImplicitMember = false; 2130 else if (R.isUnresolvableResult()) 2131 MightBeImplicitMember = true; 2132 else 2133 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2134 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2135 isa<MSPropertyDecl>(R.getFoundDecl()); 2136 2137 if (MightBeImplicitMember) 2138 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2139 R, TemplateArgs); 2140 } 2141 2142 if (TemplateArgs || TemplateKWLoc.isValid()) { 2143 2144 // In C++1y, if this is a variable template id, then check it 2145 // in BuildTemplateIdExpr(). 2146 // The single lookup result must be a variable template declaration. 2147 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2148 Id.TemplateId->Kind == TNK_Var_template) { 2149 assert(R.getAsSingle<VarTemplateDecl>() && 2150 "There should only be one declaration found."); 2151 } 2152 2153 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2154 } 2155 2156 return BuildDeclarationNameExpr(SS, R, ADL); 2157 } 2158 2159 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2160 /// declaration name, generally during template instantiation. 2161 /// There's a large number of things which don't need to be done along 2162 /// this path. 2163 ExprResult 2164 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 2165 const DeclarationNameInfo &NameInfo, 2166 bool IsAddressOfOperand) { 2167 DeclContext *DC = computeDeclContext(SS, false); 2168 if (!DC) 2169 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2170 NameInfo, /*TemplateArgs=*/0); 2171 2172 if (RequireCompleteDeclContext(SS, DC)) 2173 return ExprError(); 2174 2175 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2176 LookupQualifiedName(R, DC); 2177 2178 if (R.isAmbiguous()) 2179 return ExprError(); 2180 2181 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2182 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2183 NameInfo, /*TemplateArgs=*/0); 2184 2185 if (R.empty()) { 2186 Diag(NameInfo.getLoc(), diag::err_no_member) 2187 << NameInfo.getName() << DC << SS.getRange(); 2188 return ExprError(); 2189 } 2190 2191 // Defend against this resolving to an implicit member access. We usually 2192 // won't get here if this might be a legitimate a class member (we end up in 2193 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2194 // a pointer-to-member or in an unevaluated context in C++11. 2195 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2196 return BuildPossibleImplicitMemberExpr(SS, 2197 /*TemplateKWLoc=*/SourceLocation(), 2198 R, /*TemplateArgs=*/0); 2199 2200 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2201 } 2202 2203 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2204 /// detected that we're currently inside an ObjC method. Perform some 2205 /// additional lookup. 2206 /// 2207 /// Ideally, most of this would be done by lookup, but there's 2208 /// actually quite a lot of extra work involved. 2209 /// 2210 /// Returns a null sentinel to indicate trivial success. 2211 ExprResult 2212 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2213 IdentifierInfo *II, bool AllowBuiltinCreation) { 2214 SourceLocation Loc = Lookup.getNameLoc(); 2215 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2216 2217 // Check for error condition which is already reported. 2218 if (!CurMethod) 2219 return ExprError(); 2220 2221 // There are two cases to handle here. 1) scoped lookup could have failed, 2222 // in which case we should look for an ivar. 2) scoped lookup could have 2223 // found a decl, but that decl is outside the current instance method (i.e. 2224 // a global variable). In these two cases, we do a lookup for an ivar with 2225 // this name, if the lookup sucedes, we replace it our current decl. 2226 2227 // If we're in a class method, we don't normally want to look for 2228 // ivars. But if we don't find anything else, and there's an 2229 // ivar, that's an error. 2230 bool IsClassMethod = CurMethod->isClassMethod(); 2231 2232 bool LookForIvars; 2233 if (Lookup.empty()) 2234 LookForIvars = true; 2235 else if (IsClassMethod) 2236 LookForIvars = false; 2237 else 2238 LookForIvars = (Lookup.isSingleResult() && 2239 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2240 ObjCInterfaceDecl *IFace = 0; 2241 if (LookForIvars) { 2242 IFace = CurMethod->getClassInterface(); 2243 ObjCInterfaceDecl *ClassDeclared; 2244 ObjCIvarDecl *IV = 0; 2245 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2246 // Diagnose using an ivar in a class method. 2247 if (IsClassMethod) 2248 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2249 << IV->getDeclName()); 2250 2251 // If we're referencing an invalid decl, just return this as a silent 2252 // error node. The error diagnostic was already emitted on the decl. 2253 if (IV->isInvalidDecl()) 2254 return ExprError(); 2255 2256 // Check if referencing a field with __attribute__((deprecated)). 2257 if (DiagnoseUseOfDecl(IV, Loc)) 2258 return ExprError(); 2259 2260 // Diagnose the use of an ivar outside of the declaring class. 2261 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2262 !declaresSameEntity(ClassDeclared, IFace) && 2263 !getLangOpts().DebuggerSupport) 2264 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2265 2266 // FIXME: This should use a new expr for a direct reference, don't 2267 // turn this into Self->ivar, just return a BareIVarExpr or something. 2268 IdentifierInfo &II = Context.Idents.get("self"); 2269 UnqualifiedId SelfName; 2270 SelfName.setIdentifier(&II, SourceLocation()); 2271 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2272 CXXScopeSpec SelfScopeSpec; 2273 SourceLocation TemplateKWLoc; 2274 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2275 SelfName, false, false); 2276 if (SelfExpr.isInvalid()) 2277 return ExprError(); 2278 2279 SelfExpr = DefaultLvalueConversion(SelfExpr.take()); 2280 if (SelfExpr.isInvalid()) 2281 return ExprError(); 2282 2283 MarkAnyDeclReferenced(Loc, IV, true); 2284 2285 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2286 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2287 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2288 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2289 2290 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(), 2291 Loc, IV->getLocation(), 2292 SelfExpr.take(), 2293 true, true); 2294 2295 if (getLangOpts().ObjCAutoRefCount) { 2296 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2297 DiagnosticsEngine::Level Level = 2298 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc); 2299 if (Level != DiagnosticsEngine::Ignored) 2300 recordUseOfEvaluatedWeak(Result); 2301 } 2302 if (CurContext->isClosure()) 2303 Diag(Loc, diag::warn_implicitly_retains_self) 2304 << FixItHint::CreateInsertion(Loc, "self->"); 2305 } 2306 2307 return Owned(Result); 2308 } 2309 } else if (CurMethod->isInstanceMethod()) { 2310 // We should warn if a local variable hides an ivar. 2311 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2312 ObjCInterfaceDecl *ClassDeclared; 2313 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2314 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2315 declaresSameEntity(IFace, ClassDeclared)) 2316 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2317 } 2318 } 2319 } else if (Lookup.isSingleResult() && 2320 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2321 // If accessing a stand-alone ivar in a class method, this is an error. 2322 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2323 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2324 << IV->getDeclName()); 2325 } 2326 2327 if (Lookup.empty() && II && AllowBuiltinCreation) { 2328 // FIXME. Consolidate this with similar code in LookupName. 2329 if (unsigned BuiltinID = II->getBuiltinID()) { 2330 if (!(getLangOpts().CPlusPlus && 2331 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2332 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2333 S, Lookup.isForRedeclaration(), 2334 Lookup.getNameLoc()); 2335 if (D) Lookup.addDecl(D); 2336 } 2337 } 2338 } 2339 // Sentinel value saying that we didn't do anything special. 2340 return Owned((Expr*) 0); 2341 } 2342 2343 /// \brief Cast a base object to a member's actual type. 2344 /// 2345 /// Logically this happens in three phases: 2346 /// 2347 /// * First we cast from the base type to the naming class. 2348 /// The naming class is the class into which we were looking 2349 /// when we found the member; it's the qualifier type if a 2350 /// qualifier was provided, and otherwise it's the base type. 2351 /// 2352 /// * Next we cast from the naming class to the declaring class. 2353 /// If the member we found was brought into a class's scope by 2354 /// a using declaration, this is that class; otherwise it's 2355 /// the class declaring the member. 2356 /// 2357 /// * Finally we cast from the declaring class to the "true" 2358 /// declaring class of the member. This conversion does not 2359 /// obey access control. 2360 ExprResult 2361 Sema::PerformObjectMemberConversion(Expr *From, 2362 NestedNameSpecifier *Qualifier, 2363 NamedDecl *FoundDecl, 2364 NamedDecl *Member) { 2365 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2366 if (!RD) 2367 return Owned(From); 2368 2369 QualType DestRecordType; 2370 QualType DestType; 2371 QualType FromRecordType; 2372 QualType FromType = From->getType(); 2373 bool PointerConversions = false; 2374 if (isa<FieldDecl>(Member)) { 2375 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2376 2377 if (FromType->getAs<PointerType>()) { 2378 DestType = Context.getPointerType(DestRecordType); 2379 FromRecordType = FromType->getPointeeType(); 2380 PointerConversions = true; 2381 } else { 2382 DestType = DestRecordType; 2383 FromRecordType = FromType; 2384 } 2385 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2386 if (Method->isStatic()) 2387 return Owned(From); 2388 2389 DestType = Method->getThisType(Context); 2390 DestRecordType = DestType->getPointeeType(); 2391 2392 if (FromType->getAs<PointerType>()) { 2393 FromRecordType = FromType->getPointeeType(); 2394 PointerConversions = true; 2395 } else { 2396 FromRecordType = FromType; 2397 DestType = DestRecordType; 2398 } 2399 } else { 2400 // No conversion necessary. 2401 return Owned(From); 2402 } 2403 2404 if (DestType->isDependentType() || FromType->isDependentType()) 2405 return Owned(From); 2406 2407 // If the unqualified types are the same, no conversion is necessary. 2408 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2409 return Owned(From); 2410 2411 SourceRange FromRange = From->getSourceRange(); 2412 SourceLocation FromLoc = FromRange.getBegin(); 2413 2414 ExprValueKind VK = From->getValueKind(); 2415 2416 // C++ [class.member.lookup]p8: 2417 // [...] Ambiguities can often be resolved by qualifying a name with its 2418 // class name. 2419 // 2420 // If the member was a qualified name and the qualified referred to a 2421 // specific base subobject type, we'll cast to that intermediate type 2422 // first and then to the object in which the member is declared. That allows 2423 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2424 // 2425 // class Base { public: int x; }; 2426 // class Derived1 : public Base { }; 2427 // class Derived2 : public Base { }; 2428 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2429 // 2430 // void VeryDerived::f() { 2431 // x = 17; // error: ambiguous base subobjects 2432 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2433 // } 2434 if (Qualifier && Qualifier->getAsType()) { 2435 QualType QType = QualType(Qualifier->getAsType(), 0); 2436 assert(QType->isRecordType() && "lookup done with non-record type"); 2437 2438 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2439 2440 // In C++98, the qualifier type doesn't actually have to be a base 2441 // type of the object type, in which case we just ignore it. 2442 // Otherwise build the appropriate casts. 2443 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2444 CXXCastPath BasePath; 2445 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2446 FromLoc, FromRange, &BasePath)) 2447 return ExprError(); 2448 2449 if (PointerConversions) 2450 QType = Context.getPointerType(QType); 2451 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2452 VK, &BasePath).take(); 2453 2454 FromType = QType; 2455 FromRecordType = QRecordType; 2456 2457 // If the qualifier type was the same as the destination type, 2458 // we're done. 2459 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2460 return Owned(From); 2461 } 2462 } 2463 2464 bool IgnoreAccess = false; 2465 2466 // If we actually found the member through a using declaration, cast 2467 // down to the using declaration's type. 2468 // 2469 // Pointer equality is fine here because only one declaration of a 2470 // class ever has member declarations. 2471 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2472 assert(isa<UsingShadowDecl>(FoundDecl)); 2473 QualType URecordType = Context.getTypeDeclType( 2474 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2475 2476 // We only need to do this if the naming-class to declaring-class 2477 // conversion is non-trivial. 2478 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2479 assert(IsDerivedFrom(FromRecordType, URecordType)); 2480 CXXCastPath BasePath; 2481 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2482 FromLoc, FromRange, &BasePath)) 2483 return ExprError(); 2484 2485 QualType UType = URecordType; 2486 if (PointerConversions) 2487 UType = Context.getPointerType(UType); 2488 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2489 VK, &BasePath).take(); 2490 FromType = UType; 2491 FromRecordType = URecordType; 2492 } 2493 2494 // We don't do access control for the conversion from the 2495 // declaring class to the true declaring class. 2496 IgnoreAccess = true; 2497 } 2498 2499 CXXCastPath BasePath; 2500 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2501 FromLoc, FromRange, &BasePath, 2502 IgnoreAccess)) 2503 return ExprError(); 2504 2505 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2506 VK, &BasePath); 2507 } 2508 2509 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2510 const LookupResult &R, 2511 bool HasTrailingLParen) { 2512 // Only when used directly as the postfix-expression of a call. 2513 if (!HasTrailingLParen) 2514 return false; 2515 2516 // Never if a scope specifier was provided. 2517 if (SS.isSet()) 2518 return false; 2519 2520 // Only in C++ or ObjC++. 2521 if (!getLangOpts().CPlusPlus) 2522 return false; 2523 2524 // Turn off ADL when we find certain kinds of declarations during 2525 // normal lookup: 2526 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2527 NamedDecl *D = *I; 2528 2529 // C++0x [basic.lookup.argdep]p3: 2530 // -- a declaration of a class member 2531 // Since using decls preserve this property, we check this on the 2532 // original decl. 2533 if (D->isCXXClassMember()) 2534 return false; 2535 2536 // C++0x [basic.lookup.argdep]p3: 2537 // -- a block-scope function declaration that is not a 2538 // using-declaration 2539 // NOTE: we also trigger this for function templates (in fact, we 2540 // don't check the decl type at all, since all other decl types 2541 // turn off ADL anyway). 2542 if (isa<UsingShadowDecl>(D)) 2543 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2544 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2545 return false; 2546 2547 // C++0x [basic.lookup.argdep]p3: 2548 // -- a declaration that is neither a function or a function 2549 // template 2550 // And also for builtin functions. 2551 if (isa<FunctionDecl>(D)) { 2552 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2553 2554 // But also builtin functions. 2555 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2556 return false; 2557 } else if (!isa<FunctionTemplateDecl>(D)) 2558 return false; 2559 } 2560 2561 return true; 2562 } 2563 2564 2565 /// Diagnoses obvious problems with the use of the given declaration 2566 /// as an expression. This is only actually called for lookups that 2567 /// were not overloaded, and it doesn't promise that the declaration 2568 /// will in fact be used. 2569 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2570 if (isa<TypedefNameDecl>(D)) { 2571 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2572 return true; 2573 } 2574 2575 if (isa<ObjCInterfaceDecl>(D)) { 2576 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2577 return true; 2578 } 2579 2580 if (isa<NamespaceDecl>(D)) { 2581 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2582 return true; 2583 } 2584 2585 return false; 2586 } 2587 2588 ExprResult 2589 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2590 LookupResult &R, 2591 bool NeedsADL) { 2592 // If this is a single, fully-resolved result and we don't need ADL, 2593 // just build an ordinary singleton decl ref. 2594 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2595 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2596 R.getRepresentativeDecl()); 2597 2598 // We only need to check the declaration if there's exactly one 2599 // result, because in the overloaded case the results can only be 2600 // functions and function templates. 2601 if (R.isSingleResult() && 2602 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2603 return ExprError(); 2604 2605 // Otherwise, just build an unresolved lookup expression. Suppress 2606 // any lookup-related diagnostics; we'll hash these out later, when 2607 // we've picked a target. 2608 R.suppressDiagnostics(); 2609 2610 UnresolvedLookupExpr *ULE 2611 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2612 SS.getWithLocInContext(Context), 2613 R.getLookupNameInfo(), 2614 NeedsADL, R.isOverloadedResult(), 2615 R.begin(), R.end()); 2616 2617 return Owned(ULE); 2618 } 2619 2620 /// \brief Complete semantic analysis for a reference to the given declaration. 2621 ExprResult Sema::BuildDeclarationNameExpr( 2622 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2623 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) { 2624 assert(D && "Cannot refer to a NULL declaration"); 2625 assert(!isa<FunctionTemplateDecl>(D) && 2626 "Cannot refer unambiguously to a function template"); 2627 2628 SourceLocation Loc = NameInfo.getLoc(); 2629 if (CheckDeclInExpr(*this, Loc, D)) 2630 return ExprError(); 2631 2632 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2633 // Specifically diagnose references to class templates that are missing 2634 // a template argument list. 2635 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2636 << Template << SS.getRange(); 2637 Diag(Template->getLocation(), diag::note_template_decl_here); 2638 return ExprError(); 2639 } 2640 2641 // Make sure that we're referring to a value. 2642 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2643 if (!VD) { 2644 Diag(Loc, diag::err_ref_non_value) 2645 << D << SS.getRange(); 2646 Diag(D->getLocation(), diag::note_declared_at); 2647 return ExprError(); 2648 } 2649 2650 // Check whether this declaration can be used. Note that we suppress 2651 // this check when we're going to perform argument-dependent lookup 2652 // on this function name, because this might not be the function 2653 // that overload resolution actually selects. 2654 if (DiagnoseUseOfDecl(VD, Loc)) 2655 return ExprError(); 2656 2657 // Only create DeclRefExpr's for valid Decl's. 2658 if (VD->isInvalidDecl()) 2659 return ExprError(); 2660 2661 // Handle members of anonymous structs and unions. If we got here, 2662 // and the reference is to a class member indirect field, then this 2663 // must be the subject of a pointer-to-member expression. 2664 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2665 if (!indirectField->isCXXClassMember()) 2666 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2667 indirectField); 2668 2669 { 2670 QualType type = VD->getType(); 2671 ExprValueKind valueKind = VK_RValue; 2672 2673 switch (D->getKind()) { 2674 // Ignore all the non-ValueDecl kinds. 2675 #define ABSTRACT_DECL(kind) 2676 #define VALUE(type, base) 2677 #define DECL(type, base) \ 2678 case Decl::type: 2679 #include "clang/AST/DeclNodes.inc" 2680 llvm_unreachable("invalid value decl kind"); 2681 2682 // These shouldn't make it here. 2683 case Decl::ObjCAtDefsField: 2684 case Decl::ObjCIvar: 2685 llvm_unreachable("forming non-member reference to ivar?"); 2686 2687 // Enum constants are always r-values and never references. 2688 // Unresolved using declarations are dependent. 2689 case Decl::EnumConstant: 2690 case Decl::UnresolvedUsingValue: 2691 valueKind = VK_RValue; 2692 break; 2693 2694 // Fields and indirect fields that got here must be for 2695 // pointer-to-member expressions; we just call them l-values for 2696 // internal consistency, because this subexpression doesn't really 2697 // exist in the high-level semantics. 2698 case Decl::Field: 2699 case Decl::IndirectField: 2700 assert(getLangOpts().CPlusPlus && 2701 "building reference to field in C?"); 2702 2703 // These can't have reference type in well-formed programs, but 2704 // for internal consistency we do this anyway. 2705 type = type.getNonReferenceType(); 2706 valueKind = VK_LValue; 2707 break; 2708 2709 // Non-type template parameters are either l-values or r-values 2710 // depending on the type. 2711 case Decl::NonTypeTemplateParm: { 2712 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2713 type = reftype->getPointeeType(); 2714 valueKind = VK_LValue; // even if the parameter is an r-value reference 2715 break; 2716 } 2717 2718 // For non-references, we need to strip qualifiers just in case 2719 // the template parameter was declared as 'const int' or whatever. 2720 valueKind = VK_RValue; 2721 type = type.getUnqualifiedType(); 2722 break; 2723 } 2724 2725 case Decl::Var: 2726 case Decl::VarTemplateSpecialization: 2727 case Decl::VarTemplatePartialSpecialization: 2728 // In C, "extern void blah;" is valid and is an r-value. 2729 if (!getLangOpts().CPlusPlus && 2730 !type.hasQualifiers() && 2731 type->isVoidType()) { 2732 valueKind = VK_RValue; 2733 break; 2734 } 2735 // fallthrough 2736 2737 case Decl::ImplicitParam: 2738 case Decl::ParmVar: { 2739 // These are always l-values. 2740 valueKind = VK_LValue; 2741 type = type.getNonReferenceType(); 2742 2743 // FIXME: Does the addition of const really only apply in 2744 // potentially-evaluated contexts? Since the variable isn't actually 2745 // captured in an unevaluated context, it seems that the answer is no. 2746 if (!isUnevaluatedContext()) { 2747 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2748 if (!CapturedType.isNull()) 2749 type = CapturedType; 2750 } 2751 2752 break; 2753 } 2754 2755 case Decl::Function: { 2756 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2757 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2758 type = Context.BuiltinFnTy; 2759 valueKind = VK_RValue; 2760 break; 2761 } 2762 } 2763 2764 const FunctionType *fty = type->castAs<FunctionType>(); 2765 2766 // If we're referring to a function with an __unknown_anytype 2767 // result type, make the entire expression __unknown_anytype. 2768 if (fty->getReturnType() == Context.UnknownAnyTy) { 2769 type = Context.UnknownAnyTy; 2770 valueKind = VK_RValue; 2771 break; 2772 } 2773 2774 // Functions are l-values in C++. 2775 if (getLangOpts().CPlusPlus) { 2776 valueKind = VK_LValue; 2777 break; 2778 } 2779 2780 // C99 DR 316 says that, if a function type comes from a 2781 // function definition (without a prototype), that type is only 2782 // used for checking compatibility. Therefore, when referencing 2783 // the function, we pretend that we don't have the full function 2784 // type. 2785 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2786 isa<FunctionProtoType>(fty)) 2787 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2788 fty->getExtInfo()); 2789 2790 // Functions are r-values in C. 2791 valueKind = VK_RValue; 2792 break; 2793 } 2794 2795 case Decl::MSProperty: 2796 valueKind = VK_LValue; 2797 break; 2798 2799 case Decl::CXXMethod: 2800 // If we're referring to a method with an __unknown_anytype 2801 // result type, make the entire expression __unknown_anytype. 2802 // This should only be possible with a type written directly. 2803 if (const FunctionProtoType *proto 2804 = dyn_cast<FunctionProtoType>(VD->getType())) 2805 if (proto->getReturnType() == Context.UnknownAnyTy) { 2806 type = Context.UnknownAnyTy; 2807 valueKind = VK_RValue; 2808 break; 2809 } 2810 2811 // C++ methods are l-values if static, r-values if non-static. 2812 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2813 valueKind = VK_LValue; 2814 break; 2815 } 2816 // fallthrough 2817 2818 case Decl::CXXConversion: 2819 case Decl::CXXDestructor: 2820 case Decl::CXXConstructor: 2821 valueKind = VK_RValue; 2822 break; 2823 } 2824 2825 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2826 TemplateArgs); 2827 } 2828 } 2829 2830 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 2831 PredefinedExpr::IdentType IT) { 2832 // Pick the current block, lambda, captured statement or function. 2833 Decl *currentDecl = 0; 2834 if (const BlockScopeInfo *BSI = getCurBlock()) 2835 currentDecl = BSI->TheDecl; 2836 else if (const LambdaScopeInfo *LSI = getCurLambda()) 2837 currentDecl = LSI->CallOperator; 2838 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 2839 currentDecl = CSI->TheCapturedDecl; 2840 else 2841 currentDecl = getCurFunctionOrMethodDecl(); 2842 2843 if (!currentDecl) { 2844 Diag(Loc, diag::ext_predef_outside_function); 2845 currentDecl = Context.getTranslationUnitDecl(); 2846 } 2847 2848 QualType ResTy; 2849 if (cast<DeclContext>(currentDecl)->isDependentContext()) 2850 ResTy = Context.DependentTy; 2851 else { 2852 // Pre-defined identifiers are of type char[x], where x is the length of 2853 // the string. 2854 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 2855 2856 llvm::APInt LengthI(32, Length + 1); 2857 if (IT == PredefinedExpr::LFunction) 2858 ResTy = Context.WideCharTy.withConst(); 2859 else 2860 ResTy = Context.CharTy.withConst(); 2861 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 2862 } 2863 2864 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT)); 2865 } 2866 2867 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 2868 PredefinedExpr::IdentType IT; 2869 2870 switch (Kind) { 2871 default: llvm_unreachable("Unknown simple primary expr!"); 2872 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 2873 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 2874 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 2875 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 2876 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 2877 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 2878 } 2879 2880 return BuildPredefinedExpr(Loc, IT); 2881 } 2882 2883 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 2884 SmallString<16> CharBuffer; 2885 bool Invalid = false; 2886 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 2887 if (Invalid) 2888 return ExprError(); 2889 2890 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 2891 PP, Tok.getKind()); 2892 if (Literal.hadError()) 2893 return ExprError(); 2894 2895 QualType Ty; 2896 if (Literal.isWide()) 2897 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 2898 else if (Literal.isUTF16()) 2899 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 2900 else if (Literal.isUTF32()) 2901 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 2902 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 2903 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 2904 else 2905 Ty = Context.CharTy; // 'x' -> char in C++ 2906 2907 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 2908 if (Literal.isWide()) 2909 Kind = CharacterLiteral::Wide; 2910 else if (Literal.isUTF16()) 2911 Kind = CharacterLiteral::UTF16; 2912 else if (Literal.isUTF32()) 2913 Kind = CharacterLiteral::UTF32; 2914 2915 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 2916 Tok.getLocation()); 2917 2918 if (Literal.getUDSuffix().empty()) 2919 return Owned(Lit); 2920 2921 // We're building a user-defined literal. 2922 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2923 SourceLocation UDSuffixLoc = 2924 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2925 2926 // Make sure we're allowed user-defined literals here. 2927 if (!UDLScope) 2928 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 2929 2930 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 2931 // operator "" X (ch) 2932 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 2933 Lit, Tok.getLocation()); 2934 } 2935 2936 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 2937 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2938 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 2939 Context.IntTy, Loc)); 2940 } 2941 2942 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 2943 QualType Ty, SourceLocation Loc) { 2944 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 2945 2946 using llvm::APFloat; 2947 APFloat Val(Format); 2948 2949 APFloat::opStatus result = Literal.GetFloatValue(Val); 2950 2951 // Overflow is always an error, but underflow is only an error if 2952 // we underflowed to zero (APFloat reports denormals as underflow). 2953 if ((result & APFloat::opOverflow) || 2954 ((result & APFloat::opUnderflow) && Val.isZero())) { 2955 unsigned diagnostic; 2956 SmallString<20> buffer; 2957 if (result & APFloat::opOverflow) { 2958 diagnostic = diag::warn_float_overflow; 2959 APFloat::getLargest(Format).toString(buffer); 2960 } else { 2961 diagnostic = diag::warn_float_underflow; 2962 APFloat::getSmallest(Format).toString(buffer); 2963 } 2964 2965 S.Diag(Loc, diagnostic) 2966 << Ty 2967 << StringRef(buffer.data(), buffer.size()); 2968 } 2969 2970 bool isExact = (result == APFloat::opOK); 2971 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 2972 } 2973 2974 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 2975 // Fast path for a single digit (which is quite common). A single digit 2976 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 2977 if (Tok.getLength() == 1) { 2978 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 2979 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 2980 } 2981 2982 SmallString<128> SpellingBuffer; 2983 // NumericLiteralParser wants to overread by one character. Add padding to 2984 // the buffer in case the token is copied to the buffer. If getSpelling() 2985 // returns a StringRef to the memory buffer, it should have a null char at 2986 // the EOF, so it is also safe. 2987 SpellingBuffer.resize(Tok.getLength() + 1); 2988 2989 // Get the spelling of the token, which eliminates trigraphs, etc. 2990 bool Invalid = false; 2991 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 2992 if (Invalid) 2993 return ExprError(); 2994 2995 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 2996 if (Literal.hadError) 2997 return ExprError(); 2998 2999 if (Literal.hasUDSuffix()) { 3000 // We're building a user-defined literal. 3001 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3002 SourceLocation UDSuffixLoc = 3003 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3004 3005 // Make sure we're allowed user-defined literals here. 3006 if (!UDLScope) 3007 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3008 3009 QualType CookedTy; 3010 if (Literal.isFloatingLiteral()) { 3011 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3012 // long double, the literal is treated as a call of the form 3013 // operator "" X (f L) 3014 CookedTy = Context.LongDoubleTy; 3015 } else { 3016 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3017 // unsigned long long, the literal is treated as a call of the form 3018 // operator "" X (n ULL) 3019 CookedTy = Context.UnsignedLongLongTy; 3020 } 3021 3022 DeclarationName OpName = 3023 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3024 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3025 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3026 3027 SourceLocation TokLoc = Tok.getLocation(); 3028 3029 // Perform literal operator lookup to determine if we're building a raw 3030 // literal or a cooked one. 3031 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3032 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3033 /*AllowRaw*/true, /*AllowTemplate*/true, 3034 /*AllowStringTemplate*/false)) { 3035 case LOLR_Error: 3036 return ExprError(); 3037 3038 case LOLR_Cooked: { 3039 Expr *Lit; 3040 if (Literal.isFloatingLiteral()) { 3041 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3042 } else { 3043 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3044 if (Literal.GetIntegerValue(ResultVal)) 3045 Diag(Tok.getLocation(), diag::err_integer_too_large); 3046 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3047 Tok.getLocation()); 3048 } 3049 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3050 } 3051 3052 case LOLR_Raw: { 3053 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3054 // literal is treated as a call of the form 3055 // operator "" X ("n") 3056 unsigned Length = Literal.getUDSuffixOffset(); 3057 QualType StrTy = Context.getConstantArrayType( 3058 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3059 ArrayType::Normal, 0); 3060 Expr *Lit = StringLiteral::Create( 3061 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3062 /*Pascal*/false, StrTy, &TokLoc, 1); 3063 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3064 } 3065 3066 case LOLR_Template: { 3067 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3068 // template), L is treated as a call fo the form 3069 // operator "" X <'c1', 'c2', ... 'ck'>() 3070 // where n is the source character sequence c1 c2 ... ck. 3071 TemplateArgumentListInfo ExplicitArgs; 3072 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3073 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3074 llvm::APSInt Value(CharBits, CharIsUnsigned); 3075 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3076 Value = TokSpelling[I]; 3077 TemplateArgument Arg(Context, Value, Context.CharTy); 3078 TemplateArgumentLocInfo ArgInfo; 3079 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3080 } 3081 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3082 &ExplicitArgs); 3083 } 3084 case LOLR_StringTemplate: 3085 llvm_unreachable("unexpected literal operator lookup result"); 3086 } 3087 } 3088 3089 Expr *Res; 3090 3091 if (Literal.isFloatingLiteral()) { 3092 QualType Ty; 3093 if (Literal.isFloat) 3094 Ty = Context.FloatTy; 3095 else if (!Literal.isLong) 3096 Ty = Context.DoubleTy; 3097 else 3098 Ty = Context.LongDoubleTy; 3099 3100 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3101 3102 if (Ty == Context.DoubleTy) { 3103 if (getLangOpts().SinglePrecisionConstants) { 3104 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 3105 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) { 3106 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3107 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take(); 3108 } 3109 } 3110 } else if (!Literal.isIntegerLiteral()) { 3111 return ExprError(); 3112 } else { 3113 QualType Ty; 3114 3115 // 'long long' is a C99 or C++11 feature. 3116 if (!getLangOpts().C99 && Literal.isLongLong) { 3117 if (getLangOpts().CPlusPlus) 3118 Diag(Tok.getLocation(), 3119 getLangOpts().CPlusPlus11 ? 3120 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3121 else 3122 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3123 } 3124 3125 // Get the value in the widest-possible width. 3126 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3127 // The microsoft literal suffix extensions support 128-bit literals, which 3128 // may be wider than [u]intmax_t. 3129 // FIXME: Actually, they don't. We seem to have accidentally invented the 3130 // i128 suffix. 3131 if (Literal.isMicrosoftInteger && MaxWidth < 128 && 3132 PP.getTargetInfo().hasInt128Type()) 3133 MaxWidth = 128; 3134 llvm::APInt ResultVal(MaxWidth, 0); 3135 3136 if (Literal.GetIntegerValue(ResultVal)) { 3137 // If this value didn't fit into uintmax_t, error and force to ull. 3138 Diag(Tok.getLocation(), diag::err_integer_too_large); 3139 Ty = Context.UnsignedLongLongTy; 3140 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3141 "long long is not intmax_t?"); 3142 } else { 3143 // If this value fits into a ULL, try to figure out what else it fits into 3144 // according to the rules of C99 6.4.4.1p5. 3145 3146 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3147 // be an unsigned int. 3148 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3149 3150 // Check from smallest to largest, picking the smallest type we can. 3151 unsigned Width = 0; 3152 if (!Literal.isLong && !Literal.isLongLong) { 3153 // Are int/unsigned possibilities? 3154 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3155 3156 // Does it fit in a unsigned int? 3157 if (ResultVal.isIntN(IntSize)) { 3158 // Does it fit in a signed int? 3159 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3160 Ty = Context.IntTy; 3161 else if (AllowUnsigned) 3162 Ty = Context.UnsignedIntTy; 3163 Width = IntSize; 3164 } 3165 } 3166 3167 // Are long/unsigned long possibilities? 3168 if (Ty.isNull() && !Literal.isLongLong) { 3169 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3170 3171 // Does it fit in a unsigned long? 3172 if (ResultVal.isIntN(LongSize)) { 3173 // Does it fit in a signed long? 3174 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3175 Ty = Context.LongTy; 3176 else if (AllowUnsigned) 3177 Ty = Context.UnsignedLongTy; 3178 Width = LongSize; 3179 } 3180 } 3181 3182 // Check long long if needed. 3183 if (Ty.isNull()) { 3184 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3185 3186 // Does it fit in a unsigned long long? 3187 if (ResultVal.isIntN(LongLongSize)) { 3188 // Does it fit in a signed long long? 3189 // To be compatible with MSVC, hex integer literals ending with the 3190 // LL or i64 suffix are always signed in Microsoft mode. 3191 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3192 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3193 Ty = Context.LongLongTy; 3194 else if (AllowUnsigned) 3195 Ty = Context.UnsignedLongLongTy; 3196 Width = LongLongSize; 3197 } 3198 } 3199 3200 // If it doesn't fit in unsigned long long, and we're using Microsoft 3201 // extensions, then its a 128-bit integer literal. 3202 if (Ty.isNull() && Literal.isMicrosoftInteger && 3203 PP.getTargetInfo().hasInt128Type()) { 3204 if (Literal.isUnsigned) 3205 Ty = Context.UnsignedInt128Ty; 3206 else 3207 Ty = Context.Int128Ty; 3208 Width = 128; 3209 } 3210 3211 // If we still couldn't decide a type, we probably have something that 3212 // does not fit in a signed long long, but has no U suffix. 3213 if (Ty.isNull()) { 3214 Diag(Tok.getLocation(), diag::ext_integer_too_large_for_signed); 3215 Ty = Context.UnsignedLongLongTy; 3216 Width = Context.getTargetInfo().getLongLongWidth(); 3217 } 3218 3219 if (ResultVal.getBitWidth() != Width) 3220 ResultVal = ResultVal.trunc(Width); 3221 } 3222 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3223 } 3224 3225 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3226 if (Literal.isImaginary) 3227 Res = new (Context) ImaginaryLiteral(Res, 3228 Context.getComplexType(Res->getType())); 3229 3230 return Owned(Res); 3231 } 3232 3233 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3234 assert((E != 0) && "ActOnParenExpr() missing expr"); 3235 return Owned(new (Context) ParenExpr(L, R, E)); 3236 } 3237 3238 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3239 SourceLocation Loc, 3240 SourceRange ArgRange) { 3241 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3242 // scalar or vector data type argument..." 3243 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3244 // type (C99 6.2.5p18) or void. 3245 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3246 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3247 << T << ArgRange; 3248 return true; 3249 } 3250 3251 assert((T->isVoidType() || !T->isIncompleteType()) && 3252 "Scalar types should always be complete"); 3253 return false; 3254 } 3255 3256 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3257 SourceLocation Loc, 3258 SourceRange ArgRange, 3259 UnaryExprOrTypeTrait TraitKind) { 3260 // Invalid types must be hard errors for SFINAE in C++. 3261 if (S.LangOpts.CPlusPlus) 3262 return true; 3263 3264 // C99 6.5.3.4p1: 3265 if (T->isFunctionType() && 3266 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3267 // sizeof(function)/alignof(function) is allowed as an extension. 3268 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3269 << TraitKind << ArgRange; 3270 return false; 3271 } 3272 3273 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3274 // this is an error (OpenCL v1.1 s6.3.k) 3275 if (T->isVoidType()) { 3276 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3277 : diag::ext_sizeof_alignof_void_type; 3278 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3279 return false; 3280 } 3281 3282 return true; 3283 } 3284 3285 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3286 SourceLocation Loc, 3287 SourceRange ArgRange, 3288 UnaryExprOrTypeTrait TraitKind) { 3289 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3290 // runtime doesn't allow it. 3291 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3292 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3293 << T << (TraitKind == UETT_SizeOf) 3294 << ArgRange; 3295 return true; 3296 } 3297 3298 return false; 3299 } 3300 3301 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3302 /// pointer type is equal to T) and emit a warning if it is. 3303 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3304 Expr *E) { 3305 // Don't warn if the operation changed the type. 3306 if (T != E->getType()) 3307 return; 3308 3309 // Now look for array decays. 3310 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3311 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3312 return; 3313 3314 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3315 << ICE->getType() 3316 << ICE->getSubExpr()->getType(); 3317 } 3318 3319 /// \brief Check the constraints on expression operands to unary type expression 3320 /// and type traits. 3321 /// 3322 /// Completes any types necessary and validates the constraints on the operand 3323 /// expression. The logic mostly mirrors the type-based overload, but may modify 3324 /// the expression as it completes the type for that expression through template 3325 /// instantiation, etc. 3326 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3327 UnaryExprOrTypeTrait ExprKind) { 3328 QualType ExprTy = E->getType(); 3329 assert(!ExprTy->isReferenceType()); 3330 3331 if (ExprKind == UETT_VecStep) 3332 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3333 E->getSourceRange()); 3334 3335 // Whitelist some types as extensions 3336 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3337 E->getSourceRange(), ExprKind)) 3338 return false; 3339 3340 if (RequireCompleteExprType(E, 3341 diag::err_sizeof_alignof_incomplete_type, 3342 ExprKind, E->getSourceRange())) 3343 return true; 3344 3345 // Completing the expression's type may have changed it. 3346 ExprTy = E->getType(); 3347 assert(!ExprTy->isReferenceType()); 3348 3349 if (ExprTy->isFunctionType()) { 3350 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3351 << ExprKind << E->getSourceRange(); 3352 return true; 3353 } 3354 3355 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3356 E->getSourceRange(), ExprKind)) 3357 return true; 3358 3359 if (ExprKind == UETT_SizeOf) { 3360 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3361 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3362 QualType OType = PVD->getOriginalType(); 3363 QualType Type = PVD->getType(); 3364 if (Type->isPointerType() && OType->isArrayType()) { 3365 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3366 << Type << OType; 3367 Diag(PVD->getLocation(), diag::note_declared_at); 3368 } 3369 } 3370 } 3371 3372 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3373 // decays into a pointer and returns an unintended result. This is most 3374 // likely a typo for "sizeof(array) op x". 3375 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3376 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3377 BO->getLHS()); 3378 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3379 BO->getRHS()); 3380 } 3381 } 3382 3383 return false; 3384 } 3385 3386 /// \brief Check the constraints on operands to unary expression and type 3387 /// traits. 3388 /// 3389 /// This will complete any types necessary, and validate the various constraints 3390 /// on those operands. 3391 /// 3392 /// The UsualUnaryConversions() function is *not* called by this routine. 3393 /// C99 6.3.2.1p[2-4] all state: 3394 /// Except when it is the operand of the sizeof operator ... 3395 /// 3396 /// C++ [expr.sizeof]p4 3397 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3398 /// standard conversions are not applied to the operand of sizeof. 3399 /// 3400 /// This policy is followed for all of the unary trait expressions. 3401 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3402 SourceLocation OpLoc, 3403 SourceRange ExprRange, 3404 UnaryExprOrTypeTrait ExprKind) { 3405 if (ExprType->isDependentType()) 3406 return false; 3407 3408 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 3409 // the result is the size of the referenced type." 3410 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the 3411 // result shall be the alignment of the referenced type." 3412 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3413 ExprType = Ref->getPointeeType(); 3414 3415 if (ExprKind == UETT_VecStep) 3416 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3417 3418 // Whitelist some types as extensions 3419 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3420 ExprKind)) 3421 return false; 3422 3423 if (RequireCompleteType(OpLoc, ExprType, 3424 diag::err_sizeof_alignof_incomplete_type, 3425 ExprKind, ExprRange)) 3426 return true; 3427 3428 if (ExprType->isFunctionType()) { 3429 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3430 << ExprKind << ExprRange; 3431 return true; 3432 } 3433 3434 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3435 ExprKind)) 3436 return true; 3437 3438 return false; 3439 } 3440 3441 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3442 E = E->IgnoreParens(); 3443 3444 // Cannot know anything else if the expression is dependent. 3445 if (E->isTypeDependent()) 3446 return false; 3447 3448 if (E->getObjectKind() == OK_BitField) { 3449 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) 3450 << 1 << E->getSourceRange(); 3451 return true; 3452 } 3453 3454 ValueDecl *D = 0; 3455 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3456 D = DRE->getDecl(); 3457 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3458 D = ME->getMemberDecl(); 3459 } 3460 3461 // If it's a field, require the containing struct to have a 3462 // complete definition so that we can compute the layout. 3463 // 3464 // This requires a very particular set of circumstances. For a 3465 // field to be contained within an incomplete type, we must in the 3466 // process of parsing that type. To have an expression refer to a 3467 // field, it must be an id-expression or a member-expression, but 3468 // the latter are always ill-formed when the base type is 3469 // incomplete, including only being partially complete. An 3470 // id-expression can never refer to a field in C because fields 3471 // are not in the ordinary namespace. In C++, an id-expression 3472 // can implicitly be a member access, but only if there's an 3473 // implicit 'this' value, and all such contexts are subject to 3474 // delayed parsing --- except for trailing return types in C++11. 3475 // And if an id-expression referring to a field occurs in a 3476 // context that lacks a 'this' value, it's ill-formed --- except, 3477 // again, in C++11, where such references are allowed in an 3478 // unevaluated context. So C++11 introduces some new complexity. 3479 // 3480 // For the record, since __alignof__ on expressions is a GCC 3481 // extension, GCC seems to permit this but always gives the 3482 // nonsensical answer 0. 3483 // 3484 // We don't really need the layout here --- we could instead just 3485 // directly check for all the appropriate alignment-lowing 3486 // attributes --- but that would require duplicating a lot of 3487 // logic that just isn't worth duplicating for such a marginal 3488 // use-case. 3489 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3490 // Fast path this check, since we at least know the record has a 3491 // definition if we can find a member of it. 3492 if (!FD->getParent()->isCompleteDefinition()) { 3493 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3494 << E->getSourceRange(); 3495 return true; 3496 } 3497 3498 // Otherwise, if it's a field, and the field doesn't have 3499 // reference type, then it must have a complete type (or be a 3500 // flexible array member, which we explicitly want to 3501 // white-list anyway), which makes the following checks trivial. 3502 if (!FD->getType()->isReferenceType()) 3503 return false; 3504 } 3505 3506 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3507 } 3508 3509 bool Sema::CheckVecStepExpr(Expr *E) { 3510 E = E->IgnoreParens(); 3511 3512 // Cannot know anything else if the expression is dependent. 3513 if (E->isTypeDependent()) 3514 return false; 3515 3516 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3517 } 3518 3519 /// \brief Build a sizeof or alignof expression given a type operand. 3520 ExprResult 3521 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3522 SourceLocation OpLoc, 3523 UnaryExprOrTypeTrait ExprKind, 3524 SourceRange R) { 3525 if (!TInfo) 3526 return ExprError(); 3527 3528 QualType T = TInfo->getType(); 3529 3530 if (!T->isDependentType() && 3531 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3532 return ExprError(); 3533 3534 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3535 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo, 3536 Context.getSizeType(), 3537 OpLoc, R.getEnd())); 3538 } 3539 3540 /// \brief Build a sizeof or alignof expression given an expression 3541 /// operand. 3542 ExprResult 3543 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3544 UnaryExprOrTypeTrait ExprKind) { 3545 ExprResult PE = CheckPlaceholderExpr(E); 3546 if (PE.isInvalid()) 3547 return ExprError(); 3548 3549 E = PE.get(); 3550 3551 // Verify that the operand is valid. 3552 bool isInvalid = false; 3553 if (E->isTypeDependent()) { 3554 // Delay type-checking for type-dependent expressions. 3555 } else if (ExprKind == UETT_AlignOf) { 3556 isInvalid = CheckAlignOfExpr(*this, E); 3557 } else if (ExprKind == UETT_VecStep) { 3558 isInvalid = CheckVecStepExpr(E); 3559 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3560 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0; 3561 isInvalid = true; 3562 } else { 3563 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3564 } 3565 3566 if (isInvalid) 3567 return ExprError(); 3568 3569 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3570 PE = TransformToPotentiallyEvaluated(E); 3571 if (PE.isInvalid()) return ExprError(); 3572 E = PE.take(); 3573 } 3574 3575 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3576 return Owned(new (Context) UnaryExprOrTypeTraitExpr( 3577 ExprKind, E, Context.getSizeType(), OpLoc, 3578 E->getSourceRange().getEnd())); 3579 } 3580 3581 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3582 /// expr and the same for @c alignof and @c __alignof 3583 /// Note that the ArgRange is invalid if isType is false. 3584 ExprResult 3585 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3586 UnaryExprOrTypeTrait ExprKind, bool IsType, 3587 void *TyOrEx, const SourceRange &ArgRange) { 3588 // If error parsing type, ignore. 3589 if (TyOrEx == 0) return ExprError(); 3590 3591 if (IsType) { 3592 TypeSourceInfo *TInfo; 3593 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3594 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3595 } 3596 3597 Expr *ArgEx = (Expr *)TyOrEx; 3598 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3599 return Result; 3600 } 3601 3602 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3603 bool IsReal) { 3604 if (V.get()->isTypeDependent()) 3605 return S.Context.DependentTy; 3606 3607 // _Real and _Imag are only l-values for normal l-values. 3608 if (V.get()->getObjectKind() != OK_Ordinary) { 3609 V = S.DefaultLvalueConversion(V.take()); 3610 if (V.isInvalid()) 3611 return QualType(); 3612 } 3613 3614 // These operators return the element type of a complex type. 3615 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3616 return CT->getElementType(); 3617 3618 // Otherwise they pass through real integer and floating point types here. 3619 if (V.get()->getType()->isArithmeticType()) 3620 return V.get()->getType(); 3621 3622 // Test for placeholders. 3623 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3624 if (PR.isInvalid()) return QualType(); 3625 if (PR.get() != V.get()) { 3626 V = PR; 3627 return CheckRealImagOperand(S, V, Loc, IsReal); 3628 } 3629 3630 // Reject anything else. 3631 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3632 << (IsReal ? "__real" : "__imag"); 3633 return QualType(); 3634 } 3635 3636 3637 3638 ExprResult 3639 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3640 tok::TokenKind Kind, Expr *Input) { 3641 UnaryOperatorKind Opc; 3642 switch (Kind) { 3643 default: llvm_unreachable("Unknown unary op!"); 3644 case tok::plusplus: Opc = UO_PostInc; break; 3645 case tok::minusminus: Opc = UO_PostDec; break; 3646 } 3647 3648 // Since this might is a postfix expression, get rid of ParenListExprs. 3649 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3650 if (Result.isInvalid()) return ExprError(); 3651 Input = Result.take(); 3652 3653 return BuildUnaryOp(S, OpLoc, Opc, Input); 3654 } 3655 3656 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 3657 /// 3658 /// \return true on error 3659 static bool checkArithmeticOnObjCPointer(Sema &S, 3660 SourceLocation opLoc, 3661 Expr *op) { 3662 assert(op->getType()->isObjCObjectPointerType()); 3663 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 3664 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 3665 return false; 3666 3667 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 3668 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 3669 << op->getSourceRange(); 3670 return true; 3671 } 3672 3673 ExprResult 3674 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 3675 Expr *idx, SourceLocation rbLoc) { 3676 // Since this might be a postfix expression, get rid of ParenListExprs. 3677 if (isa<ParenListExpr>(base)) { 3678 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 3679 if (result.isInvalid()) return ExprError(); 3680 base = result.take(); 3681 } 3682 3683 // Handle any non-overload placeholder types in the base and index 3684 // expressions. We can't handle overloads here because the other 3685 // operand might be an overloadable type, in which case the overload 3686 // resolution for the operator overload should get the first crack 3687 // at the overload. 3688 if (base->getType()->isNonOverloadPlaceholderType()) { 3689 ExprResult result = CheckPlaceholderExpr(base); 3690 if (result.isInvalid()) return ExprError(); 3691 base = result.take(); 3692 } 3693 if (idx->getType()->isNonOverloadPlaceholderType()) { 3694 ExprResult result = CheckPlaceholderExpr(idx); 3695 if (result.isInvalid()) return ExprError(); 3696 idx = result.take(); 3697 } 3698 3699 // Build an unanalyzed expression if either operand is type-dependent. 3700 if (getLangOpts().CPlusPlus && 3701 (base->isTypeDependent() || idx->isTypeDependent())) { 3702 return Owned(new (Context) ArraySubscriptExpr(base, idx, 3703 Context.DependentTy, 3704 VK_LValue, OK_Ordinary, 3705 rbLoc)); 3706 } 3707 3708 // Use C++ overloaded-operator rules if either operand has record 3709 // type. The spec says to do this if either type is *overloadable*, 3710 // but enum types can't declare subscript operators or conversion 3711 // operators, so there's nothing interesting for overload resolution 3712 // to do if there aren't any record types involved. 3713 // 3714 // ObjC pointers have their own subscripting logic that is not tied 3715 // to overload resolution and so should not take this path. 3716 if (getLangOpts().CPlusPlus && 3717 (base->getType()->isRecordType() || 3718 (!base->getType()->isObjCObjectPointerType() && 3719 idx->getType()->isRecordType()))) { 3720 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 3721 } 3722 3723 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 3724 } 3725 3726 ExprResult 3727 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 3728 Expr *Idx, SourceLocation RLoc) { 3729 Expr *LHSExp = Base; 3730 Expr *RHSExp = Idx; 3731 3732 // Perform default conversions. 3733 if (!LHSExp->getType()->getAs<VectorType>()) { 3734 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 3735 if (Result.isInvalid()) 3736 return ExprError(); 3737 LHSExp = Result.take(); 3738 } 3739 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 3740 if (Result.isInvalid()) 3741 return ExprError(); 3742 RHSExp = Result.take(); 3743 3744 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 3745 ExprValueKind VK = VK_LValue; 3746 ExprObjectKind OK = OK_Ordinary; 3747 3748 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 3749 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 3750 // in the subscript position. As a result, we need to derive the array base 3751 // and index from the expression types. 3752 Expr *BaseExpr, *IndexExpr; 3753 QualType ResultType; 3754 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 3755 BaseExpr = LHSExp; 3756 IndexExpr = RHSExp; 3757 ResultType = Context.DependentTy; 3758 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 3759 BaseExpr = LHSExp; 3760 IndexExpr = RHSExp; 3761 ResultType = PTy->getPointeeType(); 3762 } else if (const ObjCObjectPointerType *PTy = 3763 LHSTy->getAs<ObjCObjectPointerType>()) { 3764 BaseExpr = LHSExp; 3765 IndexExpr = RHSExp; 3766 3767 // Use custom logic if this should be the pseudo-object subscript 3768 // expression. 3769 if (!LangOpts.isSubscriptPointerArithmetic()) 3770 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0); 3771 3772 ResultType = PTy->getPointeeType(); 3773 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 3774 // Handle the uncommon case of "123[Ptr]". 3775 BaseExpr = RHSExp; 3776 IndexExpr = LHSExp; 3777 ResultType = PTy->getPointeeType(); 3778 } else if (const ObjCObjectPointerType *PTy = 3779 RHSTy->getAs<ObjCObjectPointerType>()) { 3780 // Handle the uncommon case of "123[Ptr]". 3781 BaseExpr = RHSExp; 3782 IndexExpr = LHSExp; 3783 ResultType = PTy->getPointeeType(); 3784 if (!LangOpts.isSubscriptPointerArithmetic()) { 3785 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3786 << ResultType << BaseExpr->getSourceRange(); 3787 return ExprError(); 3788 } 3789 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 3790 BaseExpr = LHSExp; // vectors: V[123] 3791 IndexExpr = RHSExp; 3792 VK = LHSExp->getValueKind(); 3793 if (VK != VK_RValue) 3794 OK = OK_VectorComponent; 3795 3796 // FIXME: need to deal with const... 3797 ResultType = VTy->getElementType(); 3798 } else if (LHSTy->isArrayType()) { 3799 // If we see an array that wasn't promoted by 3800 // DefaultFunctionArrayLvalueConversion, it must be an array that 3801 // wasn't promoted because of the C90 rule that doesn't 3802 // allow promoting non-lvalue arrays. Warn, then 3803 // force the promotion here. 3804 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3805 LHSExp->getSourceRange(); 3806 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 3807 CK_ArrayToPointerDecay).take(); 3808 LHSTy = LHSExp->getType(); 3809 3810 BaseExpr = LHSExp; 3811 IndexExpr = RHSExp; 3812 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 3813 } else if (RHSTy->isArrayType()) { 3814 // Same as previous, except for 123[f().a] case 3815 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3816 RHSExp->getSourceRange(); 3817 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 3818 CK_ArrayToPointerDecay).take(); 3819 RHSTy = RHSExp->getType(); 3820 3821 BaseExpr = RHSExp; 3822 IndexExpr = LHSExp; 3823 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 3824 } else { 3825 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 3826 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 3827 } 3828 // C99 6.5.2.1p1 3829 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 3830 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 3831 << IndexExpr->getSourceRange()); 3832 3833 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 3834 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 3835 && !IndexExpr->isTypeDependent()) 3836 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 3837 3838 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 3839 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 3840 // type. Note that Functions are not objects, and that (in C99 parlance) 3841 // incomplete types are not object types. 3842 if (ResultType->isFunctionType()) { 3843 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 3844 << ResultType << BaseExpr->getSourceRange(); 3845 return ExprError(); 3846 } 3847 3848 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 3849 // GNU extension: subscripting on pointer to void 3850 Diag(LLoc, diag::ext_gnu_subscript_void_type) 3851 << BaseExpr->getSourceRange(); 3852 3853 // C forbids expressions of unqualified void type from being l-values. 3854 // See IsCForbiddenLValueType. 3855 if (!ResultType.hasQualifiers()) VK = VK_RValue; 3856 } else if (!ResultType->isDependentType() && 3857 RequireCompleteType(LLoc, ResultType, 3858 diag::err_subscript_incomplete_type, BaseExpr)) 3859 return ExprError(); 3860 3861 assert(VK == VK_RValue || LangOpts.CPlusPlus || 3862 !ResultType.isCForbiddenLValueType()); 3863 3864 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp, 3865 ResultType, VK, OK, RLoc)); 3866 } 3867 3868 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3869 FunctionDecl *FD, 3870 ParmVarDecl *Param) { 3871 if (Param->hasUnparsedDefaultArg()) { 3872 Diag(CallLoc, 3873 diag::err_use_of_default_argument_to_function_declared_later) << 3874 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 3875 Diag(UnparsedDefaultArgLocs[Param], 3876 diag::note_default_argument_declared_here); 3877 return ExprError(); 3878 } 3879 3880 if (Param->hasUninstantiatedDefaultArg()) { 3881 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 3882 3883 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 3884 Param); 3885 3886 // Instantiate the expression. 3887 MultiLevelTemplateArgumentList MutiLevelArgList 3888 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true); 3889 3890 InstantiatingTemplate Inst(*this, CallLoc, Param, 3891 MutiLevelArgList.getInnermost()); 3892 if (Inst.isInvalid()) 3893 return ExprError(); 3894 3895 ExprResult Result; 3896 { 3897 // C++ [dcl.fct.default]p5: 3898 // The names in the [default argument] expression are bound, and 3899 // the semantic constraints are checked, at the point where the 3900 // default argument expression appears. 3901 ContextRAII SavedContext(*this, FD); 3902 LocalInstantiationScope Local(*this); 3903 Result = SubstExpr(UninstExpr, MutiLevelArgList); 3904 } 3905 if (Result.isInvalid()) 3906 return ExprError(); 3907 3908 // Check the expression as an initializer for the parameter. 3909 InitializedEntity Entity 3910 = InitializedEntity::InitializeParameter(Context, Param); 3911 InitializationKind Kind 3912 = InitializationKind::CreateCopy(Param->getLocation(), 3913 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 3914 Expr *ResultE = Result.takeAs<Expr>(); 3915 3916 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 3917 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 3918 if (Result.isInvalid()) 3919 return ExprError(); 3920 3921 Expr *Arg = Result.takeAs<Expr>(); 3922 CheckCompletedExpr(Arg, Param->getOuterLocStart()); 3923 // Build the default argument expression. 3924 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg)); 3925 } 3926 3927 // If the default expression creates temporaries, we need to 3928 // push them to the current stack of expression temporaries so they'll 3929 // be properly destroyed. 3930 // FIXME: We should really be rebuilding the default argument with new 3931 // bound temporaries; see the comment in PR5810. 3932 // We don't need to do that with block decls, though, because 3933 // blocks in default argument expression can never capture anything. 3934 if (isa<ExprWithCleanups>(Param->getInit())) { 3935 // Set the "needs cleanups" bit regardless of whether there are 3936 // any explicit objects. 3937 ExprNeedsCleanups = true; 3938 3939 // Append all the objects to the cleanup list. Right now, this 3940 // should always be a no-op, because blocks in default argument 3941 // expressions should never be able to capture anything. 3942 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 3943 "default argument expression has capturing blocks?"); 3944 } 3945 3946 // We already type-checked the argument, so we know it works. 3947 // Just mark all of the declarations in this potentially-evaluated expression 3948 // as being "referenced". 3949 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 3950 /*SkipLocalVariables=*/true); 3951 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param)); 3952 } 3953 3954 3955 Sema::VariadicCallType 3956 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 3957 Expr *Fn) { 3958 if (Proto && Proto->isVariadic()) { 3959 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 3960 return VariadicConstructor; 3961 else if (Fn && Fn->getType()->isBlockPointerType()) 3962 return VariadicBlock; 3963 else if (FDecl) { 3964 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 3965 if (Method->isInstance()) 3966 return VariadicMethod; 3967 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 3968 return VariadicMethod; 3969 return VariadicFunction; 3970 } 3971 return VariadicDoesNotApply; 3972 } 3973 3974 namespace { 3975 class FunctionCallCCC : public FunctionCallFilterCCC { 3976 public: 3977 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 3978 unsigned NumArgs, MemberExpr *ME) 3979 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 3980 FunctionName(FuncName) {} 3981 3982 bool ValidateCandidate(const TypoCorrection &candidate) override { 3983 if (!candidate.getCorrectionSpecifier() || 3984 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 3985 return false; 3986 } 3987 3988 return FunctionCallFilterCCC::ValidateCandidate(candidate); 3989 } 3990 3991 private: 3992 const IdentifierInfo *const FunctionName; 3993 }; 3994 } 3995 3996 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 3997 FunctionDecl *FDecl, 3998 ArrayRef<Expr *> Args) { 3999 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4000 DeclarationName FuncName = FDecl->getDeclName(); 4001 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4002 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 4003 4004 if (TypoCorrection Corrected = S.CorrectTypo( 4005 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4006 S.getScopeForContext(S.CurContext), NULL, CCC)) { 4007 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 4008 if (Corrected.isOverloaded()) { 4009 OverloadCandidateSet OCS(NameLoc); 4010 OverloadCandidateSet::iterator Best; 4011 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 4012 CDEnd = Corrected.end(); 4013 CD != CDEnd; ++CD) { 4014 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 4015 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4016 OCS); 4017 } 4018 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4019 case OR_Success: 4020 ND = Best->Function; 4021 Corrected.setCorrectionDecl(ND); 4022 break; 4023 default: 4024 break; 4025 } 4026 } 4027 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 4028 return Corrected; 4029 } 4030 } 4031 } 4032 return TypoCorrection(); 4033 } 4034 4035 /// ConvertArgumentsForCall - Converts the arguments specified in 4036 /// Args/NumArgs to the parameter types of the function FDecl with 4037 /// function prototype Proto. Call is the call expression itself, and 4038 /// Fn is the function expression. For a C++ member function, this 4039 /// routine does not attempt to convert the object argument. Returns 4040 /// true if the call is ill-formed. 4041 bool 4042 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4043 FunctionDecl *FDecl, 4044 const FunctionProtoType *Proto, 4045 ArrayRef<Expr *> Args, 4046 SourceLocation RParenLoc, 4047 bool IsExecConfig) { 4048 // Bail out early if calling a builtin with custom typechecking. 4049 // We don't need to do this in the 4050 if (FDecl) 4051 if (unsigned ID = FDecl->getBuiltinID()) 4052 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4053 return false; 4054 4055 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4056 // assignment, to the types of the corresponding parameter, ... 4057 unsigned NumParams = Proto->getNumParams(); 4058 bool Invalid = false; 4059 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4060 unsigned FnKind = Fn->getType()->isBlockPointerType() 4061 ? 1 /* block */ 4062 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4063 : 0 /* function */); 4064 4065 // If too few arguments are available (and we don't have default 4066 // arguments for the remaining parameters), don't make the call. 4067 if (Args.size() < NumParams) { 4068 if (Args.size() < MinArgs) { 4069 TypoCorrection TC; 4070 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4071 unsigned diag_id = 4072 MinArgs == NumParams && !Proto->isVariadic() 4073 ? diag::err_typecheck_call_too_few_args_suggest 4074 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4075 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4076 << static_cast<unsigned>(Args.size()) 4077 << TC.getCorrectionRange()); 4078 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4079 Diag(RParenLoc, 4080 MinArgs == NumParams && !Proto->isVariadic() 4081 ? diag::err_typecheck_call_too_few_args_one 4082 : diag::err_typecheck_call_too_few_args_at_least_one) 4083 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4084 else 4085 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4086 ? diag::err_typecheck_call_too_few_args 4087 : diag::err_typecheck_call_too_few_args_at_least) 4088 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4089 << Fn->getSourceRange(); 4090 4091 // Emit the location of the prototype. 4092 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4093 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4094 << FDecl; 4095 4096 return true; 4097 } 4098 Call->setNumArgs(Context, NumParams); 4099 } 4100 4101 // If too many are passed and not variadic, error on the extras and drop 4102 // them. 4103 if (Args.size() > NumParams) { 4104 if (!Proto->isVariadic()) { 4105 TypoCorrection TC; 4106 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4107 unsigned diag_id = 4108 MinArgs == NumParams && !Proto->isVariadic() 4109 ? diag::err_typecheck_call_too_many_args_suggest 4110 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4111 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4112 << static_cast<unsigned>(Args.size()) 4113 << TC.getCorrectionRange()); 4114 } else if (NumParams == 1 && FDecl && 4115 FDecl->getParamDecl(0)->getDeclName()) 4116 Diag(Args[NumParams]->getLocStart(), 4117 MinArgs == NumParams 4118 ? diag::err_typecheck_call_too_many_args_one 4119 : diag::err_typecheck_call_too_many_args_at_most_one) 4120 << FnKind << FDecl->getParamDecl(0) 4121 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4122 << SourceRange(Args[NumParams]->getLocStart(), 4123 Args.back()->getLocEnd()); 4124 else 4125 Diag(Args[NumParams]->getLocStart(), 4126 MinArgs == NumParams 4127 ? diag::err_typecheck_call_too_many_args 4128 : diag::err_typecheck_call_too_many_args_at_most) 4129 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4130 << Fn->getSourceRange() 4131 << SourceRange(Args[NumParams]->getLocStart(), 4132 Args.back()->getLocEnd()); 4133 4134 // Emit the location of the prototype. 4135 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4136 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4137 << FDecl; 4138 4139 // This deletes the extra arguments. 4140 Call->setNumArgs(Context, NumParams); 4141 return true; 4142 } 4143 } 4144 SmallVector<Expr *, 8> AllArgs; 4145 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4146 4147 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4148 Proto, 0, Args, AllArgs, CallType); 4149 if (Invalid) 4150 return true; 4151 unsigned TotalNumArgs = AllArgs.size(); 4152 for (unsigned i = 0; i < TotalNumArgs; ++i) 4153 Call->setArg(i, AllArgs[i]); 4154 4155 return false; 4156 } 4157 4158 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4159 const FunctionProtoType *Proto, 4160 unsigned FirstParam, ArrayRef<Expr *> Args, 4161 SmallVectorImpl<Expr *> &AllArgs, 4162 VariadicCallType CallType, bool AllowExplicit, 4163 bool IsListInitialization) { 4164 unsigned NumParams = Proto->getNumParams(); 4165 unsigned NumArgsToCheck = Args.size(); 4166 bool Invalid = false; 4167 if (Args.size() != NumParams) 4168 // Use default arguments for missing arguments 4169 NumArgsToCheck = NumParams; 4170 unsigned ArgIx = 0; 4171 // Continue to check argument types (even if we have too few/many args). 4172 for (unsigned i = FirstParam; i != NumArgsToCheck; i++) { 4173 QualType ProtoArgType = Proto->getParamType(i); 4174 4175 Expr *Arg; 4176 ParmVarDecl *Param; 4177 if (ArgIx < Args.size()) { 4178 Arg = Args[ArgIx++]; 4179 4180 if (RequireCompleteType(Arg->getLocStart(), 4181 ProtoArgType, 4182 diag::err_call_incomplete_argument, Arg)) 4183 return true; 4184 4185 // Pass the argument 4186 Param = 0; 4187 if (FDecl && i < FDecl->getNumParams()) 4188 Param = FDecl->getParamDecl(i); 4189 4190 // Strip the unbridged-cast placeholder expression off, if applicable. 4191 bool CFAudited = false; 4192 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4193 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4194 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4195 Arg = stripARCUnbridgedCast(Arg); 4196 else if (getLangOpts().ObjCAutoRefCount && 4197 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4198 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4199 CFAudited = true; 4200 4201 InitializedEntity Entity = 4202 Param ? InitializedEntity::InitializeParameter(Context, Param, 4203 ProtoArgType) 4204 : InitializedEntity::InitializeParameter( 4205 Context, ProtoArgType, Proto->isParamConsumed(i)); 4206 4207 // Remember that parameter belongs to a CF audited API. 4208 if (CFAudited) 4209 Entity.setParameterCFAudited(); 4210 4211 ExprResult ArgE = PerformCopyInitialization(Entity, 4212 SourceLocation(), 4213 Owned(Arg), 4214 IsListInitialization, 4215 AllowExplicit); 4216 if (ArgE.isInvalid()) 4217 return true; 4218 4219 Arg = ArgE.takeAs<Expr>(); 4220 } else { 4221 assert(FDecl && "can't use default arguments without a known callee"); 4222 Param = FDecl->getParamDecl(i); 4223 4224 ExprResult ArgExpr = 4225 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4226 if (ArgExpr.isInvalid()) 4227 return true; 4228 4229 Arg = ArgExpr.takeAs<Expr>(); 4230 } 4231 4232 // Check for array bounds violations for each argument to the call. This 4233 // check only triggers warnings when the argument isn't a more complex Expr 4234 // with its own checking, such as a BinaryOperator. 4235 CheckArrayAccess(Arg); 4236 4237 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4238 CheckStaticArrayArgument(CallLoc, Param, Arg); 4239 4240 AllArgs.push_back(Arg); 4241 } 4242 4243 // If this is a variadic call, handle args passed through "...". 4244 if (CallType != VariadicDoesNotApply) { 4245 // Assume that extern "C" functions with variadic arguments that 4246 // return __unknown_anytype aren't *really* variadic. 4247 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4248 FDecl->isExternC()) { 4249 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4250 QualType paramType; // ignored 4251 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType); 4252 Invalid |= arg.isInvalid(); 4253 AllArgs.push_back(arg.take()); 4254 } 4255 4256 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4257 } else { 4258 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4259 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 4260 FDecl); 4261 Invalid |= Arg.isInvalid(); 4262 AllArgs.push_back(Arg.take()); 4263 } 4264 } 4265 4266 // Check for array bounds violations. 4267 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) 4268 CheckArrayAccess(Args[i]); 4269 } 4270 return Invalid; 4271 } 4272 4273 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4274 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4275 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4276 TL = DTL.getOriginalLoc(); 4277 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4278 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4279 << ATL.getLocalSourceRange(); 4280 } 4281 4282 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4283 /// array parameter, check that it is non-null, and that if it is formed by 4284 /// array-to-pointer decay, the underlying array is sufficiently large. 4285 /// 4286 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4287 /// array type derivation, then for each call to the function, the value of the 4288 /// corresponding actual argument shall provide access to the first element of 4289 /// an array with at least as many elements as specified by the size expression. 4290 void 4291 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4292 ParmVarDecl *Param, 4293 const Expr *ArgExpr) { 4294 // Static array parameters are not supported in C++. 4295 if (!Param || getLangOpts().CPlusPlus) 4296 return; 4297 4298 QualType OrigTy = Param->getOriginalType(); 4299 4300 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4301 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4302 return; 4303 4304 if (ArgExpr->isNullPointerConstant(Context, 4305 Expr::NPC_NeverValueDependent)) { 4306 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4307 DiagnoseCalleeStaticArrayParam(*this, Param); 4308 return; 4309 } 4310 4311 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4312 if (!CAT) 4313 return; 4314 4315 const ConstantArrayType *ArgCAT = 4316 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4317 if (!ArgCAT) 4318 return; 4319 4320 if (ArgCAT->getSize().ult(CAT->getSize())) { 4321 Diag(CallLoc, diag::warn_static_array_too_small) 4322 << ArgExpr->getSourceRange() 4323 << (unsigned) ArgCAT->getSize().getZExtValue() 4324 << (unsigned) CAT->getSize().getZExtValue(); 4325 DiagnoseCalleeStaticArrayParam(*this, Param); 4326 } 4327 } 4328 4329 /// Given a function expression of unknown-any type, try to rebuild it 4330 /// to have a function type. 4331 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4332 4333 /// Is the given type a placeholder that we need to lower out 4334 /// immediately during argument processing? 4335 static bool isPlaceholderToRemoveAsArg(QualType type) { 4336 // Placeholders are never sugared. 4337 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4338 if (!placeholder) return false; 4339 4340 switch (placeholder->getKind()) { 4341 // Ignore all the non-placeholder types. 4342 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4343 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4344 #include "clang/AST/BuiltinTypes.def" 4345 return false; 4346 4347 // We cannot lower out overload sets; they might validly be resolved 4348 // by the call machinery. 4349 case BuiltinType::Overload: 4350 return false; 4351 4352 // Unbridged casts in ARC can be handled in some call positions and 4353 // should be left in place. 4354 case BuiltinType::ARCUnbridgedCast: 4355 return false; 4356 4357 // Pseudo-objects should be converted as soon as possible. 4358 case BuiltinType::PseudoObject: 4359 return true; 4360 4361 // The debugger mode could theoretically but currently does not try 4362 // to resolve unknown-typed arguments based on known parameter types. 4363 case BuiltinType::UnknownAny: 4364 return true; 4365 4366 // These are always invalid as call arguments and should be reported. 4367 case BuiltinType::BoundMember: 4368 case BuiltinType::BuiltinFn: 4369 return true; 4370 } 4371 llvm_unreachable("bad builtin type kind"); 4372 } 4373 4374 /// Check an argument list for placeholders that we won't try to 4375 /// handle later. 4376 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 4377 // Apply this processing to all the arguments at once instead of 4378 // dying at the first failure. 4379 bool hasInvalid = false; 4380 for (size_t i = 0, e = args.size(); i != e; i++) { 4381 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 4382 ExprResult result = S.CheckPlaceholderExpr(args[i]); 4383 if (result.isInvalid()) hasInvalid = true; 4384 else args[i] = result.take(); 4385 } 4386 } 4387 return hasInvalid; 4388 } 4389 4390 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 4391 /// This provides the location of the left/right parens and a list of comma 4392 /// locations. 4393 ExprResult 4394 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 4395 MultiExprArg ArgExprs, SourceLocation RParenLoc, 4396 Expr *ExecConfig, bool IsExecConfig) { 4397 // Since this might be a postfix expression, get rid of ParenListExprs. 4398 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 4399 if (Result.isInvalid()) return ExprError(); 4400 Fn = Result.take(); 4401 4402 if (checkArgsForPlaceholders(*this, ArgExprs)) 4403 return ExprError(); 4404 4405 if (getLangOpts().CPlusPlus) { 4406 // If this is a pseudo-destructor expression, build the call immediately. 4407 if (isa<CXXPseudoDestructorExpr>(Fn)) { 4408 if (!ArgExprs.empty()) { 4409 // Pseudo-destructor calls should not have any arguments. 4410 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 4411 << FixItHint::CreateRemoval( 4412 SourceRange(ArgExprs[0]->getLocStart(), 4413 ArgExprs.back()->getLocEnd())); 4414 } 4415 4416 return Owned(new (Context) CallExpr(Context, Fn, None, 4417 Context.VoidTy, VK_RValue, 4418 RParenLoc)); 4419 } 4420 if (Fn->getType() == Context.PseudoObjectTy) { 4421 ExprResult result = CheckPlaceholderExpr(Fn); 4422 if (result.isInvalid()) return ExprError(); 4423 Fn = result.take(); 4424 } 4425 4426 // Determine whether this is a dependent call inside a C++ template, 4427 // in which case we won't do any semantic analysis now. 4428 // FIXME: Will need to cache the results of name lookup (including ADL) in 4429 // Fn. 4430 bool Dependent = false; 4431 if (Fn->isTypeDependent()) 4432 Dependent = true; 4433 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 4434 Dependent = true; 4435 4436 if (Dependent) { 4437 if (ExecConfig) { 4438 return Owned(new (Context) CUDAKernelCallExpr( 4439 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 4440 Context.DependentTy, VK_RValue, RParenLoc)); 4441 } else { 4442 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs, 4443 Context.DependentTy, VK_RValue, 4444 RParenLoc)); 4445 } 4446 } 4447 4448 // Determine whether this is a call to an object (C++ [over.call.object]). 4449 if (Fn->getType()->isRecordType()) 4450 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, 4451 ArgExprs, RParenLoc)); 4452 4453 if (Fn->getType() == Context.UnknownAnyTy) { 4454 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4455 if (result.isInvalid()) return ExprError(); 4456 Fn = result.take(); 4457 } 4458 4459 if (Fn->getType() == Context.BoundMemberTy) { 4460 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 4461 } 4462 } 4463 4464 // Check for overloaded calls. This can happen even in C due to extensions. 4465 if (Fn->getType() == Context.OverloadTy) { 4466 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 4467 4468 // We aren't supposed to apply this logic for if there's an '&' involved. 4469 if (!find.HasFormOfMemberPointer) { 4470 OverloadExpr *ovl = find.Expression; 4471 if (isa<UnresolvedLookupExpr>(ovl)) { 4472 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 4473 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 4474 RParenLoc, ExecConfig); 4475 } else { 4476 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, 4477 RParenLoc); 4478 } 4479 } 4480 } 4481 4482 // If we're directly calling a function, get the appropriate declaration. 4483 if (Fn->getType() == Context.UnknownAnyTy) { 4484 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4485 if (result.isInvalid()) return ExprError(); 4486 Fn = result.take(); 4487 } 4488 4489 Expr *NakedFn = Fn->IgnoreParens(); 4490 4491 NamedDecl *NDecl = 0; 4492 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 4493 if (UnOp->getOpcode() == UO_AddrOf) 4494 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 4495 4496 if (isa<DeclRefExpr>(NakedFn)) 4497 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 4498 else if (isa<MemberExpr>(NakedFn)) 4499 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 4500 4501 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 4502 if (FD->hasAttr<EnableIfAttr>()) { 4503 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 4504 Diag(Fn->getLocStart(), 4505 isa<CXXMethodDecl>(FD) ? 4506 diag::err_ovl_no_viable_member_function_in_call : 4507 diag::err_ovl_no_viable_function_in_call) 4508 << FD << FD->getSourceRange(); 4509 Diag(FD->getLocation(), 4510 diag::note_ovl_candidate_disabled_by_enable_if_attr) 4511 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 4512 } 4513 } 4514 } 4515 4516 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 4517 ExecConfig, IsExecConfig); 4518 } 4519 4520 ExprResult 4521 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 4522 MultiExprArg ExecConfig, SourceLocation GGGLoc) { 4523 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl(); 4524 if (!ConfigDecl) 4525 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use) 4526 << "cudaConfigureCall"); 4527 QualType ConfigQTy = ConfigDecl->getType(); 4528 4529 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr( 4530 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc); 4531 MarkFunctionReferenced(LLLLoc, ConfigDecl); 4532 4533 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0, 4534 /*IsExecConfig=*/true); 4535 } 4536 4537 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 4538 /// 4539 /// __builtin_astype( value, dst type ) 4540 /// 4541 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 4542 SourceLocation BuiltinLoc, 4543 SourceLocation RParenLoc) { 4544 ExprValueKind VK = VK_RValue; 4545 ExprObjectKind OK = OK_Ordinary; 4546 QualType DstTy = GetTypeFromParser(ParsedDestTy); 4547 QualType SrcTy = E->getType(); 4548 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 4549 return ExprError(Diag(BuiltinLoc, 4550 diag::err_invalid_astype_of_different_size) 4551 << DstTy 4552 << SrcTy 4553 << E->getSourceRange()); 4554 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, 4555 RParenLoc)); 4556 } 4557 4558 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 4559 /// provided arguments. 4560 /// 4561 /// __builtin_convertvector( value, dst type ) 4562 /// 4563 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 4564 SourceLocation BuiltinLoc, 4565 SourceLocation RParenLoc) { 4566 TypeSourceInfo *TInfo; 4567 GetTypeFromParser(ParsedDestTy, &TInfo); 4568 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 4569 } 4570 4571 /// BuildResolvedCallExpr - Build a call to a resolved expression, 4572 /// i.e. an expression not of \p OverloadTy. The expression should 4573 /// unary-convert to an expression of function-pointer or 4574 /// block-pointer type. 4575 /// 4576 /// \param NDecl the declaration being called, if available 4577 ExprResult 4578 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 4579 SourceLocation LParenLoc, 4580 ArrayRef<Expr *> Args, 4581 SourceLocation RParenLoc, 4582 Expr *Config, bool IsExecConfig) { 4583 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 4584 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 4585 4586 // Promote the function operand. 4587 // We special-case function promotion here because we only allow promoting 4588 // builtin functions to function pointers in the callee of a call. 4589 ExprResult Result; 4590 if (BuiltinID && 4591 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 4592 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 4593 CK_BuiltinFnToFnPtr).take(); 4594 } else { 4595 Result = CallExprUnaryConversions(Fn); 4596 } 4597 if (Result.isInvalid()) 4598 return ExprError(); 4599 Fn = Result.take(); 4600 4601 // Make the call expr early, before semantic checks. This guarantees cleanup 4602 // of arguments and function on error. 4603 CallExpr *TheCall; 4604 if (Config) 4605 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 4606 cast<CallExpr>(Config), Args, 4607 Context.BoolTy, VK_RValue, 4608 RParenLoc); 4609 else 4610 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 4611 VK_RValue, RParenLoc); 4612 4613 // Bail out early if calling a builtin with custom typechecking. 4614 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 4615 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4616 4617 retry: 4618 const FunctionType *FuncT; 4619 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 4620 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 4621 // have type pointer to function". 4622 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 4623 if (FuncT == 0) 4624 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4625 << Fn->getType() << Fn->getSourceRange()); 4626 } else if (const BlockPointerType *BPT = 4627 Fn->getType()->getAs<BlockPointerType>()) { 4628 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 4629 } else { 4630 // Handle calls to expressions of unknown-any type. 4631 if (Fn->getType() == Context.UnknownAnyTy) { 4632 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 4633 if (rewrite.isInvalid()) return ExprError(); 4634 Fn = rewrite.take(); 4635 TheCall->setCallee(Fn); 4636 goto retry; 4637 } 4638 4639 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4640 << Fn->getType() << Fn->getSourceRange()); 4641 } 4642 4643 if (getLangOpts().CUDA) { 4644 if (Config) { 4645 // CUDA: Kernel calls must be to global functions 4646 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 4647 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 4648 << FDecl->getName() << Fn->getSourceRange()); 4649 4650 // CUDA: Kernel function must have 'void' return type 4651 if (!FuncT->getReturnType()->isVoidType()) 4652 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 4653 << Fn->getType() << Fn->getSourceRange()); 4654 } else { 4655 // CUDA: Calls to global functions must be configured 4656 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 4657 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 4658 << FDecl->getName() << Fn->getSourceRange()); 4659 } 4660 } 4661 4662 // Check for a valid return type 4663 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 4664 FDecl)) 4665 return ExprError(); 4666 4667 // We know the result type of the call, set it. 4668 TheCall->setType(FuncT->getCallResultType(Context)); 4669 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 4670 4671 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 4672 if (Proto) { 4673 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 4674 IsExecConfig)) 4675 return ExprError(); 4676 } else { 4677 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 4678 4679 if (FDecl) { 4680 // Check if we have too few/too many template arguments, based 4681 // on our knowledge of the function definition. 4682 const FunctionDecl *Def = 0; 4683 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 4684 Proto = Def->getType()->getAs<FunctionProtoType>(); 4685 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 4686 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 4687 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 4688 } 4689 4690 // If the function we're calling isn't a function prototype, but we have 4691 // a function prototype from a prior declaratiom, use that prototype. 4692 if (!FDecl->hasPrototype()) 4693 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 4694 } 4695 4696 // Promote the arguments (C99 6.5.2.2p6). 4697 for (unsigned i = 0, e = Args.size(); i != e; i++) { 4698 Expr *Arg = Args[i]; 4699 4700 if (Proto && i < Proto->getNumParams()) { 4701 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4702 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 4703 ExprResult ArgE = PerformCopyInitialization(Entity, 4704 SourceLocation(), 4705 Owned(Arg)); 4706 if (ArgE.isInvalid()) 4707 return true; 4708 4709 Arg = ArgE.takeAs<Expr>(); 4710 4711 } else { 4712 ExprResult ArgE = DefaultArgumentPromotion(Arg); 4713 4714 if (ArgE.isInvalid()) 4715 return true; 4716 4717 Arg = ArgE.takeAs<Expr>(); 4718 } 4719 4720 if (RequireCompleteType(Arg->getLocStart(), 4721 Arg->getType(), 4722 diag::err_call_incomplete_argument, Arg)) 4723 return ExprError(); 4724 4725 TheCall->setArg(i, Arg); 4726 } 4727 } 4728 4729 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4730 if (!Method->isStatic()) 4731 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 4732 << Fn->getSourceRange()); 4733 4734 // Check for sentinels 4735 if (NDecl) 4736 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 4737 4738 // Do special checking on direct calls to functions. 4739 if (FDecl) { 4740 if (CheckFunctionCall(FDecl, TheCall, Proto)) 4741 return ExprError(); 4742 4743 if (BuiltinID) 4744 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4745 } else if (NDecl) { 4746 if (CheckPointerCall(NDecl, TheCall, Proto)) 4747 return ExprError(); 4748 } else { 4749 if (CheckOtherCall(TheCall, Proto)) 4750 return ExprError(); 4751 } 4752 4753 return MaybeBindToTemporary(TheCall); 4754 } 4755 4756 ExprResult 4757 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 4758 SourceLocation RParenLoc, Expr *InitExpr) { 4759 assert(Ty && "ActOnCompoundLiteral(): missing type"); 4760 // FIXME: put back this assert when initializers are worked out. 4761 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 4762 4763 TypeSourceInfo *TInfo; 4764 QualType literalType = GetTypeFromParser(Ty, &TInfo); 4765 if (!TInfo) 4766 TInfo = Context.getTrivialTypeSourceInfo(literalType); 4767 4768 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 4769 } 4770 4771 ExprResult 4772 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 4773 SourceLocation RParenLoc, Expr *LiteralExpr) { 4774 QualType literalType = TInfo->getType(); 4775 4776 if (literalType->isArrayType()) { 4777 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 4778 diag::err_illegal_decl_array_incomplete_type, 4779 SourceRange(LParenLoc, 4780 LiteralExpr->getSourceRange().getEnd()))) 4781 return ExprError(); 4782 if (literalType->isVariableArrayType()) 4783 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 4784 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 4785 } else if (!literalType->isDependentType() && 4786 RequireCompleteType(LParenLoc, literalType, 4787 diag::err_typecheck_decl_incomplete_type, 4788 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 4789 return ExprError(); 4790 4791 InitializedEntity Entity 4792 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 4793 InitializationKind Kind 4794 = InitializationKind::CreateCStyleCast(LParenLoc, 4795 SourceRange(LParenLoc, RParenLoc), 4796 /*InitList=*/true); 4797 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 4798 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 4799 &literalType); 4800 if (Result.isInvalid()) 4801 return ExprError(); 4802 LiteralExpr = Result.get(); 4803 4804 bool isFileScope = getCurFunctionOrMethodDecl() == 0; 4805 if (isFileScope && 4806 !LiteralExpr->isTypeDependent() && 4807 !LiteralExpr->isValueDependent() && 4808 !literalType->isDependentType()) { // 6.5.2.5p3 4809 if (CheckForConstantInitializer(LiteralExpr, literalType)) 4810 return ExprError(); 4811 } 4812 4813 // In C, compound literals are l-values for some reason. 4814 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 4815 4816 return MaybeBindToTemporary( 4817 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 4818 VK, LiteralExpr, isFileScope)); 4819 } 4820 4821 ExprResult 4822 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 4823 SourceLocation RBraceLoc) { 4824 // Immediately handle non-overload placeholders. Overloads can be 4825 // resolved contextually, but everything else here can't. 4826 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 4827 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 4828 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 4829 4830 // Ignore failures; dropping the entire initializer list because 4831 // of one failure would be terrible for indexing/etc. 4832 if (result.isInvalid()) continue; 4833 4834 InitArgList[I] = result.take(); 4835 } 4836 } 4837 4838 // Semantic analysis for initializers is done by ActOnDeclarator() and 4839 // CheckInitializer() - it requires knowledge of the object being intialized. 4840 4841 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 4842 RBraceLoc); 4843 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 4844 return Owned(E); 4845 } 4846 4847 /// Do an explicit extend of the given block pointer if we're in ARC. 4848 static void maybeExtendBlockObject(Sema &S, ExprResult &E) { 4849 assert(E.get()->getType()->isBlockPointerType()); 4850 assert(E.get()->isRValue()); 4851 4852 // Only do this in an r-value context. 4853 if (!S.getLangOpts().ObjCAutoRefCount) return; 4854 4855 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), 4856 CK_ARCExtendBlockObject, E.get(), 4857 /*base path*/ 0, VK_RValue); 4858 S.ExprNeedsCleanups = true; 4859 } 4860 4861 /// Prepare a conversion of the given expression to an ObjC object 4862 /// pointer type. 4863 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 4864 QualType type = E.get()->getType(); 4865 if (type->isObjCObjectPointerType()) { 4866 return CK_BitCast; 4867 } else if (type->isBlockPointerType()) { 4868 maybeExtendBlockObject(*this, E); 4869 return CK_BlockPointerToObjCPointerCast; 4870 } else { 4871 assert(type->isPointerType()); 4872 return CK_CPointerToObjCPointerCast; 4873 } 4874 } 4875 4876 /// Prepares for a scalar cast, performing all the necessary stages 4877 /// except the final cast and returning the kind required. 4878 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 4879 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 4880 // Also, callers should have filtered out the invalid cases with 4881 // pointers. Everything else should be possible. 4882 4883 QualType SrcTy = Src.get()->getType(); 4884 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 4885 return CK_NoOp; 4886 4887 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 4888 case Type::STK_MemberPointer: 4889 llvm_unreachable("member pointer type in C"); 4890 4891 case Type::STK_CPointer: 4892 case Type::STK_BlockPointer: 4893 case Type::STK_ObjCObjectPointer: 4894 switch (DestTy->getScalarTypeKind()) { 4895 case Type::STK_CPointer: { 4896 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 4897 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 4898 if (SrcAS != DestAS) 4899 return CK_AddressSpaceConversion; 4900 return CK_BitCast; 4901 } 4902 case Type::STK_BlockPointer: 4903 return (SrcKind == Type::STK_BlockPointer 4904 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 4905 case Type::STK_ObjCObjectPointer: 4906 if (SrcKind == Type::STK_ObjCObjectPointer) 4907 return CK_BitCast; 4908 if (SrcKind == Type::STK_CPointer) 4909 return CK_CPointerToObjCPointerCast; 4910 maybeExtendBlockObject(*this, Src); 4911 return CK_BlockPointerToObjCPointerCast; 4912 case Type::STK_Bool: 4913 return CK_PointerToBoolean; 4914 case Type::STK_Integral: 4915 return CK_PointerToIntegral; 4916 case Type::STK_Floating: 4917 case Type::STK_FloatingComplex: 4918 case Type::STK_IntegralComplex: 4919 case Type::STK_MemberPointer: 4920 llvm_unreachable("illegal cast from pointer"); 4921 } 4922 llvm_unreachable("Should have returned before this"); 4923 4924 case Type::STK_Bool: // casting from bool is like casting from an integer 4925 case Type::STK_Integral: 4926 switch (DestTy->getScalarTypeKind()) { 4927 case Type::STK_CPointer: 4928 case Type::STK_ObjCObjectPointer: 4929 case Type::STK_BlockPointer: 4930 if (Src.get()->isNullPointerConstant(Context, 4931 Expr::NPC_ValueDependentIsNull)) 4932 return CK_NullToPointer; 4933 return CK_IntegralToPointer; 4934 case Type::STK_Bool: 4935 return CK_IntegralToBoolean; 4936 case Type::STK_Integral: 4937 return CK_IntegralCast; 4938 case Type::STK_Floating: 4939 return CK_IntegralToFloating; 4940 case Type::STK_IntegralComplex: 4941 Src = ImpCastExprToType(Src.take(), 4942 DestTy->castAs<ComplexType>()->getElementType(), 4943 CK_IntegralCast); 4944 return CK_IntegralRealToComplex; 4945 case Type::STK_FloatingComplex: 4946 Src = ImpCastExprToType(Src.take(), 4947 DestTy->castAs<ComplexType>()->getElementType(), 4948 CK_IntegralToFloating); 4949 return CK_FloatingRealToComplex; 4950 case Type::STK_MemberPointer: 4951 llvm_unreachable("member pointer type in C"); 4952 } 4953 llvm_unreachable("Should have returned before this"); 4954 4955 case Type::STK_Floating: 4956 switch (DestTy->getScalarTypeKind()) { 4957 case Type::STK_Floating: 4958 return CK_FloatingCast; 4959 case Type::STK_Bool: 4960 return CK_FloatingToBoolean; 4961 case Type::STK_Integral: 4962 return CK_FloatingToIntegral; 4963 case Type::STK_FloatingComplex: 4964 Src = ImpCastExprToType(Src.take(), 4965 DestTy->castAs<ComplexType>()->getElementType(), 4966 CK_FloatingCast); 4967 return CK_FloatingRealToComplex; 4968 case Type::STK_IntegralComplex: 4969 Src = ImpCastExprToType(Src.take(), 4970 DestTy->castAs<ComplexType>()->getElementType(), 4971 CK_FloatingToIntegral); 4972 return CK_IntegralRealToComplex; 4973 case Type::STK_CPointer: 4974 case Type::STK_ObjCObjectPointer: 4975 case Type::STK_BlockPointer: 4976 llvm_unreachable("valid float->pointer cast?"); 4977 case Type::STK_MemberPointer: 4978 llvm_unreachable("member pointer type in C"); 4979 } 4980 llvm_unreachable("Should have returned before this"); 4981 4982 case Type::STK_FloatingComplex: 4983 switch (DestTy->getScalarTypeKind()) { 4984 case Type::STK_FloatingComplex: 4985 return CK_FloatingComplexCast; 4986 case Type::STK_IntegralComplex: 4987 return CK_FloatingComplexToIntegralComplex; 4988 case Type::STK_Floating: { 4989 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 4990 if (Context.hasSameType(ET, DestTy)) 4991 return CK_FloatingComplexToReal; 4992 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal); 4993 return CK_FloatingCast; 4994 } 4995 case Type::STK_Bool: 4996 return CK_FloatingComplexToBoolean; 4997 case Type::STK_Integral: 4998 Src = ImpCastExprToType(Src.take(), 4999 SrcTy->castAs<ComplexType>()->getElementType(), 5000 CK_FloatingComplexToReal); 5001 return CK_FloatingToIntegral; 5002 case Type::STK_CPointer: 5003 case Type::STK_ObjCObjectPointer: 5004 case Type::STK_BlockPointer: 5005 llvm_unreachable("valid complex float->pointer cast?"); 5006 case Type::STK_MemberPointer: 5007 llvm_unreachable("member pointer type in C"); 5008 } 5009 llvm_unreachable("Should have returned before this"); 5010 5011 case Type::STK_IntegralComplex: 5012 switch (DestTy->getScalarTypeKind()) { 5013 case Type::STK_FloatingComplex: 5014 return CK_IntegralComplexToFloatingComplex; 5015 case Type::STK_IntegralComplex: 5016 return CK_IntegralComplexCast; 5017 case Type::STK_Integral: { 5018 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5019 if (Context.hasSameType(ET, DestTy)) 5020 return CK_IntegralComplexToReal; 5021 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal); 5022 return CK_IntegralCast; 5023 } 5024 case Type::STK_Bool: 5025 return CK_IntegralComplexToBoolean; 5026 case Type::STK_Floating: 5027 Src = ImpCastExprToType(Src.take(), 5028 SrcTy->castAs<ComplexType>()->getElementType(), 5029 CK_IntegralComplexToReal); 5030 return CK_IntegralToFloating; 5031 case Type::STK_CPointer: 5032 case Type::STK_ObjCObjectPointer: 5033 case Type::STK_BlockPointer: 5034 llvm_unreachable("valid complex int->pointer cast?"); 5035 case Type::STK_MemberPointer: 5036 llvm_unreachable("member pointer type in C"); 5037 } 5038 llvm_unreachable("Should have returned before this"); 5039 } 5040 5041 llvm_unreachable("Unhandled scalar cast"); 5042 } 5043 5044 static bool breakDownVectorType(QualType type, uint64_t &len, 5045 QualType &eltType) { 5046 // Vectors are simple. 5047 if (const VectorType *vecType = type->getAs<VectorType>()) { 5048 len = vecType->getNumElements(); 5049 eltType = vecType->getElementType(); 5050 assert(eltType->isScalarType()); 5051 return true; 5052 } 5053 5054 // We allow lax conversion to and from non-vector types, but only if 5055 // they're real types (i.e. non-complex, non-pointer scalar types). 5056 if (!type->isRealType()) return false; 5057 5058 len = 1; 5059 eltType = type; 5060 return true; 5061 } 5062 5063 static bool VectorTypesMatch(Sema &S, QualType srcTy, QualType destTy) { 5064 uint64_t srcLen, destLen; 5065 QualType srcElt, destElt; 5066 if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false; 5067 if (!breakDownVectorType(destTy, destLen, destElt)) return false; 5068 5069 // ASTContext::getTypeSize will return the size rounded up to a 5070 // power of 2, so instead of using that, we need to use the raw 5071 // element size multiplied by the element count. 5072 uint64_t srcEltSize = S.Context.getTypeSize(srcElt); 5073 uint64_t destEltSize = S.Context.getTypeSize(destElt); 5074 5075 return (srcLen * srcEltSize == destLen * destEltSize); 5076 } 5077 5078 /// Is this a legal conversion between two known vector types? 5079 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5080 assert(destTy->isVectorType() || srcTy->isVectorType()); 5081 5082 if (!Context.getLangOpts().LaxVectorConversions) 5083 return false; 5084 return VectorTypesMatch(*this, srcTy, destTy); 5085 } 5086 5087 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5088 CastKind &Kind) { 5089 assert(VectorTy->isVectorType() && "Not a vector type!"); 5090 5091 if (Ty->isVectorType() || Ty->isIntegerType()) { 5092 if (!VectorTypesMatch(*this, Ty, VectorTy)) 5093 return Diag(R.getBegin(), 5094 Ty->isVectorType() ? 5095 diag::err_invalid_conversion_between_vectors : 5096 diag::err_invalid_conversion_between_vector_and_integer) 5097 << VectorTy << Ty << R; 5098 } else 5099 return Diag(R.getBegin(), 5100 diag::err_invalid_conversion_between_vector_and_scalar) 5101 << VectorTy << Ty << R; 5102 5103 Kind = CK_BitCast; 5104 return false; 5105 } 5106 5107 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5108 Expr *CastExpr, CastKind &Kind) { 5109 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5110 5111 QualType SrcTy = CastExpr->getType(); 5112 5113 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5114 // an ExtVectorType. 5115 // In OpenCL, casts between vectors of different types are not allowed. 5116 // (See OpenCL 6.2). 5117 if (SrcTy->isVectorType()) { 5118 if (!VectorTypesMatch(*this, SrcTy, DestTy) 5119 || (getLangOpts().OpenCL && 5120 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5121 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5122 << DestTy << SrcTy << R; 5123 return ExprError(); 5124 } 5125 Kind = CK_BitCast; 5126 return Owned(CastExpr); 5127 } 5128 5129 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5130 // conversion will take place first from scalar to elt type, and then 5131 // splat from elt type to vector. 5132 if (SrcTy->isPointerType()) 5133 return Diag(R.getBegin(), 5134 diag::err_invalid_conversion_between_vector_and_scalar) 5135 << DestTy << SrcTy << R; 5136 5137 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 5138 ExprResult CastExprRes = Owned(CastExpr); 5139 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 5140 if (CastExprRes.isInvalid()) 5141 return ExprError(); 5142 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take(); 5143 5144 Kind = CK_VectorSplat; 5145 return Owned(CastExpr); 5146 } 5147 5148 ExprResult 5149 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5150 Declarator &D, ParsedType &Ty, 5151 SourceLocation RParenLoc, Expr *CastExpr) { 5152 assert(!D.isInvalidType() && (CastExpr != 0) && 5153 "ActOnCastExpr(): missing type or expr"); 5154 5155 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5156 if (D.isInvalidType()) 5157 return ExprError(); 5158 5159 if (getLangOpts().CPlusPlus) { 5160 // Check that there are no default arguments (C++ only). 5161 CheckExtraCXXDefaultArguments(D); 5162 } 5163 5164 checkUnusedDeclAttributes(D); 5165 5166 QualType castType = castTInfo->getType(); 5167 Ty = CreateParsedType(castType, castTInfo); 5168 5169 bool isVectorLiteral = false; 5170 5171 // Check for an altivec or OpenCL literal, 5172 // i.e. all the elements are integer constants. 5173 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5174 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5175 if ((getLangOpts().AltiVec || getLangOpts().OpenCL) 5176 && castType->isVectorType() && (PE || PLE)) { 5177 if (PLE && PLE->getNumExprs() == 0) { 5178 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 5179 return ExprError(); 5180 } 5181 if (PE || PLE->getNumExprs() == 1) { 5182 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 5183 if (!E->getType()->isVectorType()) 5184 isVectorLiteral = true; 5185 } 5186 else 5187 isVectorLiteral = true; 5188 } 5189 5190 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 5191 // then handle it as such. 5192 if (isVectorLiteral) 5193 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 5194 5195 // If the Expr being casted is a ParenListExpr, handle it specially. 5196 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 5197 // sequence of BinOp comma operators. 5198 if (isa<ParenListExpr>(CastExpr)) { 5199 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 5200 if (Result.isInvalid()) return ExprError(); 5201 CastExpr = Result.take(); 5202 } 5203 5204 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 5205 !getSourceManager().isInSystemMacro(LParenLoc)) 5206 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 5207 5208 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 5209 } 5210 5211 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 5212 SourceLocation RParenLoc, Expr *E, 5213 TypeSourceInfo *TInfo) { 5214 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 5215 "Expected paren or paren list expression"); 5216 5217 Expr **exprs; 5218 unsigned numExprs; 5219 Expr *subExpr; 5220 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 5221 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 5222 LiteralLParenLoc = PE->getLParenLoc(); 5223 LiteralRParenLoc = PE->getRParenLoc(); 5224 exprs = PE->getExprs(); 5225 numExprs = PE->getNumExprs(); 5226 } else { // isa<ParenExpr> by assertion at function entrance 5227 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 5228 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 5229 subExpr = cast<ParenExpr>(E)->getSubExpr(); 5230 exprs = &subExpr; 5231 numExprs = 1; 5232 } 5233 5234 QualType Ty = TInfo->getType(); 5235 assert(Ty->isVectorType() && "Expected vector type"); 5236 5237 SmallVector<Expr *, 8> initExprs; 5238 const VectorType *VTy = Ty->getAs<VectorType>(); 5239 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 5240 5241 // '(...)' form of vector initialization in AltiVec: the number of 5242 // initializers must be one or must match the size of the vector. 5243 // If a single value is specified in the initializer then it will be 5244 // replicated to all the components of the vector 5245 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 5246 // The number of initializers must be one or must match the size of the 5247 // vector. If a single value is specified in the initializer then it will 5248 // be replicated to all the components of the vector 5249 if (numExprs == 1) { 5250 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5251 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5252 if (Literal.isInvalid()) 5253 return ExprError(); 5254 Literal = ImpCastExprToType(Literal.take(), ElemTy, 5255 PrepareScalarCast(Literal, ElemTy)); 5256 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 5257 } 5258 else if (numExprs < numElems) { 5259 Diag(E->getExprLoc(), 5260 diag::err_incorrect_number_of_vector_initializers); 5261 return ExprError(); 5262 } 5263 else 5264 initExprs.append(exprs, exprs + numExprs); 5265 } 5266 else { 5267 // For OpenCL, when the number of initializers is a single value, 5268 // it will be replicated to all components of the vector. 5269 if (getLangOpts().OpenCL && 5270 VTy->getVectorKind() == VectorType::GenericVector && 5271 numExprs == 1) { 5272 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5273 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5274 if (Literal.isInvalid()) 5275 return ExprError(); 5276 Literal = ImpCastExprToType(Literal.take(), ElemTy, 5277 PrepareScalarCast(Literal, ElemTy)); 5278 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take()); 5279 } 5280 5281 initExprs.append(exprs, exprs + numExprs); 5282 } 5283 // FIXME: This means that pretty-printing the final AST will produce curly 5284 // braces instead of the original commas. 5285 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 5286 initExprs, LiteralRParenLoc); 5287 initE->setType(Ty); 5288 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 5289 } 5290 5291 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 5292 /// the ParenListExpr into a sequence of comma binary operators. 5293 ExprResult 5294 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 5295 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 5296 if (!E) 5297 return Owned(OrigExpr); 5298 5299 ExprResult Result(E->getExpr(0)); 5300 5301 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 5302 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 5303 E->getExpr(i)); 5304 5305 if (Result.isInvalid()) return ExprError(); 5306 5307 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 5308 } 5309 5310 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 5311 SourceLocation R, 5312 MultiExprArg Val) { 5313 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 5314 return Owned(expr); 5315 } 5316 5317 /// \brief Emit a specialized diagnostic when one expression is a null pointer 5318 /// constant and the other is not a pointer. Returns true if a diagnostic is 5319 /// emitted. 5320 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 5321 SourceLocation QuestionLoc) { 5322 Expr *NullExpr = LHSExpr; 5323 Expr *NonPointerExpr = RHSExpr; 5324 Expr::NullPointerConstantKind NullKind = 5325 NullExpr->isNullPointerConstant(Context, 5326 Expr::NPC_ValueDependentIsNotNull); 5327 5328 if (NullKind == Expr::NPCK_NotNull) { 5329 NullExpr = RHSExpr; 5330 NonPointerExpr = LHSExpr; 5331 NullKind = 5332 NullExpr->isNullPointerConstant(Context, 5333 Expr::NPC_ValueDependentIsNotNull); 5334 } 5335 5336 if (NullKind == Expr::NPCK_NotNull) 5337 return false; 5338 5339 if (NullKind == Expr::NPCK_ZeroExpression) 5340 return false; 5341 5342 if (NullKind == Expr::NPCK_ZeroLiteral) { 5343 // In this case, check to make sure that we got here from a "NULL" 5344 // string in the source code. 5345 NullExpr = NullExpr->IgnoreParenImpCasts(); 5346 SourceLocation loc = NullExpr->getExprLoc(); 5347 if (!findMacroSpelling(loc, "NULL")) 5348 return false; 5349 } 5350 5351 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 5352 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 5353 << NonPointerExpr->getType() << DiagType 5354 << NonPointerExpr->getSourceRange(); 5355 return true; 5356 } 5357 5358 /// \brief Return false if the condition expression is valid, true otherwise. 5359 static bool checkCondition(Sema &S, Expr *Cond) { 5360 QualType CondTy = Cond->getType(); 5361 5362 // C99 6.5.15p2 5363 if (CondTy->isScalarType()) return false; 5364 5365 // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar. 5366 if (S.getLangOpts().OpenCL && CondTy->isVectorType()) 5367 return false; 5368 5369 // Emit the proper error message. 5370 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ? 5371 diag::err_typecheck_cond_expect_scalar : 5372 diag::err_typecheck_cond_expect_scalar_or_vector) 5373 << CondTy; 5374 return true; 5375 } 5376 5377 /// \brief Return false if the two expressions can be converted to a vector, 5378 /// true otherwise 5379 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS, 5380 ExprResult &RHS, 5381 QualType CondTy) { 5382 // Both operands should be of scalar type. 5383 if (!LHS.get()->getType()->isScalarType()) { 5384 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5385 << CondTy; 5386 return true; 5387 } 5388 if (!RHS.get()->getType()->isScalarType()) { 5389 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5390 << CondTy; 5391 return true; 5392 } 5393 5394 // Implicity convert these scalars to the type of the condition. 5395 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast); 5396 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast); 5397 return false; 5398 } 5399 5400 /// \brief Handle when one or both operands are void type. 5401 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 5402 ExprResult &RHS) { 5403 Expr *LHSExpr = LHS.get(); 5404 Expr *RHSExpr = RHS.get(); 5405 5406 if (!LHSExpr->getType()->isVoidType()) 5407 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5408 << RHSExpr->getSourceRange(); 5409 if (!RHSExpr->getType()->isVoidType()) 5410 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5411 << LHSExpr->getSourceRange(); 5412 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid); 5413 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid); 5414 return S.Context.VoidTy; 5415 } 5416 5417 /// \brief Return false if the NullExpr can be promoted to PointerTy, 5418 /// true otherwise. 5419 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 5420 QualType PointerTy) { 5421 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 5422 !NullExpr.get()->isNullPointerConstant(S.Context, 5423 Expr::NPC_ValueDependentIsNull)) 5424 return true; 5425 5426 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer); 5427 return false; 5428 } 5429 5430 /// \brief Checks compatibility between two pointers and return the resulting 5431 /// type. 5432 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 5433 ExprResult &RHS, 5434 SourceLocation Loc) { 5435 QualType LHSTy = LHS.get()->getType(); 5436 QualType RHSTy = RHS.get()->getType(); 5437 5438 if (S.Context.hasSameType(LHSTy, RHSTy)) { 5439 // Two identical pointers types are always compatible. 5440 return LHSTy; 5441 } 5442 5443 QualType lhptee, rhptee; 5444 5445 // Get the pointee types. 5446 bool IsBlockPointer = false; 5447 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 5448 lhptee = LHSBTy->getPointeeType(); 5449 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 5450 IsBlockPointer = true; 5451 } else { 5452 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 5453 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 5454 } 5455 5456 // C99 6.5.15p6: If both operands are pointers to compatible types or to 5457 // differently qualified versions of compatible types, the result type is 5458 // a pointer to an appropriately qualified version of the composite 5459 // type. 5460 5461 // Only CVR-qualifiers exist in the standard, and the differently-qualified 5462 // clause doesn't make sense for our extensions. E.g. address space 2 should 5463 // be incompatible with address space 3: they may live on different devices or 5464 // anything. 5465 Qualifiers lhQual = lhptee.getQualifiers(); 5466 Qualifiers rhQual = rhptee.getQualifiers(); 5467 5468 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 5469 lhQual.removeCVRQualifiers(); 5470 rhQual.removeCVRQualifiers(); 5471 5472 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 5473 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 5474 5475 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 5476 5477 if (CompositeTy.isNull()) { 5478 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers) 5479 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5480 << RHS.get()->getSourceRange(); 5481 // In this situation, we assume void* type. No especially good 5482 // reason, but this is what gcc does, and we do have to pick 5483 // to get a consistent AST. 5484 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 5485 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5486 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5487 return incompatTy; 5488 } 5489 5490 // The pointer types are compatible. 5491 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 5492 if (IsBlockPointer) 5493 ResultTy = S.Context.getBlockPointerType(ResultTy); 5494 else 5495 ResultTy = S.Context.getPointerType(ResultTy); 5496 5497 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast); 5498 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast); 5499 return ResultTy; 5500 } 5501 5502 /// \brief Return the resulting type when the operands are both block pointers. 5503 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 5504 ExprResult &LHS, 5505 ExprResult &RHS, 5506 SourceLocation Loc) { 5507 QualType LHSTy = LHS.get()->getType(); 5508 QualType RHSTy = RHS.get()->getType(); 5509 5510 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 5511 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 5512 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 5513 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5514 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5515 return destType; 5516 } 5517 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 5518 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5519 << RHS.get()->getSourceRange(); 5520 return QualType(); 5521 } 5522 5523 // We have 2 block pointer types. 5524 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5525 } 5526 5527 /// \brief Return the resulting type when the operands are both pointers. 5528 static QualType 5529 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 5530 ExprResult &RHS, 5531 SourceLocation Loc) { 5532 // get the pointer types 5533 QualType LHSTy = LHS.get()->getType(); 5534 QualType RHSTy = RHS.get()->getType(); 5535 5536 // get the "pointed to" types 5537 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5538 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5539 5540 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 5541 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 5542 // Figure out necessary qualifiers (C99 6.5.15p6) 5543 QualType destPointee 5544 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5545 QualType destType = S.Context.getPointerType(destPointee); 5546 // Add qualifiers if necessary. 5547 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5548 // Promote to void*. 5549 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5550 return destType; 5551 } 5552 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 5553 QualType destPointee 5554 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5555 QualType destType = S.Context.getPointerType(destPointee); 5556 // Add qualifiers if necessary. 5557 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5558 // Promote to void*. 5559 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5560 return destType; 5561 } 5562 5563 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5564 } 5565 5566 /// \brief Return false if the first expression is not an integer and the second 5567 /// expression is not a pointer, true otherwise. 5568 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 5569 Expr* PointerExpr, SourceLocation Loc, 5570 bool IsIntFirstExpr) { 5571 if (!PointerExpr->getType()->isPointerType() || 5572 !Int.get()->getType()->isIntegerType()) 5573 return false; 5574 5575 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 5576 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 5577 5578 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch) 5579 << Expr1->getType() << Expr2->getType() 5580 << Expr1->getSourceRange() << Expr2->getSourceRange(); 5581 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(), 5582 CK_IntegralToPointer); 5583 return true; 5584 } 5585 5586 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 5587 /// In that case, LHS = cond. 5588 /// C99 6.5.15 5589 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 5590 ExprResult &RHS, ExprValueKind &VK, 5591 ExprObjectKind &OK, 5592 SourceLocation QuestionLoc) { 5593 5594 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 5595 if (!LHSResult.isUsable()) return QualType(); 5596 LHS = LHSResult; 5597 5598 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 5599 if (!RHSResult.isUsable()) return QualType(); 5600 RHS = RHSResult; 5601 5602 // C++ is sufficiently different to merit its own checker. 5603 if (getLangOpts().CPlusPlus) 5604 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 5605 5606 VK = VK_RValue; 5607 OK = OK_Ordinary; 5608 5609 // First, check the condition. 5610 Cond = UsualUnaryConversions(Cond.take()); 5611 if (Cond.isInvalid()) 5612 return QualType(); 5613 if (checkCondition(*this, Cond.get())) 5614 return QualType(); 5615 5616 // Now check the two expressions. 5617 if (LHS.get()->getType()->isVectorType() || 5618 RHS.get()->getType()->isVectorType()) 5619 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false); 5620 5621 UsualArithmeticConversions(LHS, RHS); 5622 if (LHS.isInvalid() || RHS.isInvalid()) 5623 return QualType(); 5624 5625 QualType CondTy = Cond.get()->getType(); 5626 QualType LHSTy = LHS.get()->getType(); 5627 QualType RHSTy = RHS.get()->getType(); 5628 5629 // If the condition is a vector, and both operands are scalar, 5630 // attempt to implicity convert them to the vector type to act like the 5631 // built in select. (OpenCL v1.1 s6.3.i) 5632 if (getLangOpts().OpenCL && CondTy->isVectorType()) 5633 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy)) 5634 return QualType(); 5635 5636 // If both operands have arithmetic type, do the usual arithmetic conversions 5637 // to find a common type: C99 6.5.15p3,5. 5638 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) 5639 return LHS.get()->getType(); 5640 5641 // If both operands are the same structure or union type, the result is that 5642 // type. 5643 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 5644 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 5645 if (LHSRT->getDecl() == RHSRT->getDecl()) 5646 // "If both the operands have structure or union type, the result has 5647 // that type." This implies that CV qualifiers are dropped. 5648 return LHSTy.getUnqualifiedType(); 5649 // FIXME: Type of conditional expression must be complete in C mode. 5650 } 5651 5652 // C99 6.5.15p5: "If both operands have void type, the result has void type." 5653 // The following || allows only one side to be void (a GCC-ism). 5654 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 5655 return checkConditionalVoidType(*this, LHS, RHS); 5656 } 5657 5658 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 5659 // the type of the other operand." 5660 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 5661 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 5662 5663 // All objective-c pointer type analysis is done here. 5664 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 5665 QuestionLoc); 5666 if (LHS.isInvalid() || RHS.isInvalid()) 5667 return QualType(); 5668 if (!compositeType.isNull()) 5669 return compositeType; 5670 5671 5672 // Handle block pointer types. 5673 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 5674 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 5675 QuestionLoc); 5676 5677 // Check constraints for C object pointers types (C99 6.5.15p3,6). 5678 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 5679 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 5680 QuestionLoc); 5681 5682 // GCC compatibility: soften pointer/integer mismatch. Note that 5683 // null pointers have been filtered out by this point. 5684 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 5685 /*isIntFirstExpr=*/true)) 5686 return RHSTy; 5687 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 5688 /*isIntFirstExpr=*/false)) 5689 return LHSTy; 5690 5691 // Emit a better diagnostic if one of the expressions is a null pointer 5692 // constant and the other is not a pointer type. In this case, the user most 5693 // likely forgot to take the address of the other expression. 5694 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 5695 return QualType(); 5696 5697 // Otherwise, the operands are not compatible. 5698 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 5699 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5700 << RHS.get()->getSourceRange(); 5701 return QualType(); 5702 } 5703 5704 /// FindCompositeObjCPointerType - Helper method to find composite type of 5705 /// two objective-c pointer types of the two input expressions. 5706 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 5707 SourceLocation QuestionLoc) { 5708 QualType LHSTy = LHS.get()->getType(); 5709 QualType RHSTy = RHS.get()->getType(); 5710 5711 // Handle things like Class and struct objc_class*. Here we case the result 5712 // to the pseudo-builtin, because that will be implicitly cast back to the 5713 // redefinition type if an attempt is made to access its fields. 5714 if (LHSTy->isObjCClassType() && 5715 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 5716 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5717 return LHSTy; 5718 } 5719 if (RHSTy->isObjCClassType() && 5720 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 5721 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5722 return RHSTy; 5723 } 5724 // And the same for struct objc_object* / id 5725 if (LHSTy->isObjCIdType() && 5726 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 5727 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast); 5728 return LHSTy; 5729 } 5730 if (RHSTy->isObjCIdType() && 5731 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 5732 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast); 5733 return RHSTy; 5734 } 5735 // And the same for struct objc_selector* / SEL 5736 if (Context.isObjCSelType(LHSTy) && 5737 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 5738 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast); 5739 return LHSTy; 5740 } 5741 if (Context.isObjCSelType(RHSTy) && 5742 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 5743 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast); 5744 return RHSTy; 5745 } 5746 // Check constraints for Objective-C object pointers types. 5747 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 5748 5749 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 5750 // Two identical object pointer types are always compatible. 5751 return LHSTy; 5752 } 5753 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 5754 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 5755 QualType compositeType = LHSTy; 5756 5757 // If both operands are interfaces and either operand can be 5758 // assigned to the other, use that type as the composite 5759 // type. This allows 5760 // xxx ? (A*) a : (B*) b 5761 // where B is a subclass of A. 5762 // 5763 // Additionally, as for assignment, if either type is 'id' 5764 // allow silent coercion. Finally, if the types are 5765 // incompatible then make sure to use 'id' as the composite 5766 // type so the result is acceptable for sending messages to. 5767 5768 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 5769 // It could return the composite type. 5770 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 5771 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 5772 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 5773 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 5774 } else if ((LHSTy->isObjCQualifiedIdType() || 5775 RHSTy->isObjCQualifiedIdType()) && 5776 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 5777 // Need to handle "id<xx>" explicitly. 5778 // GCC allows qualified id and any Objective-C type to devolve to 5779 // id. Currently localizing to here until clear this should be 5780 // part of ObjCQualifiedIdTypesAreCompatible. 5781 compositeType = Context.getObjCIdType(); 5782 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 5783 compositeType = Context.getObjCIdType(); 5784 } else if (!(compositeType = 5785 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 5786 ; 5787 else { 5788 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 5789 << LHSTy << RHSTy 5790 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5791 QualType incompatTy = Context.getObjCIdType(); 5792 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast); 5793 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast); 5794 return incompatTy; 5795 } 5796 // The object pointer types are compatible. 5797 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast); 5798 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast); 5799 return compositeType; 5800 } 5801 // Check Objective-C object pointer types and 'void *' 5802 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 5803 if (getLangOpts().ObjCAutoRefCount) { 5804 // ARC forbids the implicit conversion of object pointers to 'void *', 5805 // so these types are not compatible. 5806 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5807 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5808 LHS = RHS = true; 5809 return QualType(); 5810 } 5811 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5812 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5813 QualType destPointee 5814 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5815 QualType destType = Context.getPointerType(destPointee); 5816 // Add qualifiers if necessary. 5817 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp); 5818 // Promote to void*. 5819 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast); 5820 return destType; 5821 } 5822 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 5823 if (getLangOpts().ObjCAutoRefCount) { 5824 // ARC forbids the implicit conversion of object pointers to 'void *', 5825 // so these types are not compatible. 5826 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5827 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5828 LHS = RHS = true; 5829 return QualType(); 5830 } 5831 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5832 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5833 QualType destPointee 5834 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5835 QualType destType = Context.getPointerType(destPointee); 5836 // Add qualifiers if necessary. 5837 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp); 5838 // Promote to void*. 5839 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast); 5840 return destType; 5841 } 5842 return QualType(); 5843 } 5844 5845 /// SuggestParentheses - Emit a note with a fixit hint that wraps 5846 /// ParenRange in parentheses. 5847 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 5848 const PartialDiagnostic &Note, 5849 SourceRange ParenRange) { 5850 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 5851 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 5852 EndLoc.isValid()) { 5853 Self.Diag(Loc, Note) 5854 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 5855 << FixItHint::CreateInsertion(EndLoc, ")"); 5856 } else { 5857 // We can't display the parentheses, so just show the bare note. 5858 Self.Diag(Loc, Note) << ParenRange; 5859 } 5860 } 5861 5862 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 5863 return Opc >= BO_Mul && Opc <= BO_Shr; 5864 } 5865 5866 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 5867 /// expression, either using a built-in or overloaded operator, 5868 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 5869 /// expression. 5870 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 5871 Expr **RHSExprs) { 5872 // Don't strip parenthesis: we should not warn if E is in parenthesis. 5873 E = E->IgnoreImpCasts(); 5874 E = E->IgnoreConversionOperator(); 5875 E = E->IgnoreImpCasts(); 5876 5877 // Built-in binary operator. 5878 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 5879 if (IsArithmeticOp(OP->getOpcode())) { 5880 *Opcode = OP->getOpcode(); 5881 *RHSExprs = OP->getRHS(); 5882 return true; 5883 } 5884 } 5885 5886 // Overloaded operator. 5887 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 5888 if (Call->getNumArgs() != 2) 5889 return false; 5890 5891 // Make sure this is really a binary operator that is safe to pass into 5892 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 5893 OverloadedOperatorKind OO = Call->getOperator(); 5894 if (OO < OO_Plus || OO > OO_Arrow || 5895 OO == OO_PlusPlus || OO == OO_MinusMinus) 5896 return false; 5897 5898 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 5899 if (IsArithmeticOp(OpKind)) { 5900 *Opcode = OpKind; 5901 *RHSExprs = Call->getArg(1); 5902 return true; 5903 } 5904 } 5905 5906 return false; 5907 } 5908 5909 static bool IsLogicOp(BinaryOperatorKind Opc) { 5910 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 5911 } 5912 5913 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 5914 /// or is a logical expression such as (x==y) which has int type, but is 5915 /// commonly interpreted as boolean. 5916 static bool ExprLooksBoolean(Expr *E) { 5917 E = E->IgnoreParenImpCasts(); 5918 5919 if (E->getType()->isBooleanType()) 5920 return true; 5921 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 5922 return IsLogicOp(OP->getOpcode()); 5923 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 5924 return OP->getOpcode() == UO_LNot; 5925 5926 return false; 5927 } 5928 5929 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 5930 /// and binary operator are mixed in a way that suggests the programmer assumed 5931 /// the conditional operator has higher precedence, for example: 5932 /// "int x = a + someBinaryCondition ? 1 : 2". 5933 static void DiagnoseConditionalPrecedence(Sema &Self, 5934 SourceLocation OpLoc, 5935 Expr *Condition, 5936 Expr *LHSExpr, 5937 Expr *RHSExpr) { 5938 BinaryOperatorKind CondOpcode; 5939 Expr *CondRHS; 5940 5941 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 5942 return; 5943 if (!ExprLooksBoolean(CondRHS)) 5944 return; 5945 5946 // The condition is an arithmetic binary expression, with a right- 5947 // hand side that looks boolean, so warn. 5948 5949 Self.Diag(OpLoc, diag::warn_precedence_conditional) 5950 << Condition->getSourceRange() 5951 << BinaryOperator::getOpcodeStr(CondOpcode); 5952 5953 SuggestParentheses(Self, OpLoc, 5954 Self.PDiag(diag::note_precedence_silence) 5955 << BinaryOperator::getOpcodeStr(CondOpcode), 5956 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 5957 5958 SuggestParentheses(Self, OpLoc, 5959 Self.PDiag(diag::note_precedence_conditional_first), 5960 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 5961 } 5962 5963 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 5964 /// in the case of a the GNU conditional expr extension. 5965 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 5966 SourceLocation ColonLoc, 5967 Expr *CondExpr, Expr *LHSExpr, 5968 Expr *RHSExpr) { 5969 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 5970 // was the condition. 5971 OpaqueValueExpr *opaqueValue = 0; 5972 Expr *commonExpr = 0; 5973 if (LHSExpr == 0) { 5974 commonExpr = CondExpr; 5975 // Lower out placeholder types first. This is important so that we don't 5976 // try to capture a placeholder. This happens in few cases in C++; such 5977 // as Objective-C++'s dictionary subscripting syntax. 5978 if (commonExpr->hasPlaceholderType()) { 5979 ExprResult result = CheckPlaceholderExpr(commonExpr); 5980 if (!result.isUsable()) return ExprError(); 5981 commonExpr = result.take(); 5982 } 5983 // We usually want to apply unary conversions *before* saving, except 5984 // in the special case of a C++ l-value conditional. 5985 if (!(getLangOpts().CPlusPlus 5986 && !commonExpr->isTypeDependent() 5987 && commonExpr->getValueKind() == RHSExpr->getValueKind() 5988 && commonExpr->isGLValue() 5989 && commonExpr->isOrdinaryOrBitFieldObject() 5990 && RHSExpr->isOrdinaryOrBitFieldObject() 5991 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 5992 ExprResult commonRes = UsualUnaryConversions(commonExpr); 5993 if (commonRes.isInvalid()) 5994 return ExprError(); 5995 commonExpr = commonRes.take(); 5996 } 5997 5998 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 5999 commonExpr->getType(), 6000 commonExpr->getValueKind(), 6001 commonExpr->getObjectKind(), 6002 commonExpr); 6003 LHSExpr = CondExpr = opaqueValue; 6004 } 6005 6006 ExprValueKind VK = VK_RValue; 6007 ExprObjectKind OK = OK_Ordinary; 6008 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 6009 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 6010 VK, OK, QuestionLoc); 6011 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 6012 RHS.isInvalid()) 6013 return ExprError(); 6014 6015 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 6016 RHS.get()); 6017 6018 if (!commonExpr) 6019 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc, 6020 LHS.take(), ColonLoc, 6021 RHS.take(), result, VK, OK)); 6022 6023 return Owned(new (Context) 6024 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(), 6025 RHS.take(), QuestionLoc, ColonLoc, result, VK, 6026 OK)); 6027 } 6028 6029 // checkPointerTypesForAssignment - This is a very tricky routine (despite 6030 // being closely modeled after the C99 spec:-). The odd characteristic of this 6031 // routine is it effectively iqnores the qualifiers on the top level pointee. 6032 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 6033 // FIXME: add a couple examples in this comment. 6034 static Sema::AssignConvertType 6035 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 6036 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6037 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6038 6039 // get the "pointed to" type (ignoring qualifiers at the top level) 6040 const Type *lhptee, *rhptee; 6041 Qualifiers lhq, rhq; 6042 std::tie(lhptee, lhq) = 6043 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 6044 std::tie(rhptee, rhq) = 6045 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 6046 6047 Sema::AssignConvertType ConvTy = Sema::Compatible; 6048 6049 // C99 6.5.16.1p1: This following citation is common to constraints 6050 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 6051 // qualifiers of the type *pointed to* by the right; 6052 6053 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 6054 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 6055 lhq.compatiblyIncludesObjCLifetime(rhq)) { 6056 // Ignore lifetime for further calculation. 6057 lhq.removeObjCLifetime(); 6058 rhq.removeObjCLifetime(); 6059 } 6060 6061 if (!lhq.compatiblyIncludes(rhq)) { 6062 // Treat address-space mismatches as fatal. TODO: address subspaces 6063 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 6064 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6065 6066 // It's okay to add or remove GC or lifetime qualifiers when converting to 6067 // and from void*. 6068 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 6069 .compatiblyIncludes( 6070 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 6071 && (lhptee->isVoidType() || rhptee->isVoidType())) 6072 ; // keep old 6073 6074 // Treat lifetime mismatches as fatal. 6075 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 6076 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6077 6078 // For GCC compatibility, other qualifier mismatches are treated 6079 // as still compatible in C. 6080 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6081 } 6082 6083 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 6084 // incomplete type and the other is a pointer to a qualified or unqualified 6085 // version of void... 6086 if (lhptee->isVoidType()) { 6087 if (rhptee->isIncompleteOrObjectType()) 6088 return ConvTy; 6089 6090 // As an extension, we allow cast to/from void* to function pointer. 6091 assert(rhptee->isFunctionType()); 6092 return Sema::FunctionVoidPointer; 6093 } 6094 6095 if (rhptee->isVoidType()) { 6096 if (lhptee->isIncompleteOrObjectType()) 6097 return ConvTy; 6098 6099 // As an extension, we allow cast to/from void* to function pointer. 6100 assert(lhptee->isFunctionType()); 6101 return Sema::FunctionVoidPointer; 6102 } 6103 6104 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 6105 // unqualified versions of compatible types, ... 6106 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 6107 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 6108 // Check if the pointee types are compatible ignoring the sign. 6109 // We explicitly check for char so that we catch "char" vs 6110 // "unsigned char" on systems where "char" is unsigned. 6111 if (lhptee->isCharType()) 6112 ltrans = S.Context.UnsignedCharTy; 6113 else if (lhptee->hasSignedIntegerRepresentation()) 6114 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 6115 6116 if (rhptee->isCharType()) 6117 rtrans = S.Context.UnsignedCharTy; 6118 else if (rhptee->hasSignedIntegerRepresentation()) 6119 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 6120 6121 if (ltrans == rtrans) { 6122 // Types are compatible ignoring the sign. Qualifier incompatibility 6123 // takes priority over sign incompatibility because the sign 6124 // warning can be disabled. 6125 if (ConvTy != Sema::Compatible) 6126 return ConvTy; 6127 6128 return Sema::IncompatiblePointerSign; 6129 } 6130 6131 // If we are a multi-level pointer, it's possible that our issue is simply 6132 // one of qualification - e.g. char ** -> const char ** is not allowed. If 6133 // the eventual target type is the same and the pointers have the same 6134 // level of indirection, this must be the issue. 6135 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 6136 do { 6137 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 6138 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 6139 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 6140 6141 if (lhptee == rhptee) 6142 return Sema::IncompatibleNestedPointerQualifiers; 6143 } 6144 6145 // General pointer incompatibility takes priority over qualifiers. 6146 return Sema::IncompatiblePointer; 6147 } 6148 if (!S.getLangOpts().CPlusPlus && 6149 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 6150 return Sema::IncompatiblePointer; 6151 return ConvTy; 6152 } 6153 6154 /// checkBlockPointerTypesForAssignment - This routine determines whether two 6155 /// block pointer types are compatible or whether a block and normal pointer 6156 /// are compatible. It is more restrict than comparing two function pointer 6157 // types. 6158 static Sema::AssignConvertType 6159 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 6160 QualType RHSType) { 6161 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6162 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6163 6164 QualType lhptee, rhptee; 6165 6166 // get the "pointed to" type (ignoring qualifiers at the top level) 6167 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 6168 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 6169 6170 // In C++, the types have to match exactly. 6171 if (S.getLangOpts().CPlusPlus) 6172 return Sema::IncompatibleBlockPointer; 6173 6174 Sema::AssignConvertType ConvTy = Sema::Compatible; 6175 6176 // For blocks we enforce that qualifiers are identical. 6177 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 6178 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6179 6180 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 6181 return Sema::IncompatibleBlockPointer; 6182 6183 return ConvTy; 6184 } 6185 6186 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 6187 /// for assignment compatibility. 6188 static Sema::AssignConvertType 6189 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 6190 QualType RHSType) { 6191 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 6192 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 6193 6194 if (LHSType->isObjCBuiltinType()) { 6195 // Class is not compatible with ObjC object pointers. 6196 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 6197 !RHSType->isObjCQualifiedClassType()) 6198 return Sema::IncompatiblePointer; 6199 return Sema::Compatible; 6200 } 6201 if (RHSType->isObjCBuiltinType()) { 6202 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 6203 !LHSType->isObjCQualifiedClassType()) 6204 return Sema::IncompatiblePointer; 6205 return Sema::Compatible; 6206 } 6207 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6208 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6209 6210 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 6211 // make an exception for id<P> 6212 !LHSType->isObjCQualifiedIdType()) 6213 return Sema::CompatiblePointerDiscardsQualifiers; 6214 6215 if (S.Context.typesAreCompatible(LHSType, RHSType)) 6216 return Sema::Compatible; 6217 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 6218 return Sema::IncompatibleObjCQualifiedId; 6219 return Sema::IncompatiblePointer; 6220 } 6221 6222 Sema::AssignConvertType 6223 Sema::CheckAssignmentConstraints(SourceLocation Loc, 6224 QualType LHSType, QualType RHSType) { 6225 // Fake up an opaque expression. We don't actually care about what 6226 // cast operations are required, so if CheckAssignmentConstraints 6227 // adds casts to this they'll be wasted, but fortunately that doesn't 6228 // usually happen on valid code. 6229 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 6230 ExprResult RHSPtr = &RHSExpr; 6231 CastKind K = CK_Invalid; 6232 6233 return CheckAssignmentConstraints(LHSType, RHSPtr, K); 6234 } 6235 6236 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 6237 /// has code to accommodate several GCC extensions when type checking 6238 /// pointers. Here are some objectionable examples that GCC considers warnings: 6239 /// 6240 /// int a, *pint; 6241 /// short *pshort; 6242 /// struct foo *pfoo; 6243 /// 6244 /// pint = pshort; // warning: assignment from incompatible pointer type 6245 /// a = pint; // warning: assignment makes integer from pointer without a cast 6246 /// pint = a; // warning: assignment makes pointer from integer without a cast 6247 /// pint = pfoo; // warning: assignment from incompatible pointer type 6248 /// 6249 /// As a result, the code for dealing with pointers is more complex than the 6250 /// C99 spec dictates. 6251 /// 6252 /// Sets 'Kind' for any result kind except Incompatible. 6253 Sema::AssignConvertType 6254 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6255 CastKind &Kind) { 6256 QualType RHSType = RHS.get()->getType(); 6257 QualType OrigLHSType = LHSType; 6258 6259 // Get canonical types. We're not formatting these types, just comparing 6260 // them. 6261 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 6262 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 6263 6264 // Common case: no conversion required. 6265 if (LHSType == RHSType) { 6266 Kind = CK_NoOp; 6267 return Compatible; 6268 } 6269 6270 // If we have an atomic type, try a non-atomic assignment, then just add an 6271 // atomic qualification step. 6272 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 6273 Sema::AssignConvertType result = 6274 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 6275 if (result != Compatible) 6276 return result; 6277 if (Kind != CK_NoOp) 6278 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind); 6279 Kind = CK_NonAtomicToAtomic; 6280 return Compatible; 6281 } 6282 6283 // If the left-hand side is a reference type, then we are in a 6284 // (rare!) case where we've allowed the use of references in C, 6285 // e.g., as a parameter type in a built-in function. In this case, 6286 // just make sure that the type referenced is compatible with the 6287 // right-hand side type. The caller is responsible for adjusting 6288 // LHSType so that the resulting expression does not have reference 6289 // type. 6290 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 6291 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 6292 Kind = CK_LValueBitCast; 6293 return Compatible; 6294 } 6295 return Incompatible; 6296 } 6297 6298 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 6299 // to the same ExtVector type. 6300 if (LHSType->isExtVectorType()) { 6301 if (RHSType->isExtVectorType()) 6302 return Incompatible; 6303 if (RHSType->isArithmeticType()) { 6304 // CK_VectorSplat does T -> vector T, so first cast to the 6305 // element type. 6306 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 6307 if (elType != RHSType) { 6308 Kind = PrepareScalarCast(RHS, elType); 6309 RHS = ImpCastExprToType(RHS.take(), elType, Kind); 6310 } 6311 Kind = CK_VectorSplat; 6312 return Compatible; 6313 } 6314 } 6315 6316 // Conversions to or from vector type. 6317 if (LHSType->isVectorType() || RHSType->isVectorType()) { 6318 if (LHSType->isVectorType() && RHSType->isVectorType()) { 6319 // Allow assignments of an AltiVec vector type to an equivalent GCC 6320 // vector type and vice versa 6321 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6322 Kind = CK_BitCast; 6323 return Compatible; 6324 } 6325 6326 // If we are allowing lax vector conversions, and LHS and RHS are both 6327 // vectors, the total size only needs to be the same. This is a bitcast; 6328 // no bits are changed but the result type is different. 6329 if (isLaxVectorConversion(RHSType, LHSType)) { 6330 Kind = CK_BitCast; 6331 return IncompatibleVectors; 6332 } 6333 } 6334 return Incompatible; 6335 } 6336 6337 // Arithmetic conversions. 6338 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 6339 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 6340 Kind = PrepareScalarCast(RHS, LHSType); 6341 return Compatible; 6342 } 6343 6344 // Conversions to normal pointers. 6345 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 6346 // U* -> T* 6347 if (isa<PointerType>(RHSType)) { 6348 Kind = CK_BitCast; 6349 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 6350 } 6351 6352 // int -> T* 6353 if (RHSType->isIntegerType()) { 6354 Kind = CK_IntegralToPointer; // FIXME: null? 6355 return IntToPointer; 6356 } 6357 6358 // C pointers are not compatible with ObjC object pointers, 6359 // with two exceptions: 6360 if (isa<ObjCObjectPointerType>(RHSType)) { 6361 // - conversions to void* 6362 if (LHSPointer->getPointeeType()->isVoidType()) { 6363 Kind = CK_BitCast; 6364 return Compatible; 6365 } 6366 6367 // - conversions from 'Class' to the redefinition type 6368 if (RHSType->isObjCClassType() && 6369 Context.hasSameType(LHSType, 6370 Context.getObjCClassRedefinitionType())) { 6371 Kind = CK_BitCast; 6372 return Compatible; 6373 } 6374 6375 Kind = CK_BitCast; 6376 return IncompatiblePointer; 6377 } 6378 6379 // U^ -> void* 6380 if (RHSType->getAs<BlockPointerType>()) { 6381 if (LHSPointer->getPointeeType()->isVoidType()) { 6382 Kind = CK_BitCast; 6383 return Compatible; 6384 } 6385 } 6386 6387 return Incompatible; 6388 } 6389 6390 // Conversions to block pointers. 6391 if (isa<BlockPointerType>(LHSType)) { 6392 // U^ -> T^ 6393 if (RHSType->isBlockPointerType()) { 6394 Kind = CK_BitCast; 6395 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 6396 } 6397 6398 // int or null -> T^ 6399 if (RHSType->isIntegerType()) { 6400 Kind = CK_IntegralToPointer; // FIXME: null 6401 return IntToBlockPointer; 6402 } 6403 6404 // id -> T^ 6405 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 6406 Kind = CK_AnyPointerToBlockPointerCast; 6407 return Compatible; 6408 } 6409 6410 // void* -> T^ 6411 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 6412 if (RHSPT->getPointeeType()->isVoidType()) { 6413 Kind = CK_AnyPointerToBlockPointerCast; 6414 return Compatible; 6415 } 6416 6417 return Incompatible; 6418 } 6419 6420 // Conversions to Objective-C pointers. 6421 if (isa<ObjCObjectPointerType>(LHSType)) { 6422 // A* -> B* 6423 if (RHSType->isObjCObjectPointerType()) { 6424 Kind = CK_BitCast; 6425 Sema::AssignConvertType result = 6426 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 6427 if (getLangOpts().ObjCAutoRefCount && 6428 result == Compatible && 6429 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 6430 result = IncompatibleObjCWeakRef; 6431 return result; 6432 } 6433 6434 // int or null -> A* 6435 if (RHSType->isIntegerType()) { 6436 Kind = CK_IntegralToPointer; // FIXME: null 6437 return IntToPointer; 6438 } 6439 6440 // In general, C pointers are not compatible with ObjC object pointers, 6441 // with two exceptions: 6442 if (isa<PointerType>(RHSType)) { 6443 Kind = CK_CPointerToObjCPointerCast; 6444 6445 // - conversions from 'void*' 6446 if (RHSType->isVoidPointerType()) { 6447 return Compatible; 6448 } 6449 6450 // - conversions to 'Class' from its redefinition type 6451 if (LHSType->isObjCClassType() && 6452 Context.hasSameType(RHSType, 6453 Context.getObjCClassRedefinitionType())) { 6454 return Compatible; 6455 } 6456 6457 return IncompatiblePointer; 6458 } 6459 6460 // T^ -> A* 6461 if (RHSType->isBlockPointerType()) { 6462 maybeExtendBlockObject(*this, RHS); 6463 Kind = CK_BlockPointerToObjCPointerCast; 6464 return Compatible; 6465 } 6466 6467 return Incompatible; 6468 } 6469 6470 // Conversions from pointers that are not covered by the above. 6471 if (isa<PointerType>(RHSType)) { 6472 // T* -> _Bool 6473 if (LHSType == Context.BoolTy) { 6474 Kind = CK_PointerToBoolean; 6475 return Compatible; 6476 } 6477 6478 // T* -> int 6479 if (LHSType->isIntegerType()) { 6480 Kind = CK_PointerToIntegral; 6481 return PointerToInt; 6482 } 6483 6484 return Incompatible; 6485 } 6486 6487 // Conversions from Objective-C pointers that are not covered by the above. 6488 if (isa<ObjCObjectPointerType>(RHSType)) { 6489 // T* -> _Bool 6490 if (LHSType == Context.BoolTy) { 6491 Kind = CK_PointerToBoolean; 6492 return Compatible; 6493 } 6494 6495 // T* -> int 6496 if (LHSType->isIntegerType()) { 6497 Kind = CK_PointerToIntegral; 6498 return PointerToInt; 6499 } 6500 6501 return Incompatible; 6502 } 6503 6504 // struct A -> struct B 6505 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 6506 if (Context.typesAreCompatible(LHSType, RHSType)) { 6507 Kind = CK_NoOp; 6508 return Compatible; 6509 } 6510 } 6511 6512 return Incompatible; 6513 } 6514 6515 /// \brief Constructs a transparent union from an expression that is 6516 /// used to initialize the transparent union. 6517 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 6518 ExprResult &EResult, QualType UnionType, 6519 FieldDecl *Field) { 6520 // Build an initializer list that designates the appropriate member 6521 // of the transparent union. 6522 Expr *E = EResult.take(); 6523 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 6524 E, SourceLocation()); 6525 Initializer->setType(UnionType); 6526 Initializer->setInitializedFieldInUnion(Field); 6527 6528 // Build a compound literal constructing a value of the transparent 6529 // union type from this initializer list. 6530 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 6531 EResult = S.Owned( 6532 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 6533 VK_RValue, Initializer, false)); 6534 } 6535 6536 Sema::AssignConvertType 6537 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 6538 ExprResult &RHS) { 6539 QualType RHSType = RHS.get()->getType(); 6540 6541 // If the ArgType is a Union type, we want to handle a potential 6542 // transparent_union GCC extension. 6543 const RecordType *UT = ArgType->getAsUnionType(); 6544 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 6545 return Incompatible; 6546 6547 // The field to initialize within the transparent union. 6548 RecordDecl *UD = UT->getDecl(); 6549 FieldDecl *InitField = 0; 6550 // It's compatible if the expression matches any of the fields. 6551 for (auto *it : UD->fields()) { 6552 if (it->getType()->isPointerType()) { 6553 // If the transparent union contains a pointer type, we allow: 6554 // 1) void pointer 6555 // 2) null pointer constant 6556 if (RHSType->isPointerType()) 6557 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 6558 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast); 6559 InitField = it; 6560 break; 6561 } 6562 6563 if (RHS.get()->isNullPointerConstant(Context, 6564 Expr::NPC_ValueDependentIsNull)) { 6565 RHS = ImpCastExprToType(RHS.take(), it->getType(), 6566 CK_NullToPointer); 6567 InitField = it; 6568 break; 6569 } 6570 } 6571 6572 CastKind Kind = CK_Invalid; 6573 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 6574 == Compatible) { 6575 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind); 6576 InitField = it; 6577 break; 6578 } 6579 } 6580 6581 if (!InitField) 6582 return Incompatible; 6583 6584 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 6585 return Compatible; 6586 } 6587 6588 Sema::AssignConvertType 6589 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6590 bool Diagnose, 6591 bool DiagnoseCFAudited) { 6592 if (getLangOpts().CPlusPlus) { 6593 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 6594 // C++ 5.17p3: If the left operand is not of class type, the 6595 // expression is implicitly converted (C++ 4) to the 6596 // cv-unqualified type of the left operand. 6597 ExprResult Res; 6598 if (Diagnose) { 6599 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6600 AA_Assigning); 6601 } else { 6602 ImplicitConversionSequence ICS = 6603 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6604 /*SuppressUserConversions=*/false, 6605 /*AllowExplicit=*/false, 6606 /*InOverloadResolution=*/false, 6607 /*CStyle=*/false, 6608 /*AllowObjCWritebackConversion=*/false); 6609 if (ICS.isFailure()) 6610 return Incompatible; 6611 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6612 ICS, AA_Assigning); 6613 } 6614 if (Res.isInvalid()) 6615 return Incompatible; 6616 Sema::AssignConvertType result = Compatible; 6617 if (getLangOpts().ObjCAutoRefCount && 6618 !CheckObjCARCUnavailableWeakConversion(LHSType, 6619 RHS.get()->getType())) 6620 result = IncompatibleObjCWeakRef; 6621 RHS = Res; 6622 return result; 6623 } 6624 6625 // FIXME: Currently, we fall through and treat C++ classes like C 6626 // structures. 6627 // FIXME: We also fall through for atomics; not sure what should 6628 // happen there, though. 6629 } 6630 6631 // C99 6.5.16.1p1: the left operand is a pointer and the right is 6632 // a null pointer constant. 6633 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 6634 LHSType->isBlockPointerType()) && 6635 RHS.get()->isNullPointerConstant(Context, 6636 Expr::NPC_ValueDependentIsNull)) { 6637 CastKind Kind; 6638 CXXCastPath Path; 6639 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false); 6640 RHS = ImpCastExprToType(RHS.take(), LHSType, Kind, VK_RValue, &Path); 6641 return Compatible; 6642 } 6643 6644 // This check seems unnatural, however it is necessary to ensure the proper 6645 // conversion of functions/arrays. If the conversion were done for all 6646 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 6647 // expressions that suppress this implicit conversion (&, sizeof). 6648 // 6649 // Suppress this for references: C++ 8.5.3p5. 6650 if (!LHSType->isReferenceType()) { 6651 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6652 if (RHS.isInvalid()) 6653 return Incompatible; 6654 } 6655 6656 CastKind Kind = CK_Invalid; 6657 Sema::AssignConvertType result = 6658 CheckAssignmentConstraints(LHSType, RHS, Kind); 6659 6660 // C99 6.5.16.1p2: The value of the right operand is converted to the 6661 // type of the assignment expression. 6662 // CheckAssignmentConstraints allows the left-hand side to be a reference, 6663 // so that we can use references in built-in functions even in C. 6664 // The getNonReferenceType() call makes sure that the resulting expression 6665 // does not have reference type. 6666 if (result != Incompatible && RHS.get()->getType() != LHSType) { 6667 QualType Ty = LHSType.getNonLValueExprType(Context); 6668 Expr *E = RHS.take(); 6669 if (getLangOpts().ObjCAutoRefCount) 6670 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 6671 DiagnoseCFAudited); 6672 if (getLangOpts().ObjC1 && 6673 (CheckObjCBridgeRelatedConversions(E->getLocStart(), 6674 LHSType, E->getType(), E) || 6675 ConversionToObjCStringLiteralCheck(LHSType, E))) { 6676 RHS = Owned(E); 6677 return Compatible; 6678 } 6679 6680 RHS = ImpCastExprToType(E, Ty, Kind); 6681 } 6682 return result; 6683 } 6684 6685 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 6686 ExprResult &RHS) { 6687 Diag(Loc, diag::err_typecheck_invalid_operands) 6688 << LHS.get()->getType() << RHS.get()->getType() 6689 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6690 return QualType(); 6691 } 6692 6693 /// Try to convert a value of non-vector type to a vector type by converting 6694 /// the type to the element type of the vector and then performing a splat. 6695 /// If the language is OpenCL, we only use conversions that promote scalar 6696 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 6697 /// for float->int. 6698 /// 6699 /// \param scalar - if non-null, actually perform the conversions 6700 /// \return true if the operation fails (but without diagnosing the failure) 6701 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 6702 QualType scalarTy, 6703 QualType vectorEltTy, 6704 QualType vectorTy) { 6705 // The conversion to apply to the scalar before splatting it, 6706 // if necessary. 6707 CastKind scalarCast = CK_Invalid; 6708 6709 if (vectorEltTy->isIntegralType(S.Context)) { 6710 if (!scalarTy->isIntegralType(S.Context)) 6711 return true; 6712 if (S.getLangOpts().OpenCL && 6713 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 6714 return true; 6715 scalarCast = CK_IntegralCast; 6716 } else if (vectorEltTy->isRealFloatingType()) { 6717 if (scalarTy->isRealFloatingType()) { 6718 if (S.getLangOpts().OpenCL && 6719 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 6720 return true; 6721 scalarCast = CK_FloatingCast; 6722 } 6723 else if (scalarTy->isIntegralType(S.Context)) 6724 scalarCast = CK_IntegralToFloating; 6725 else 6726 return true; 6727 } else { 6728 return true; 6729 } 6730 6731 // Adjust scalar if desired. 6732 if (scalar) { 6733 if (scalarCast != CK_Invalid) 6734 *scalar = S.ImpCastExprToType(scalar->take(), vectorEltTy, scalarCast); 6735 *scalar = S.ImpCastExprToType(scalar->take(), vectorTy, CK_VectorSplat); 6736 } 6737 return false; 6738 } 6739 6740 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 6741 SourceLocation Loc, bool IsCompAssign) { 6742 if (!IsCompAssign) { 6743 LHS = DefaultFunctionArrayLvalueConversion(LHS.take()); 6744 if (LHS.isInvalid()) 6745 return QualType(); 6746 } 6747 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 6748 if (RHS.isInvalid()) 6749 return QualType(); 6750 6751 // For conversion purposes, we ignore any qualifiers. 6752 // For example, "const float" and "float" are equivalent. 6753 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 6754 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 6755 6756 // If the vector types are identical, return. 6757 if (Context.hasSameType(LHSType, RHSType)) 6758 return LHSType; 6759 6760 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 6761 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 6762 assert(LHSVecType || RHSVecType); 6763 6764 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 6765 if (LHSVecType && RHSVecType && 6766 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6767 if (isa<ExtVectorType>(LHSVecType)) { 6768 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 6769 return LHSType; 6770 } 6771 6772 if (!IsCompAssign) 6773 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 6774 return RHSType; 6775 } 6776 6777 // If there's an ext-vector type and a scalar, try to convert the scalar to 6778 // the vector element type and splat. 6779 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 6780 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 6781 LHSVecType->getElementType(), LHSType)) 6782 return LHSType; 6783 } 6784 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 6785 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? 0 : &LHS), LHSType, 6786 RHSVecType->getElementType(), RHSType)) 6787 return RHSType; 6788 } 6789 6790 // If we're allowing lax vector conversions, only the total (data) size 6791 // needs to be the same. 6792 // FIXME: Should we really be allowing this? 6793 // FIXME: We really just pick the LHS type arbitrarily? 6794 if (isLaxVectorConversion(RHSType, LHSType)) { 6795 QualType resultType = LHSType; 6796 RHS = ImpCastExprToType(RHS.take(), resultType, CK_BitCast); 6797 return resultType; 6798 } 6799 6800 // Okay, the expression is invalid. 6801 6802 // If there's a non-vector, non-real operand, diagnose that. 6803 if ((!RHSVecType && !RHSType->isRealType()) || 6804 (!LHSVecType && !LHSType->isRealType())) { 6805 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 6806 << LHSType << RHSType 6807 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6808 return QualType(); 6809 } 6810 6811 // Otherwise, use the generic diagnostic. 6812 Diag(Loc, diag::err_typecheck_vector_not_convertable) 6813 << LHSType << RHSType 6814 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6815 return QualType(); 6816 } 6817 6818 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 6819 // expression. These are mainly cases where the null pointer is used as an 6820 // integer instead of a pointer. 6821 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 6822 SourceLocation Loc, bool IsCompare) { 6823 // The canonical way to check for a GNU null is with isNullPointerConstant, 6824 // but we use a bit of a hack here for speed; this is a relatively 6825 // hot path, and isNullPointerConstant is slow. 6826 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 6827 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 6828 6829 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 6830 6831 // Avoid analyzing cases where the result will either be invalid (and 6832 // diagnosed as such) or entirely valid and not something to warn about. 6833 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 6834 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 6835 return; 6836 6837 // Comparison operations would not make sense with a null pointer no matter 6838 // what the other expression is. 6839 if (!IsCompare) { 6840 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 6841 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 6842 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 6843 return; 6844 } 6845 6846 // The rest of the operations only make sense with a null pointer 6847 // if the other expression is a pointer. 6848 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 6849 NonNullType->canDecayToPointerType()) 6850 return; 6851 6852 S.Diag(Loc, diag::warn_null_in_comparison_operation) 6853 << LHSNull /* LHS is NULL */ << NonNullType 6854 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6855 } 6856 6857 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 6858 SourceLocation Loc, 6859 bool IsCompAssign, bool IsDiv) { 6860 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6861 6862 if (LHS.get()->getType()->isVectorType() || 6863 RHS.get()->getType()->isVectorType()) 6864 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6865 6866 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6867 if (LHS.isInvalid() || RHS.isInvalid()) 6868 return QualType(); 6869 6870 6871 if (compType.isNull() || !compType->isArithmeticType()) 6872 return InvalidOperands(Loc, LHS, RHS); 6873 6874 // Check for division by zero. 6875 llvm::APSInt RHSValue; 6876 if (IsDiv && !RHS.get()->isValueDependent() && 6877 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0) 6878 DiagRuntimeBehavior(Loc, RHS.get(), 6879 PDiag(diag::warn_division_by_zero) 6880 << RHS.get()->getSourceRange()); 6881 6882 return compType; 6883 } 6884 6885 QualType Sema::CheckRemainderOperands( 6886 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 6887 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6888 6889 if (LHS.get()->getType()->isVectorType() || 6890 RHS.get()->getType()->isVectorType()) { 6891 if (LHS.get()->getType()->hasIntegerRepresentation() && 6892 RHS.get()->getType()->hasIntegerRepresentation()) 6893 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6894 return InvalidOperands(Loc, LHS, RHS); 6895 } 6896 6897 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6898 if (LHS.isInvalid() || RHS.isInvalid()) 6899 return QualType(); 6900 6901 if (compType.isNull() || !compType->isIntegerType()) 6902 return InvalidOperands(Loc, LHS, RHS); 6903 6904 // Check for remainder by zero. 6905 llvm::APSInt RHSValue; 6906 if (!RHS.get()->isValueDependent() && 6907 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0) 6908 DiagRuntimeBehavior(Loc, RHS.get(), 6909 PDiag(diag::warn_remainder_by_zero) 6910 << RHS.get()->getSourceRange()); 6911 6912 return compType; 6913 } 6914 6915 /// \brief Diagnose invalid arithmetic on two void pointers. 6916 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 6917 Expr *LHSExpr, Expr *RHSExpr) { 6918 S.Diag(Loc, S.getLangOpts().CPlusPlus 6919 ? diag::err_typecheck_pointer_arith_void_type 6920 : diag::ext_gnu_void_ptr) 6921 << 1 /* two pointers */ << LHSExpr->getSourceRange() 6922 << RHSExpr->getSourceRange(); 6923 } 6924 6925 /// \brief Diagnose invalid arithmetic on a void pointer. 6926 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 6927 Expr *Pointer) { 6928 S.Diag(Loc, S.getLangOpts().CPlusPlus 6929 ? diag::err_typecheck_pointer_arith_void_type 6930 : diag::ext_gnu_void_ptr) 6931 << 0 /* one pointer */ << Pointer->getSourceRange(); 6932 } 6933 6934 /// \brief Diagnose invalid arithmetic on two function pointers. 6935 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 6936 Expr *LHS, Expr *RHS) { 6937 assert(LHS->getType()->isAnyPointerType()); 6938 assert(RHS->getType()->isAnyPointerType()); 6939 S.Diag(Loc, S.getLangOpts().CPlusPlus 6940 ? diag::err_typecheck_pointer_arith_function_type 6941 : diag::ext_gnu_ptr_func_arith) 6942 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 6943 // We only show the second type if it differs from the first. 6944 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 6945 RHS->getType()) 6946 << RHS->getType()->getPointeeType() 6947 << LHS->getSourceRange() << RHS->getSourceRange(); 6948 } 6949 6950 /// \brief Diagnose invalid arithmetic on a function pointer. 6951 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 6952 Expr *Pointer) { 6953 assert(Pointer->getType()->isAnyPointerType()); 6954 S.Diag(Loc, S.getLangOpts().CPlusPlus 6955 ? diag::err_typecheck_pointer_arith_function_type 6956 : diag::ext_gnu_ptr_func_arith) 6957 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 6958 << 0 /* one pointer, so only one type */ 6959 << Pointer->getSourceRange(); 6960 } 6961 6962 /// \brief Emit error if Operand is incomplete pointer type 6963 /// 6964 /// \returns True if pointer has incomplete type 6965 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 6966 Expr *Operand) { 6967 assert(Operand->getType()->isAnyPointerType() && 6968 !Operand->getType()->isDependentType()); 6969 QualType PointeeTy = Operand->getType()->getPointeeType(); 6970 return S.RequireCompleteType(Loc, PointeeTy, 6971 diag::err_typecheck_arithmetic_incomplete_type, 6972 PointeeTy, Operand->getSourceRange()); 6973 } 6974 6975 /// \brief Check the validity of an arithmetic pointer operand. 6976 /// 6977 /// If the operand has pointer type, this code will check for pointer types 6978 /// which are invalid in arithmetic operations. These will be diagnosed 6979 /// appropriately, including whether or not the use is supported as an 6980 /// extension. 6981 /// 6982 /// \returns True when the operand is valid to use (even if as an extension). 6983 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 6984 Expr *Operand) { 6985 if (!Operand->getType()->isAnyPointerType()) return true; 6986 6987 QualType PointeeTy = Operand->getType()->getPointeeType(); 6988 if (PointeeTy->isVoidType()) { 6989 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 6990 return !S.getLangOpts().CPlusPlus; 6991 } 6992 if (PointeeTy->isFunctionType()) { 6993 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 6994 return !S.getLangOpts().CPlusPlus; 6995 } 6996 6997 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 6998 6999 return true; 7000 } 7001 7002 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 7003 /// operands. 7004 /// 7005 /// This routine will diagnose any invalid arithmetic on pointer operands much 7006 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 7007 /// for emitting a single diagnostic even for operations where both LHS and RHS 7008 /// are (potentially problematic) pointers. 7009 /// 7010 /// \returns True when the operand is valid to use (even if as an extension). 7011 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 7012 Expr *LHSExpr, Expr *RHSExpr) { 7013 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 7014 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 7015 if (!isLHSPointer && !isRHSPointer) return true; 7016 7017 QualType LHSPointeeTy, RHSPointeeTy; 7018 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 7019 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 7020 7021 // Check for arithmetic on pointers to incomplete types. 7022 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 7023 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 7024 if (isLHSVoidPtr || isRHSVoidPtr) { 7025 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 7026 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 7027 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 7028 7029 return !S.getLangOpts().CPlusPlus; 7030 } 7031 7032 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 7033 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 7034 if (isLHSFuncPtr || isRHSFuncPtr) { 7035 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 7036 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 7037 RHSExpr); 7038 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 7039 7040 return !S.getLangOpts().CPlusPlus; 7041 } 7042 7043 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 7044 return false; 7045 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 7046 return false; 7047 7048 return true; 7049 } 7050 7051 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 7052 /// literal. 7053 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 7054 Expr *LHSExpr, Expr *RHSExpr) { 7055 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 7056 Expr* IndexExpr = RHSExpr; 7057 if (!StrExpr) { 7058 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 7059 IndexExpr = LHSExpr; 7060 } 7061 7062 bool IsStringPlusInt = StrExpr && 7063 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 7064 if (!IsStringPlusInt) 7065 return; 7066 7067 llvm::APSInt index; 7068 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 7069 unsigned StrLenWithNull = StrExpr->getLength() + 1; 7070 if (index.isNonNegative() && 7071 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 7072 index.isUnsigned())) 7073 return; 7074 } 7075 7076 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7077 Self.Diag(OpLoc, diag::warn_string_plus_int) 7078 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 7079 7080 // Only print a fixit for "str" + int, not for int + "str". 7081 if (IndexExpr == RHSExpr) { 7082 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 7083 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7084 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7085 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7086 << FixItHint::CreateInsertion(EndLoc, "]"); 7087 } else 7088 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7089 } 7090 7091 /// \brief Emit a warning when adding a char literal to a string. 7092 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 7093 Expr *LHSExpr, Expr *RHSExpr) { 7094 const DeclRefExpr *StringRefExpr = 7095 dyn_cast<DeclRefExpr>(LHSExpr->IgnoreImpCasts()); 7096 const CharacterLiteral *CharExpr = 7097 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 7098 if (!StringRefExpr) { 7099 StringRefExpr = dyn_cast<DeclRefExpr>(RHSExpr->IgnoreImpCasts()); 7100 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 7101 } 7102 7103 if (!CharExpr || !StringRefExpr) 7104 return; 7105 7106 const QualType StringType = StringRefExpr->getType(); 7107 7108 // Return if not a PointerType. 7109 if (!StringType->isAnyPointerType()) 7110 return; 7111 7112 // Return if not a CharacterType. 7113 if (!StringType->getPointeeType()->isAnyCharacterType()) 7114 return; 7115 7116 ASTContext &Ctx = Self.getASTContext(); 7117 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7118 7119 const QualType CharType = CharExpr->getType(); 7120 if (!CharType->isAnyCharacterType() && 7121 CharType->isIntegerType() && 7122 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 7123 Self.Diag(OpLoc, diag::warn_string_plus_char) 7124 << DiagRange << Ctx.CharTy; 7125 } else { 7126 Self.Diag(OpLoc, diag::warn_string_plus_char) 7127 << DiagRange << CharExpr->getType(); 7128 } 7129 7130 // Only print a fixit for str + char, not for char + str. 7131 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 7132 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 7133 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7134 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7135 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7136 << FixItHint::CreateInsertion(EndLoc, "]"); 7137 } else { 7138 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7139 } 7140 } 7141 7142 /// \brief Emit error when two pointers are incompatible. 7143 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 7144 Expr *LHSExpr, Expr *RHSExpr) { 7145 assert(LHSExpr->getType()->isAnyPointerType()); 7146 assert(RHSExpr->getType()->isAnyPointerType()); 7147 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 7148 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 7149 << RHSExpr->getSourceRange(); 7150 } 7151 7152 QualType Sema::CheckAdditionOperands( // C99 6.5.6 7153 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 7154 QualType* CompLHSTy) { 7155 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7156 7157 if (LHS.get()->getType()->isVectorType() || 7158 RHS.get()->getType()->isVectorType()) { 7159 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 7160 if (CompLHSTy) *CompLHSTy = compType; 7161 return compType; 7162 } 7163 7164 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7165 if (LHS.isInvalid() || RHS.isInvalid()) 7166 return QualType(); 7167 7168 // Diagnose "string literal" '+' int and string '+' "char literal". 7169 if (Opc == BO_Add) { 7170 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 7171 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 7172 } 7173 7174 // handle the common case first (both operands are arithmetic). 7175 if (!compType.isNull() && compType->isArithmeticType()) { 7176 if (CompLHSTy) *CompLHSTy = compType; 7177 return compType; 7178 } 7179 7180 // Type-checking. Ultimately the pointer's going to be in PExp; 7181 // note that we bias towards the LHS being the pointer. 7182 Expr *PExp = LHS.get(), *IExp = RHS.get(); 7183 7184 bool isObjCPointer; 7185 if (PExp->getType()->isPointerType()) { 7186 isObjCPointer = false; 7187 } else if (PExp->getType()->isObjCObjectPointerType()) { 7188 isObjCPointer = true; 7189 } else { 7190 std::swap(PExp, IExp); 7191 if (PExp->getType()->isPointerType()) { 7192 isObjCPointer = false; 7193 } else if (PExp->getType()->isObjCObjectPointerType()) { 7194 isObjCPointer = true; 7195 } else { 7196 return InvalidOperands(Loc, LHS, RHS); 7197 } 7198 } 7199 assert(PExp->getType()->isAnyPointerType()); 7200 7201 if (!IExp->getType()->isIntegerType()) 7202 return InvalidOperands(Loc, LHS, RHS); 7203 7204 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 7205 return QualType(); 7206 7207 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 7208 return QualType(); 7209 7210 // Check array bounds for pointer arithemtic 7211 CheckArrayAccess(PExp, IExp); 7212 7213 if (CompLHSTy) { 7214 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 7215 if (LHSTy.isNull()) { 7216 LHSTy = LHS.get()->getType(); 7217 if (LHSTy->isPromotableIntegerType()) 7218 LHSTy = Context.getPromotedIntegerType(LHSTy); 7219 } 7220 *CompLHSTy = LHSTy; 7221 } 7222 7223 return PExp->getType(); 7224 } 7225 7226 // C99 6.5.6 7227 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 7228 SourceLocation Loc, 7229 QualType* CompLHSTy) { 7230 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7231 7232 if (LHS.get()->getType()->isVectorType() || 7233 RHS.get()->getType()->isVectorType()) { 7234 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 7235 if (CompLHSTy) *CompLHSTy = compType; 7236 return compType; 7237 } 7238 7239 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7240 if (LHS.isInvalid() || RHS.isInvalid()) 7241 return QualType(); 7242 7243 // Enforce type constraints: C99 6.5.6p3. 7244 7245 // Handle the common case first (both operands are arithmetic). 7246 if (!compType.isNull() && compType->isArithmeticType()) { 7247 if (CompLHSTy) *CompLHSTy = compType; 7248 return compType; 7249 } 7250 7251 // Either ptr - int or ptr - ptr. 7252 if (LHS.get()->getType()->isAnyPointerType()) { 7253 QualType lpointee = LHS.get()->getType()->getPointeeType(); 7254 7255 // Diagnose bad cases where we step over interface counts. 7256 if (LHS.get()->getType()->isObjCObjectPointerType() && 7257 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 7258 return QualType(); 7259 7260 // The result type of a pointer-int computation is the pointer type. 7261 if (RHS.get()->getType()->isIntegerType()) { 7262 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 7263 return QualType(); 7264 7265 // Check array bounds for pointer arithemtic 7266 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0, 7267 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 7268 7269 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 7270 return LHS.get()->getType(); 7271 } 7272 7273 // Handle pointer-pointer subtractions. 7274 if (const PointerType *RHSPTy 7275 = RHS.get()->getType()->getAs<PointerType>()) { 7276 QualType rpointee = RHSPTy->getPointeeType(); 7277 7278 if (getLangOpts().CPlusPlus) { 7279 // Pointee types must be the same: C++ [expr.add] 7280 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 7281 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 7282 } 7283 } else { 7284 // Pointee types must be compatible C99 6.5.6p3 7285 if (!Context.typesAreCompatible( 7286 Context.getCanonicalType(lpointee).getUnqualifiedType(), 7287 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 7288 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 7289 return QualType(); 7290 } 7291 } 7292 7293 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 7294 LHS.get(), RHS.get())) 7295 return QualType(); 7296 7297 // The pointee type may have zero size. As an extension, a structure or 7298 // union may have zero size or an array may have zero length. In this 7299 // case subtraction does not make sense. 7300 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 7301 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 7302 if (ElementSize.isZero()) { 7303 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 7304 << rpointee.getUnqualifiedType() 7305 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7306 } 7307 } 7308 7309 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 7310 return Context.getPointerDiffType(); 7311 } 7312 } 7313 7314 return InvalidOperands(Loc, LHS, RHS); 7315 } 7316 7317 static bool isScopedEnumerationType(QualType T) { 7318 if (const EnumType *ET = dyn_cast<EnumType>(T)) 7319 return ET->getDecl()->isScoped(); 7320 return false; 7321 } 7322 7323 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 7324 SourceLocation Loc, unsigned Opc, 7325 QualType LHSType) { 7326 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 7327 // so skip remaining warnings as we don't want to modify values within Sema. 7328 if (S.getLangOpts().OpenCL) 7329 return; 7330 7331 llvm::APSInt Right; 7332 // Check right/shifter operand 7333 if (RHS.get()->isValueDependent() || 7334 !RHS.get()->isIntegerConstantExpr(Right, S.Context)) 7335 return; 7336 7337 if (Right.isNegative()) { 7338 S.DiagRuntimeBehavior(Loc, RHS.get(), 7339 S.PDiag(diag::warn_shift_negative) 7340 << RHS.get()->getSourceRange()); 7341 return; 7342 } 7343 llvm::APInt LeftBits(Right.getBitWidth(), 7344 S.Context.getTypeSize(LHS.get()->getType())); 7345 if (Right.uge(LeftBits)) { 7346 S.DiagRuntimeBehavior(Loc, RHS.get(), 7347 S.PDiag(diag::warn_shift_gt_typewidth) 7348 << RHS.get()->getSourceRange()); 7349 return; 7350 } 7351 if (Opc != BO_Shl) 7352 return; 7353 7354 // When left shifting an ICE which is signed, we can check for overflow which 7355 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 7356 // integers have defined behavior modulo one more than the maximum value 7357 // representable in the result type, so never warn for those. 7358 llvm::APSInt Left; 7359 if (LHS.get()->isValueDependent() || 7360 !LHS.get()->isIntegerConstantExpr(Left, S.Context) || 7361 LHSType->hasUnsignedIntegerRepresentation()) 7362 return; 7363 llvm::APInt ResultBits = 7364 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 7365 if (LeftBits.uge(ResultBits)) 7366 return; 7367 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 7368 Result = Result.shl(Right); 7369 7370 // Print the bit representation of the signed integer as an unsigned 7371 // hexadecimal number. 7372 SmallString<40> HexResult; 7373 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 7374 7375 // If we are only missing a sign bit, this is less likely to result in actual 7376 // bugs -- if the result is cast back to an unsigned type, it will have the 7377 // expected value. Thus we place this behind a different warning that can be 7378 // turned off separately if needed. 7379 if (LeftBits == ResultBits - 1) { 7380 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 7381 << HexResult.str() << LHSType 7382 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7383 return; 7384 } 7385 7386 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 7387 << HexResult.str() << Result.getMinSignedBits() << LHSType 7388 << Left.getBitWidth() << LHS.get()->getSourceRange() 7389 << RHS.get()->getSourceRange(); 7390 } 7391 7392 // C99 6.5.7 7393 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 7394 SourceLocation Loc, unsigned Opc, 7395 bool IsCompAssign) { 7396 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7397 7398 // Vector shifts promote their scalar inputs to vector type. 7399 if (LHS.get()->getType()->isVectorType() || 7400 RHS.get()->getType()->isVectorType()) 7401 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 7402 7403 // Shifts don't perform usual arithmetic conversions, they just do integer 7404 // promotions on each operand. C99 6.5.7p3 7405 7406 // For the LHS, do usual unary conversions, but then reset them away 7407 // if this is a compound assignment. 7408 ExprResult OldLHS = LHS; 7409 LHS = UsualUnaryConversions(LHS.take()); 7410 if (LHS.isInvalid()) 7411 return QualType(); 7412 QualType LHSType = LHS.get()->getType(); 7413 if (IsCompAssign) LHS = OldLHS; 7414 7415 // The RHS is simpler. 7416 RHS = UsualUnaryConversions(RHS.take()); 7417 if (RHS.isInvalid()) 7418 return QualType(); 7419 QualType RHSType = RHS.get()->getType(); 7420 7421 // C99 6.5.7p2: Each of the operands shall have integer type. 7422 if (!LHSType->hasIntegerRepresentation() || 7423 !RHSType->hasIntegerRepresentation()) 7424 return InvalidOperands(Loc, LHS, RHS); 7425 7426 // C++0x: Don't allow scoped enums. FIXME: Use something better than 7427 // hasIntegerRepresentation() above instead of this. 7428 if (isScopedEnumerationType(LHSType) || 7429 isScopedEnumerationType(RHSType)) { 7430 return InvalidOperands(Loc, LHS, RHS); 7431 } 7432 // Sanity-check shift operands 7433 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 7434 7435 // "The type of the result is that of the promoted left operand." 7436 return LHSType; 7437 } 7438 7439 static bool IsWithinTemplateSpecialization(Decl *D) { 7440 if (DeclContext *DC = D->getDeclContext()) { 7441 if (isa<ClassTemplateSpecializationDecl>(DC)) 7442 return true; 7443 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 7444 return FD->isFunctionTemplateSpecialization(); 7445 } 7446 return false; 7447 } 7448 7449 /// If two different enums are compared, raise a warning. 7450 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 7451 Expr *RHS) { 7452 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 7453 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 7454 7455 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 7456 if (!LHSEnumType) 7457 return; 7458 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 7459 if (!RHSEnumType) 7460 return; 7461 7462 // Ignore anonymous enums. 7463 if (!LHSEnumType->getDecl()->getIdentifier()) 7464 return; 7465 if (!RHSEnumType->getDecl()->getIdentifier()) 7466 return; 7467 7468 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 7469 return; 7470 7471 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 7472 << LHSStrippedType << RHSStrippedType 7473 << LHS->getSourceRange() << RHS->getSourceRange(); 7474 } 7475 7476 /// \brief Diagnose bad pointer comparisons. 7477 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 7478 ExprResult &LHS, ExprResult &RHS, 7479 bool IsError) { 7480 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 7481 : diag::ext_typecheck_comparison_of_distinct_pointers) 7482 << LHS.get()->getType() << RHS.get()->getType() 7483 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7484 } 7485 7486 /// \brief Returns false if the pointers are converted to a composite type, 7487 /// true otherwise. 7488 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 7489 ExprResult &LHS, ExprResult &RHS) { 7490 // C++ [expr.rel]p2: 7491 // [...] Pointer conversions (4.10) and qualification 7492 // conversions (4.4) are performed on pointer operands (or on 7493 // a pointer operand and a null pointer constant) to bring 7494 // them to their composite pointer type. [...] 7495 // 7496 // C++ [expr.eq]p1 uses the same notion for (in)equality 7497 // comparisons of pointers. 7498 7499 // C++ [expr.eq]p2: 7500 // In addition, pointers to members can be compared, or a pointer to 7501 // member and a null pointer constant. Pointer to member conversions 7502 // (4.11) and qualification conversions (4.4) are performed to bring 7503 // them to a common type. If one operand is a null pointer constant, 7504 // the common type is the type of the other operand. Otherwise, the 7505 // common type is a pointer to member type similar (4.4) to the type 7506 // of one of the operands, with a cv-qualification signature (4.4) 7507 // that is the union of the cv-qualification signatures of the operand 7508 // types. 7509 7510 QualType LHSType = LHS.get()->getType(); 7511 QualType RHSType = RHS.get()->getType(); 7512 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 7513 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 7514 7515 bool NonStandardCompositeType = false; 7516 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType; 7517 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 7518 if (T.isNull()) { 7519 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 7520 return true; 7521 } 7522 7523 if (NonStandardCompositeType) 7524 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 7525 << LHSType << RHSType << T << LHS.get()->getSourceRange() 7526 << RHS.get()->getSourceRange(); 7527 7528 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast); 7529 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast); 7530 return false; 7531 } 7532 7533 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 7534 ExprResult &LHS, 7535 ExprResult &RHS, 7536 bool IsError) { 7537 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 7538 : diag::ext_typecheck_comparison_of_fptr_to_void) 7539 << LHS.get()->getType() << RHS.get()->getType() 7540 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7541 } 7542 7543 static bool isObjCObjectLiteral(ExprResult &E) { 7544 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 7545 case Stmt::ObjCArrayLiteralClass: 7546 case Stmt::ObjCDictionaryLiteralClass: 7547 case Stmt::ObjCStringLiteralClass: 7548 case Stmt::ObjCBoxedExprClass: 7549 return true; 7550 default: 7551 // Note that ObjCBoolLiteral is NOT an object literal! 7552 return false; 7553 } 7554 } 7555 7556 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 7557 const ObjCObjectPointerType *Type = 7558 LHS->getType()->getAs<ObjCObjectPointerType>(); 7559 7560 // If this is not actually an Objective-C object, bail out. 7561 if (!Type) 7562 return false; 7563 7564 // Get the LHS object's interface type. 7565 QualType InterfaceType = Type->getPointeeType(); 7566 if (const ObjCObjectType *iQFaceTy = 7567 InterfaceType->getAsObjCQualifiedInterfaceType()) 7568 InterfaceType = iQFaceTy->getBaseType(); 7569 7570 // If the RHS isn't an Objective-C object, bail out. 7571 if (!RHS->getType()->isObjCObjectPointerType()) 7572 return false; 7573 7574 // Try to find the -isEqual: method. 7575 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 7576 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 7577 InterfaceType, 7578 /*instance=*/true); 7579 if (!Method) { 7580 if (Type->isObjCIdType()) { 7581 // For 'id', just check the global pool. 7582 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 7583 /*receiverId=*/true, 7584 /*warn=*/false); 7585 } else { 7586 // Check protocols. 7587 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 7588 /*instance=*/true); 7589 } 7590 } 7591 7592 if (!Method) 7593 return false; 7594 7595 QualType T = Method->param_begin()[0]->getType(); 7596 if (!T->isObjCObjectPointerType()) 7597 return false; 7598 7599 QualType R = Method->getReturnType(); 7600 if (!R->isScalarType()) 7601 return false; 7602 7603 return true; 7604 } 7605 7606 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 7607 FromE = FromE->IgnoreParenImpCasts(); 7608 switch (FromE->getStmtClass()) { 7609 default: 7610 break; 7611 case Stmt::ObjCStringLiteralClass: 7612 // "string literal" 7613 return LK_String; 7614 case Stmt::ObjCArrayLiteralClass: 7615 // "array literal" 7616 return LK_Array; 7617 case Stmt::ObjCDictionaryLiteralClass: 7618 // "dictionary literal" 7619 return LK_Dictionary; 7620 case Stmt::BlockExprClass: 7621 return LK_Block; 7622 case Stmt::ObjCBoxedExprClass: { 7623 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 7624 switch (Inner->getStmtClass()) { 7625 case Stmt::IntegerLiteralClass: 7626 case Stmt::FloatingLiteralClass: 7627 case Stmt::CharacterLiteralClass: 7628 case Stmt::ObjCBoolLiteralExprClass: 7629 case Stmt::CXXBoolLiteralExprClass: 7630 // "numeric literal" 7631 return LK_Numeric; 7632 case Stmt::ImplicitCastExprClass: { 7633 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 7634 // Boolean literals can be represented by implicit casts. 7635 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 7636 return LK_Numeric; 7637 break; 7638 } 7639 default: 7640 break; 7641 } 7642 return LK_Boxed; 7643 } 7644 } 7645 return LK_None; 7646 } 7647 7648 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 7649 ExprResult &LHS, ExprResult &RHS, 7650 BinaryOperator::Opcode Opc){ 7651 Expr *Literal; 7652 Expr *Other; 7653 if (isObjCObjectLiteral(LHS)) { 7654 Literal = LHS.get(); 7655 Other = RHS.get(); 7656 } else { 7657 Literal = RHS.get(); 7658 Other = LHS.get(); 7659 } 7660 7661 // Don't warn on comparisons against nil. 7662 Other = Other->IgnoreParenCasts(); 7663 if (Other->isNullPointerConstant(S.getASTContext(), 7664 Expr::NPC_ValueDependentIsNotNull)) 7665 return; 7666 7667 // This should be kept in sync with warn_objc_literal_comparison. 7668 // LK_String should always be after the other literals, since it has its own 7669 // warning flag. 7670 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 7671 assert(LiteralKind != Sema::LK_Block); 7672 if (LiteralKind == Sema::LK_None) { 7673 llvm_unreachable("Unknown Objective-C object literal kind"); 7674 } 7675 7676 if (LiteralKind == Sema::LK_String) 7677 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 7678 << Literal->getSourceRange(); 7679 else 7680 S.Diag(Loc, diag::warn_objc_literal_comparison) 7681 << LiteralKind << Literal->getSourceRange(); 7682 7683 if (BinaryOperator::isEqualityOp(Opc) && 7684 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 7685 SourceLocation Start = LHS.get()->getLocStart(); 7686 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 7687 CharSourceRange OpRange = 7688 CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc)); 7689 7690 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 7691 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 7692 << FixItHint::CreateReplacement(OpRange, " isEqual:") 7693 << FixItHint::CreateInsertion(End, "]"); 7694 } 7695 } 7696 7697 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 7698 ExprResult &RHS, 7699 SourceLocation Loc, 7700 unsigned OpaqueOpc) { 7701 // This checking requires bools. 7702 if (!S.getLangOpts().Bool) return; 7703 7704 // Check that left hand side is !something. 7705 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 7706 if (!UO || UO->getOpcode() != UO_LNot) return; 7707 7708 // Only check if the right hand side is non-bool arithmetic type. 7709 if (RHS.get()->getType()->isBooleanType()) return; 7710 7711 // Make sure that the something in !something is not bool. 7712 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 7713 if (SubExpr->getType()->isBooleanType()) return; 7714 7715 // Emit warning. 7716 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 7717 << Loc; 7718 7719 // First note suggest !(x < y) 7720 SourceLocation FirstOpen = SubExpr->getLocStart(); 7721 SourceLocation FirstClose = RHS.get()->getLocEnd(); 7722 FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose); 7723 if (FirstClose.isInvalid()) 7724 FirstOpen = SourceLocation(); 7725 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 7726 << FixItHint::CreateInsertion(FirstOpen, "(") 7727 << FixItHint::CreateInsertion(FirstClose, ")"); 7728 7729 // Second note suggests (!x) < y 7730 SourceLocation SecondOpen = LHS.get()->getLocStart(); 7731 SourceLocation SecondClose = LHS.get()->getLocEnd(); 7732 SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose); 7733 if (SecondClose.isInvalid()) 7734 SecondOpen = SourceLocation(); 7735 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 7736 << FixItHint::CreateInsertion(SecondOpen, "(") 7737 << FixItHint::CreateInsertion(SecondClose, ")"); 7738 } 7739 7740 // Get the decl for a simple expression: a reference to a variable, 7741 // an implicit C++ field reference, or an implicit ObjC ivar reference. 7742 static ValueDecl *getCompareDecl(Expr *E) { 7743 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 7744 return DR->getDecl(); 7745 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 7746 if (Ivar->isFreeIvar()) 7747 return Ivar->getDecl(); 7748 } 7749 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 7750 if (Mem->isImplicitAccess()) 7751 return Mem->getMemberDecl(); 7752 } 7753 return 0; 7754 } 7755 7756 // C99 6.5.8, C++ [expr.rel] 7757 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 7758 SourceLocation Loc, unsigned OpaqueOpc, 7759 bool IsRelational) { 7760 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 7761 7762 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 7763 7764 // Handle vector comparisons separately. 7765 if (LHS.get()->getType()->isVectorType() || 7766 RHS.get()->getType()->isVectorType()) 7767 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 7768 7769 QualType LHSType = LHS.get()->getType(); 7770 QualType RHSType = RHS.get()->getType(); 7771 7772 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 7773 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 7774 7775 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 7776 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc); 7777 7778 if (!LHSType->hasFloatingRepresentation() && 7779 !(LHSType->isBlockPointerType() && IsRelational) && 7780 !LHS.get()->getLocStart().isMacroID() && 7781 !RHS.get()->getLocStart().isMacroID() && 7782 ActiveTemplateInstantiations.empty()) { 7783 // For non-floating point types, check for self-comparisons of the form 7784 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 7785 // often indicate logic errors in the program. 7786 // 7787 // NOTE: Don't warn about comparison expressions resulting from macro 7788 // expansion. Also don't warn about comparisons which are only self 7789 // comparisons within a template specialization. The warnings should catch 7790 // obvious cases in the definition of the template anyways. The idea is to 7791 // warn when the typed comparison operator will always evaluate to the same 7792 // result. 7793 ValueDecl *DL = getCompareDecl(LHSStripped); 7794 ValueDecl *DR = getCompareDecl(RHSStripped); 7795 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 7796 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7797 << 0 // self- 7798 << (Opc == BO_EQ 7799 || Opc == BO_LE 7800 || Opc == BO_GE)); 7801 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 7802 !DL->getType()->isReferenceType() && 7803 !DR->getType()->isReferenceType()) { 7804 // what is it always going to eval to? 7805 char always_evals_to; 7806 switch(Opc) { 7807 case BO_EQ: // e.g. array1 == array2 7808 always_evals_to = 0; // false 7809 break; 7810 case BO_NE: // e.g. array1 != array2 7811 always_evals_to = 1; // true 7812 break; 7813 default: 7814 // best we can say is 'a constant' 7815 always_evals_to = 2; // e.g. array1 <= array2 7816 break; 7817 } 7818 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always) 7819 << 1 // array 7820 << always_evals_to); 7821 } 7822 7823 if (isa<CastExpr>(LHSStripped)) 7824 LHSStripped = LHSStripped->IgnoreParenCasts(); 7825 if (isa<CastExpr>(RHSStripped)) 7826 RHSStripped = RHSStripped->IgnoreParenCasts(); 7827 7828 // Warn about comparisons against a string constant (unless the other 7829 // operand is null), the user probably wants strcmp. 7830 Expr *literalString = 0; 7831 Expr *literalStringStripped = 0; 7832 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 7833 !RHSStripped->isNullPointerConstant(Context, 7834 Expr::NPC_ValueDependentIsNull)) { 7835 literalString = LHS.get(); 7836 literalStringStripped = LHSStripped; 7837 } else if ((isa<StringLiteral>(RHSStripped) || 7838 isa<ObjCEncodeExpr>(RHSStripped)) && 7839 !LHSStripped->isNullPointerConstant(Context, 7840 Expr::NPC_ValueDependentIsNull)) { 7841 literalString = RHS.get(); 7842 literalStringStripped = RHSStripped; 7843 } 7844 7845 if (literalString) { 7846 DiagRuntimeBehavior(Loc, 0, 7847 PDiag(diag::warn_stringcompare) 7848 << isa<ObjCEncodeExpr>(literalStringStripped) 7849 << literalString->getSourceRange()); 7850 } 7851 } 7852 7853 // C99 6.5.8p3 / C99 6.5.9p4 7854 UsualArithmeticConversions(LHS, RHS); 7855 if (LHS.isInvalid() || RHS.isInvalid()) 7856 return QualType(); 7857 7858 LHSType = LHS.get()->getType(); 7859 RHSType = RHS.get()->getType(); 7860 7861 // The result of comparisons is 'bool' in C++, 'int' in C. 7862 QualType ResultTy = Context.getLogicalOperationType(); 7863 7864 if (IsRelational) { 7865 if (LHSType->isRealType() && RHSType->isRealType()) 7866 return ResultTy; 7867 } else { 7868 // Check for comparisons of floating point operands using != and ==. 7869 if (LHSType->hasFloatingRepresentation()) 7870 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 7871 7872 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 7873 return ResultTy; 7874 } 7875 7876 const Expr::NullPointerConstantKind LHSNullKind = 7877 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 7878 const Expr::NullPointerConstantKind RHSNullKind = 7879 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 7880 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 7881 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 7882 7883 if (!IsRelational && LHSIsNull != RHSIsNull) { 7884 bool IsEquality = Opc == BO_EQ; 7885 if (RHSIsNull) 7886 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 7887 RHS.get()->getSourceRange()); 7888 else 7889 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 7890 LHS.get()->getSourceRange()); 7891 } 7892 7893 // All of the following pointer-related warnings are GCC extensions, except 7894 // when handling null pointer constants. 7895 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 7896 QualType LCanPointeeTy = 7897 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7898 QualType RCanPointeeTy = 7899 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7900 7901 if (getLangOpts().CPlusPlus) { 7902 if (LCanPointeeTy == RCanPointeeTy) 7903 return ResultTy; 7904 if (!IsRelational && 7905 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7906 // Valid unless comparison between non-null pointer and function pointer 7907 // This is a gcc extension compatibility comparison. 7908 // In a SFINAE context, we treat this as a hard error to maintain 7909 // conformance with the C++ standard. 7910 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7911 && !LHSIsNull && !RHSIsNull) { 7912 diagnoseFunctionPointerToVoidComparison( 7913 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 7914 7915 if (isSFINAEContext()) 7916 return QualType(); 7917 7918 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 7919 return ResultTy; 7920 } 7921 } 7922 7923 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7924 return QualType(); 7925 else 7926 return ResultTy; 7927 } 7928 // C99 6.5.9p2 and C99 6.5.8p2 7929 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 7930 RCanPointeeTy.getUnqualifiedType())) { 7931 // Valid unless a relational comparison of function pointers 7932 if (IsRelational && LCanPointeeTy->isFunctionType()) { 7933 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 7934 << LHSType << RHSType << LHS.get()->getSourceRange() 7935 << RHS.get()->getSourceRange(); 7936 } 7937 } else if (!IsRelational && 7938 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 7939 // Valid unless comparison between non-null pointer and function pointer 7940 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 7941 && !LHSIsNull && !RHSIsNull) 7942 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 7943 /*isError*/false); 7944 } else { 7945 // Invalid 7946 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 7947 } 7948 if (LCanPointeeTy != RCanPointeeTy) { 7949 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 7950 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 7951 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 7952 : CK_BitCast; 7953 if (LHSIsNull && !RHSIsNull) 7954 LHS = ImpCastExprToType(LHS.take(), RHSType, Kind); 7955 else 7956 RHS = ImpCastExprToType(RHS.take(), LHSType, Kind); 7957 } 7958 return ResultTy; 7959 } 7960 7961 if (getLangOpts().CPlusPlus) { 7962 // Comparison of nullptr_t with itself. 7963 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 7964 return ResultTy; 7965 7966 // Comparison of pointers with null pointer constants and equality 7967 // comparisons of member pointers to null pointer constants. 7968 if (RHSIsNull && 7969 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 7970 (!IsRelational && 7971 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 7972 RHS = ImpCastExprToType(RHS.take(), LHSType, 7973 LHSType->isMemberPointerType() 7974 ? CK_NullToMemberPointer 7975 : CK_NullToPointer); 7976 return ResultTy; 7977 } 7978 if (LHSIsNull && 7979 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 7980 (!IsRelational && 7981 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 7982 LHS = ImpCastExprToType(LHS.take(), RHSType, 7983 RHSType->isMemberPointerType() 7984 ? CK_NullToMemberPointer 7985 : CK_NullToPointer); 7986 return ResultTy; 7987 } 7988 7989 // Comparison of member pointers. 7990 if (!IsRelational && 7991 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 7992 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 7993 return QualType(); 7994 else 7995 return ResultTy; 7996 } 7997 7998 // Handle scoped enumeration types specifically, since they don't promote 7999 // to integers. 8000 if (LHS.get()->getType()->isEnumeralType() && 8001 Context.hasSameUnqualifiedType(LHS.get()->getType(), 8002 RHS.get()->getType())) 8003 return ResultTy; 8004 } 8005 8006 // Handle block pointer types. 8007 if (!IsRelational && LHSType->isBlockPointerType() && 8008 RHSType->isBlockPointerType()) { 8009 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 8010 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 8011 8012 if (!LHSIsNull && !RHSIsNull && 8013 !Context.typesAreCompatible(lpointee, rpointee)) { 8014 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 8015 << LHSType << RHSType << LHS.get()->getSourceRange() 8016 << RHS.get()->getSourceRange(); 8017 } 8018 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 8019 return ResultTy; 8020 } 8021 8022 // Allow block pointers to be compared with null pointer constants. 8023 if (!IsRelational 8024 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 8025 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 8026 if (!LHSIsNull && !RHSIsNull) { 8027 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 8028 ->getPointeeType()->isVoidType()) 8029 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 8030 ->getPointeeType()->isVoidType()))) 8031 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 8032 << LHSType << RHSType << LHS.get()->getSourceRange() 8033 << RHS.get()->getSourceRange(); 8034 } 8035 if (LHSIsNull && !RHSIsNull) 8036 LHS = ImpCastExprToType(LHS.take(), RHSType, 8037 RHSType->isPointerType() ? CK_BitCast 8038 : CK_AnyPointerToBlockPointerCast); 8039 else 8040 RHS = ImpCastExprToType(RHS.take(), LHSType, 8041 LHSType->isPointerType() ? CK_BitCast 8042 : CK_AnyPointerToBlockPointerCast); 8043 return ResultTy; 8044 } 8045 8046 if (LHSType->isObjCObjectPointerType() || 8047 RHSType->isObjCObjectPointerType()) { 8048 const PointerType *LPT = LHSType->getAs<PointerType>(); 8049 const PointerType *RPT = RHSType->getAs<PointerType>(); 8050 if (LPT || RPT) { 8051 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 8052 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 8053 8054 if (!LPtrToVoid && !RPtrToVoid && 8055 !Context.typesAreCompatible(LHSType, RHSType)) { 8056 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8057 /*isError*/false); 8058 } 8059 if (LHSIsNull && !RHSIsNull) { 8060 Expr *E = LHS.take(); 8061 if (getLangOpts().ObjCAutoRefCount) 8062 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 8063 LHS = ImpCastExprToType(E, RHSType, 8064 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8065 } 8066 else { 8067 Expr *E = RHS.take(); 8068 if (getLangOpts().ObjCAutoRefCount) 8069 CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion); 8070 RHS = ImpCastExprToType(E, LHSType, 8071 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8072 } 8073 return ResultTy; 8074 } 8075 if (LHSType->isObjCObjectPointerType() && 8076 RHSType->isObjCObjectPointerType()) { 8077 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 8078 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8079 /*isError*/false); 8080 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 8081 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 8082 8083 if (LHSIsNull && !RHSIsNull) 8084 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast); 8085 else 8086 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast); 8087 return ResultTy; 8088 } 8089 } 8090 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 8091 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 8092 unsigned DiagID = 0; 8093 bool isError = false; 8094 if (LangOpts.DebuggerSupport) { 8095 // Under a debugger, allow the comparison of pointers to integers, 8096 // since users tend to want to compare addresses. 8097 } else if ((LHSIsNull && LHSType->isIntegerType()) || 8098 (RHSIsNull && RHSType->isIntegerType())) { 8099 if (IsRelational && !getLangOpts().CPlusPlus) 8100 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 8101 } else if (IsRelational && !getLangOpts().CPlusPlus) 8102 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 8103 else if (getLangOpts().CPlusPlus) { 8104 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 8105 isError = true; 8106 } else 8107 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 8108 8109 if (DiagID) { 8110 Diag(Loc, DiagID) 8111 << LHSType << RHSType << LHS.get()->getSourceRange() 8112 << RHS.get()->getSourceRange(); 8113 if (isError) 8114 return QualType(); 8115 } 8116 8117 if (LHSType->isIntegerType()) 8118 LHS = ImpCastExprToType(LHS.take(), RHSType, 8119 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8120 else 8121 RHS = ImpCastExprToType(RHS.take(), LHSType, 8122 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8123 return ResultTy; 8124 } 8125 8126 // Handle block pointers. 8127 if (!IsRelational && RHSIsNull 8128 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 8129 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer); 8130 return ResultTy; 8131 } 8132 if (!IsRelational && LHSIsNull 8133 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 8134 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer); 8135 return ResultTy; 8136 } 8137 8138 return InvalidOperands(Loc, LHS, RHS); 8139 } 8140 8141 8142 // Return a signed type that is of identical size and number of elements. 8143 // For floating point vectors, return an integer type of identical size 8144 // and number of elements. 8145 QualType Sema::GetSignedVectorType(QualType V) { 8146 const VectorType *VTy = V->getAs<VectorType>(); 8147 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 8148 if (TypeSize == Context.getTypeSize(Context.CharTy)) 8149 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 8150 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 8151 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 8152 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 8153 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 8154 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 8155 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 8156 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 8157 "Unhandled vector element size in vector compare"); 8158 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 8159 } 8160 8161 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 8162 /// operates on extended vector types. Instead of producing an IntTy result, 8163 /// like a scalar comparison, a vector comparison produces a vector of integer 8164 /// types. 8165 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 8166 SourceLocation Loc, 8167 bool IsRelational) { 8168 // Check to make sure we're operating on vectors of the same type and width, 8169 // Allowing one side to be a scalar of element type. 8170 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false); 8171 if (vType.isNull()) 8172 return vType; 8173 8174 QualType LHSType = LHS.get()->getType(); 8175 8176 // If AltiVec, the comparison results in a numeric type, i.e. 8177 // bool for C++, int for C 8178 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 8179 return Context.getLogicalOperationType(); 8180 8181 // For non-floating point types, check for self-comparisons of the form 8182 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 8183 // often indicate logic errors in the program. 8184 if (!LHSType->hasFloatingRepresentation() && 8185 ActiveTemplateInstantiations.empty()) { 8186 if (DeclRefExpr* DRL 8187 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 8188 if (DeclRefExpr* DRR 8189 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 8190 if (DRL->getDecl() == DRR->getDecl()) 8191 DiagRuntimeBehavior(Loc, 0, 8192 PDiag(diag::warn_comparison_always) 8193 << 0 // self- 8194 << 2 // "a constant" 8195 ); 8196 } 8197 8198 // Check for comparisons of floating point operands using != and ==. 8199 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 8200 assert (RHS.get()->getType()->hasFloatingRepresentation()); 8201 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 8202 } 8203 8204 // Return a signed type for the vector. 8205 return GetSignedVectorType(LHSType); 8206 } 8207 8208 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 8209 SourceLocation Loc) { 8210 // Ensure that either both operands are of the same vector type, or 8211 // one operand is of a vector type and the other is of its element type. 8212 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false); 8213 if (vType.isNull()) 8214 return InvalidOperands(Loc, LHS, RHS); 8215 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 8216 vType->hasFloatingRepresentation()) 8217 return InvalidOperands(Loc, LHS, RHS); 8218 8219 return GetSignedVectorType(LHS.get()->getType()); 8220 } 8221 8222 inline QualType Sema::CheckBitwiseOperands( 8223 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8224 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8225 8226 if (LHS.get()->getType()->isVectorType() || 8227 RHS.get()->getType()->isVectorType()) { 8228 if (LHS.get()->getType()->hasIntegerRepresentation() && 8229 RHS.get()->getType()->hasIntegerRepresentation()) 8230 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 8231 8232 return InvalidOperands(Loc, LHS, RHS); 8233 } 8234 8235 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS); 8236 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 8237 IsCompAssign); 8238 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 8239 return QualType(); 8240 LHS = LHSResult.take(); 8241 RHS = RHSResult.take(); 8242 8243 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 8244 return compType; 8245 return InvalidOperands(Loc, LHS, RHS); 8246 } 8247 8248 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 8249 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) { 8250 8251 // Check vector operands differently. 8252 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 8253 return CheckVectorLogicalOperands(LHS, RHS, Loc); 8254 8255 // Diagnose cases where the user write a logical and/or but probably meant a 8256 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 8257 // is a constant. 8258 if (LHS.get()->getType()->isIntegerType() && 8259 !LHS.get()->getType()->isBooleanType() && 8260 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 8261 // Don't warn in macros or template instantiations. 8262 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 8263 // If the RHS can be constant folded, and if it constant folds to something 8264 // that isn't 0 or 1 (which indicate a potential logical operation that 8265 // happened to fold to true/false) then warn. 8266 // Parens on the RHS are ignored. 8267 llvm::APSInt Result; 8268 if (RHS.get()->EvaluateAsInt(Result, Context)) 8269 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) || 8270 (Result != 0 && Result != 1)) { 8271 Diag(Loc, diag::warn_logical_instead_of_bitwise) 8272 << RHS.get()->getSourceRange() 8273 << (Opc == BO_LAnd ? "&&" : "||"); 8274 // Suggest replacing the logical operator with the bitwise version 8275 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 8276 << (Opc == BO_LAnd ? "&" : "|") 8277 << FixItHint::CreateReplacement(SourceRange( 8278 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(), 8279 getLangOpts())), 8280 Opc == BO_LAnd ? "&" : "|"); 8281 if (Opc == BO_LAnd) 8282 // Suggest replacing "Foo() && kNonZero" with "Foo()" 8283 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 8284 << FixItHint::CreateRemoval( 8285 SourceRange( 8286 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(), 8287 0, getSourceManager(), 8288 getLangOpts()), 8289 RHS.get()->getLocEnd())); 8290 } 8291 } 8292 8293 if (!Context.getLangOpts().CPlusPlus) { 8294 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 8295 // not operate on the built-in scalar and vector float types. 8296 if (Context.getLangOpts().OpenCL && 8297 Context.getLangOpts().OpenCLVersion < 120) { 8298 if (LHS.get()->getType()->isFloatingType() || 8299 RHS.get()->getType()->isFloatingType()) 8300 return InvalidOperands(Loc, LHS, RHS); 8301 } 8302 8303 LHS = UsualUnaryConversions(LHS.take()); 8304 if (LHS.isInvalid()) 8305 return QualType(); 8306 8307 RHS = UsualUnaryConversions(RHS.take()); 8308 if (RHS.isInvalid()) 8309 return QualType(); 8310 8311 if (!LHS.get()->getType()->isScalarType() || 8312 !RHS.get()->getType()->isScalarType()) 8313 return InvalidOperands(Loc, LHS, RHS); 8314 8315 return Context.IntTy; 8316 } 8317 8318 // The following is safe because we only use this method for 8319 // non-overloadable operands. 8320 8321 // C++ [expr.log.and]p1 8322 // C++ [expr.log.or]p1 8323 // The operands are both contextually converted to type bool. 8324 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 8325 if (LHSRes.isInvalid()) 8326 return InvalidOperands(Loc, LHS, RHS); 8327 LHS = LHSRes; 8328 8329 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 8330 if (RHSRes.isInvalid()) 8331 return InvalidOperands(Loc, LHS, RHS); 8332 RHS = RHSRes; 8333 8334 // C++ [expr.log.and]p2 8335 // C++ [expr.log.or]p2 8336 // The result is a bool. 8337 return Context.BoolTy; 8338 } 8339 8340 static bool IsReadonlyMessage(Expr *E, Sema &S) { 8341 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 8342 if (!ME) return false; 8343 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 8344 ObjCMessageExpr *Base = 8345 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 8346 if (!Base) return false; 8347 return Base->getMethodDecl() != 0; 8348 } 8349 8350 /// Is the given expression (which must be 'const') a reference to a 8351 /// variable which was originally non-const, but which has become 8352 /// 'const' due to being captured within a block? 8353 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 8354 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 8355 assert(E->isLValue() && E->getType().isConstQualified()); 8356 E = E->IgnoreParens(); 8357 8358 // Must be a reference to a declaration from an enclosing scope. 8359 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 8360 if (!DRE) return NCCK_None; 8361 if (!DRE->refersToEnclosingLocal()) return NCCK_None; 8362 8363 // The declaration must be a variable which is not declared 'const'. 8364 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 8365 if (!var) return NCCK_None; 8366 if (var->getType().isConstQualified()) return NCCK_None; 8367 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 8368 8369 // Decide whether the first capture was for a block or a lambda. 8370 DeclContext *DC = S.CurContext, *Prev = 0; 8371 while (DC != var->getDeclContext()) { 8372 Prev = DC; 8373 DC = DC->getParent(); 8374 } 8375 // Unless we have an init-capture, we've gone one step too far. 8376 if (!var->isInitCapture()) 8377 DC = Prev; 8378 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 8379 } 8380 8381 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 8382 /// emit an error and return true. If so, return false. 8383 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 8384 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 8385 SourceLocation OrigLoc = Loc; 8386 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 8387 &Loc); 8388 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 8389 IsLV = Expr::MLV_InvalidMessageExpression; 8390 if (IsLV == Expr::MLV_Valid) 8391 return false; 8392 8393 unsigned Diag = 0; 8394 bool NeedType = false; 8395 switch (IsLV) { // C99 6.5.16p2 8396 case Expr::MLV_ConstQualified: 8397 Diag = diag::err_typecheck_assign_const; 8398 8399 // Use a specialized diagnostic when we're assigning to an object 8400 // from an enclosing function or block. 8401 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 8402 if (NCCK == NCCK_Block) 8403 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 8404 else 8405 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue; 8406 break; 8407 } 8408 8409 // In ARC, use some specialized diagnostics for occasions where we 8410 // infer 'const'. These are always pseudo-strong variables. 8411 if (S.getLangOpts().ObjCAutoRefCount) { 8412 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 8413 if (declRef && isa<VarDecl>(declRef->getDecl())) { 8414 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 8415 8416 // Use the normal diagnostic if it's pseudo-__strong but the 8417 // user actually wrote 'const'. 8418 if (var->isARCPseudoStrong() && 8419 (!var->getTypeSourceInfo() || 8420 !var->getTypeSourceInfo()->getType().isConstQualified())) { 8421 // There are two pseudo-strong cases: 8422 // - self 8423 ObjCMethodDecl *method = S.getCurMethodDecl(); 8424 if (method && var == method->getSelfDecl()) 8425 Diag = method->isClassMethod() 8426 ? diag::err_typecheck_arc_assign_self_class_method 8427 : diag::err_typecheck_arc_assign_self; 8428 8429 // - fast enumeration variables 8430 else 8431 Diag = diag::err_typecheck_arr_assign_enumeration; 8432 8433 SourceRange Assign; 8434 if (Loc != OrigLoc) 8435 Assign = SourceRange(OrigLoc, OrigLoc); 8436 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 8437 // We need to preserve the AST regardless, so migration tool 8438 // can do its job. 8439 return false; 8440 } 8441 } 8442 } 8443 8444 break; 8445 case Expr::MLV_ArrayType: 8446 case Expr::MLV_ArrayTemporary: 8447 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 8448 NeedType = true; 8449 break; 8450 case Expr::MLV_NotObjectType: 8451 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 8452 NeedType = true; 8453 break; 8454 case Expr::MLV_LValueCast: 8455 Diag = diag::err_typecheck_lvalue_casts_not_supported; 8456 break; 8457 case Expr::MLV_Valid: 8458 llvm_unreachable("did not take early return for MLV_Valid"); 8459 case Expr::MLV_InvalidExpression: 8460 case Expr::MLV_MemberFunction: 8461 case Expr::MLV_ClassTemporary: 8462 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 8463 break; 8464 case Expr::MLV_IncompleteType: 8465 case Expr::MLV_IncompleteVoidType: 8466 return S.RequireCompleteType(Loc, E->getType(), 8467 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 8468 case Expr::MLV_DuplicateVectorComponents: 8469 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 8470 break; 8471 case Expr::MLV_NoSetterProperty: 8472 llvm_unreachable("readonly properties should be processed differently"); 8473 case Expr::MLV_InvalidMessageExpression: 8474 Diag = diag::error_readonly_message_assignment; 8475 break; 8476 case Expr::MLV_SubObjCPropertySetting: 8477 Diag = diag::error_no_subobject_property_setting; 8478 break; 8479 } 8480 8481 SourceRange Assign; 8482 if (Loc != OrigLoc) 8483 Assign = SourceRange(OrigLoc, OrigLoc); 8484 if (NeedType) 8485 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 8486 else 8487 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 8488 return true; 8489 } 8490 8491 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 8492 SourceLocation Loc, 8493 Sema &Sema) { 8494 // C / C++ fields 8495 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 8496 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 8497 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 8498 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 8499 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 8500 } 8501 8502 // Objective-C instance variables 8503 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 8504 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 8505 if (OL && OR && OL->getDecl() == OR->getDecl()) { 8506 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 8507 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 8508 if (RL && RR && RL->getDecl() == RR->getDecl()) 8509 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 8510 } 8511 } 8512 8513 // C99 6.5.16.1 8514 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 8515 SourceLocation Loc, 8516 QualType CompoundType) { 8517 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 8518 8519 // Verify that LHS is a modifiable lvalue, and emit error if not. 8520 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 8521 return QualType(); 8522 8523 QualType LHSType = LHSExpr->getType(); 8524 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 8525 CompoundType; 8526 AssignConvertType ConvTy; 8527 if (CompoundType.isNull()) { 8528 Expr *RHSCheck = RHS.get(); 8529 8530 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 8531 8532 QualType LHSTy(LHSType); 8533 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 8534 if (RHS.isInvalid()) 8535 return QualType(); 8536 // Special case of NSObject attributes on c-style pointer types. 8537 if (ConvTy == IncompatiblePointer && 8538 ((Context.isObjCNSObjectType(LHSType) && 8539 RHSType->isObjCObjectPointerType()) || 8540 (Context.isObjCNSObjectType(RHSType) && 8541 LHSType->isObjCObjectPointerType()))) 8542 ConvTy = Compatible; 8543 8544 if (ConvTy == Compatible && 8545 LHSType->isObjCObjectType()) 8546 Diag(Loc, diag::err_objc_object_assignment) 8547 << LHSType; 8548 8549 // If the RHS is a unary plus or minus, check to see if they = and + are 8550 // right next to each other. If so, the user may have typo'd "x =+ 4" 8551 // instead of "x += 4". 8552 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 8553 RHSCheck = ICE->getSubExpr(); 8554 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 8555 if ((UO->getOpcode() == UO_Plus || 8556 UO->getOpcode() == UO_Minus) && 8557 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 8558 // Only if the two operators are exactly adjacent. 8559 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 8560 // And there is a space or other character before the subexpr of the 8561 // unary +/-. We don't want to warn on "x=-1". 8562 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 8563 UO->getSubExpr()->getLocStart().isFileID()) { 8564 Diag(Loc, diag::warn_not_compound_assign) 8565 << (UO->getOpcode() == UO_Plus ? "+" : "-") 8566 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 8567 } 8568 } 8569 8570 if (ConvTy == Compatible) { 8571 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 8572 // Warn about retain cycles where a block captures the LHS, but 8573 // not if the LHS is a simple variable into which the block is 8574 // being stored...unless that variable can be captured by reference! 8575 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 8576 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 8577 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 8578 checkRetainCycles(LHSExpr, RHS.get()); 8579 8580 // It is safe to assign a weak reference into a strong variable. 8581 // Although this code can still have problems: 8582 // id x = self.weakProp; 8583 // id y = self.weakProp; 8584 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8585 // paths through the function. This should be revisited if 8586 // -Wrepeated-use-of-weak is made flow-sensitive. 8587 DiagnosticsEngine::Level Level = 8588 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 8589 RHS.get()->getLocStart()); 8590 if (Level != DiagnosticsEngine::Ignored) 8591 getCurFunction()->markSafeWeakUse(RHS.get()); 8592 8593 } else if (getLangOpts().ObjCAutoRefCount) { 8594 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 8595 } 8596 } 8597 } else { 8598 // Compound assignment "x += y" 8599 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 8600 } 8601 8602 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 8603 RHS.get(), AA_Assigning)) 8604 return QualType(); 8605 8606 CheckForNullPointerDereference(*this, LHSExpr); 8607 8608 // C99 6.5.16p3: The type of an assignment expression is the type of the 8609 // left operand unless the left operand has qualified type, in which case 8610 // it is the unqualified version of the type of the left operand. 8611 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 8612 // is converted to the type of the assignment expression (above). 8613 // C++ 5.17p1: the type of the assignment expression is that of its left 8614 // operand. 8615 return (getLangOpts().CPlusPlus 8616 ? LHSType : LHSType.getUnqualifiedType()); 8617 } 8618 8619 // C99 6.5.17 8620 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 8621 SourceLocation Loc) { 8622 LHS = S.CheckPlaceholderExpr(LHS.take()); 8623 RHS = S.CheckPlaceholderExpr(RHS.take()); 8624 if (LHS.isInvalid() || RHS.isInvalid()) 8625 return QualType(); 8626 8627 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 8628 // operands, but not unary promotions. 8629 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 8630 8631 // So we treat the LHS as a ignored value, and in C++ we allow the 8632 // containing site to determine what should be done with the RHS. 8633 LHS = S.IgnoredValueConversions(LHS.take()); 8634 if (LHS.isInvalid()) 8635 return QualType(); 8636 8637 S.DiagnoseUnusedExprResult(LHS.get()); 8638 8639 if (!S.getLangOpts().CPlusPlus) { 8640 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take()); 8641 if (RHS.isInvalid()) 8642 return QualType(); 8643 if (!RHS.get()->getType()->isVoidType()) 8644 S.RequireCompleteType(Loc, RHS.get()->getType(), 8645 diag::err_incomplete_type); 8646 } 8647 8648 return RHS.get()->getType(); 8649 } 8650 8651 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 8652 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 8653 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 8654 ExprValueKind &VK, 8655 SourceLocation OpLoc, 8656 bool IsInc, bool IsPrefix) { 8657 if (Op->isTypeDependent()) 8658 return S.Context.DependentTy; 8659 8660 QualType ResType = Op->getType(); 8661 // Atomic types can be used for increment / decrement where the non-atomic 8662 // versions can, so ignore the _Atomic() specifier for the purpose of 8663 // checking. 8664 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8665 ResType = ResAtomicType->getValueType(); 8666 8667 assert(!ResType.isNull() && "no type for increment/decrement expression"); 8668 8669 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 8670 // Decrement of bool is not allowed. 8671 if (!IsInc) { 8672 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 8673 return QualType(); 8674 } 8675 // Increment of bool sets it to true, but is deprecated. 8676 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 8677 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 8678 // Error on enum increments and decrements in C++ mode 8679 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 8680 return QualType(); 8681 } else if (ResType->isRealType()) { 8682 // OK! 8683 } else if (ResType->isPointerType()) { 8684 // C99 6.5.2.4p2, 6.5.6p2 8685 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 8686 return QualType(); 8687 } else if (ResType->isObjCObjectPointerType()) { 8688 // On modern runtimes, ObjC pointer arithmetic is forbidden. 8689 // Otherwise, we just need a complete type. 8690 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 8691 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 8692 return QualType(); 8693 } else if (ResType->isAnyComplexType()) { 8694 // C99 does not support ++/-- on complex types, we allow as an extension. 8695 S.Diag(OpLoc, diag::ext_integer_increment_complex) 8696 << ResType << Op->getSourceRange(); 8697 } else if (ResType->isPlaceholderType()) { 8698 ExprResult PR = S.CheckPlaceholderExpr(Op); 8699 if (PR.isInvalid()) return QualType(); 8700 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc, 8701 IsInc, IsPrefix); 8702 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 8703 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 8704 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 8705 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 8706 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 8707 } else { 8708 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 8709 << ResType << int(IsInc) << Op->getSourceRange(); 8710 return QualType(); 8711 } 8712 // At this point, we know we have a real, complex or pointer type. 8713 // Now make sure the operand is a modifiable lvalue. 8714 if (CheckForModifiableLvalue(Op, OpLoc, S)) 8715 return QualType(); 8716 // In C++, a prefix increment is the same type as the operand. Otherwise 8717 // (in C or with postfix), the increment is the unqualified type of the 8718 // operand. 8719 if (IsPrefix && S.getLangOpts().CPlusPlus) { 8720 VK = VK_LValue; 8721 return ResType; 8722 } else { 8723 VK = VK_RValue; 8724 return ResType.getUnqualifiedType(); 8725 } 8726 } 8727 8728 8729 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 8730 /// This routine allows us to typecheck complex/recursive expressions 8731 /// where the declaration is needed for type checking. We only need to 8732 /// handle cases when the expression references a function designator 8733 /// or is an lvalue. Here are some examples: 8734 /// - &(x) => x 8735 /// - &*****f => f for f a function designator. 8736 /// - &s.xx => s 8737 /// - &s.zz[1].yy -> s, if zz is an array 8738 /// - *(x + 1) -> x, if x is an array 8739 /// - &"123"[2] -> 0 8740 /// - & __real__ x -> x 8741 static ValueDecl *getPrimaryDecl(Expr *E) { 8742 switch (E->getStmtClass()) { 8743 case Stmt::DeclRefExprClass: 8744 return cast<DeclRefExpr>(E)->getDecl(); 8745 case Stmt::MemberExprClass: 8746 // If this is an arrow operator, the address is an offset from 8747 // the base's value, so the object the base refers to is 8748 // irrelevant. 8749 if (cast<MemberExpr>(E)->isArrow()) 8750 return 0; 8751 // Otherwise, the expression refers to a part of the base 8752 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 8753 case Stmt::ArraySubscriptExprClass: { 8754 // FIXME: This code shouldn't be necessary! We should catch the implicit 8755 // promotion of register arrays earlier. 8756 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 8757 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 8758 if (ICE->getSubExpr()->getType()->isArrayType()) 8759 return getPrimaryDecl(ICE->getSubExpr()); 8760 } 8761 return 0; 8762 } 8763 case Stmt::UnaryOperatorClass: { 8764 UnaryOperator *UO = cast<UnaryOperator>(E); 8765 8766 switch(UO->getOpcode()) { 8767 case UO_Real: 8768 case UO_Imag: 8769 case UO_Extension: 8770 return getPrimaryDecl(UO->getSubExpr()); 8771 default: 8772 return 0; 8773 } 8774 } 8775 case Stmt::ParenExprClass: 8776 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 8777 case Stmt::ImplicitCastExprClass: 8778 // If the result of an implicit cast is an l-value, we care about 8779 // the sub-expression; otherwise, the result here doesn't matter. 8780 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 8781 default: 8782 return 0; 8783 } 8784 } 8785 8786 namespace { 8787 enum { 8788 AO_Bit_Field = 0, 8789 AO_Vector_Element = 1, 8790 AO_Property_Expansion = 2, 8791 AO_Register_Variable = 3, 8792 AO_No_Error = 4 8793 }; 8794 } 8795 /// \brief Diagnose invalid operand for address of operations. 8796 /// 8797 /// \param Type The type of operand which cannot have its address taken. 8798 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 8799 Expr *E, unsigned Type) { 8800 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 8801 } 8802 8803 /// CheckAddressOfOperand - The operand of & must be either a function 8804 /// designator or an lvalue designating an object. If it is an lvalue, the 8805 /// object cannot be declared with storage class register or be a bit field. 8806 /// Note: The usual conversions are *not* applied to the operand of the & 8807 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 8808 /// In C++, the operand might be an overloaded function name, in which case 8809 /// we allow the '&' but retain the overloaded-function type. 8810 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 8811 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 8812 if (PTy->getKind() == BuiltinType::Overload) { 8813 Expr *E = OrigOp.get()->IgnoreParens(); 8814 if (!isa<OverloadExpr>(E)) { 8815 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 8816 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 8817 << OrigOp.get()->getSourceRange(); 8818 return QualType(); 8819 } 8820 8821 OverloadExpr *Ovl = cast<OverloadExpr>(E); 8822 if (isa<UnresolvedMemberExpr>(Ovl)) 8823 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 8824 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8825 << OrigOp.get()->getSourceRange(); 8826 return QualType(); 8827 } 8828 8829 return Context.OverloadTy; 8830 } 8831 8832 if (PTy->getKind() == BuiltinType::UnknownAny) 8833 return Context.UnknownAnyTy; 8834 8835 if (PTy->getKind() == BuiltinType::BoundMember) { 8836 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8837 << OrigOp.get()->getSourceRange(); 8838 return QualType(); 8839 } 8840 8841 OrigOp = CheckPlaceholderExpr(OrigOp.take()); 8842 if (OrigOp.isInvalid()) return QualType(); 8843 } 8844 8845 if (OrigOp.get()->isTypeDependent()) 8846 return Context.DependentTy; 8847 8848 assert(!OrigOp.get()->getType()->isPlaceholderType()); 8849 8850 // Make sure to ignore parentheses in subsequent checks 8851 Expr *op = OrigOp.get()->IgnoreParens(); 8852 8853 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 8854 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 8855 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 8856 return QualType(); 8857 } 8858 8859 if (getLangOpts().C99) { 8860 // Implement C99-only parts of addressof rules. 8861 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 8862 if (uOp->getOpcode() == UO_Deref) 8863 // Per C99 6.5.3.2, the address of a deref always returns a valid result 8864 // (assuming the deref expression is valid). 8865 return uOp->getSubExpr()->getType(); 8866 } 8867 // Technically, there should be a check for array subscript 8868 // expressions here, but the result of one is always an lvalue anyway. 8869 } 8870 ValueDecl *dcl = getPrimaryDecl(op); 8871 Expr::LValueClassification lval = op->ClassifyLValue(Context); 8872 unsigned AddressOfError = AO_No_Error; 8873 8874 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 8875 bool sfinae = (bool)isSFINAEContext(); 8876 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 8877 : diag::ext_typecheck_addrof_temporary) 8878 << op->getType() << op->getSourceRange(); 8879 if (sfinae) 8880 return QualType(); 8881 // Materialize the temporary as an lvalue so that we can take its address. 8882 OrigOp = op = new (Context) 8883 MaterializeTemporaryExpr(op->getType(), OrigOp.take(), true, 0); 8884 } else if (isa<ObjCSelectorExpr>(op)) { 8885 return Context.getPointerType(op->getType()); 8886 } else if (lval == Expr::LV_MemberFunction) { 8887 // If it's an instance method, make a member pointer. 8888 // The expression must have exactly the form &A::foo. 8889 8890 // If the underlying expression isn't a decl ref, give up. 8891 if (!isa<DeclRefExpr>(op)) { 8892 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8893 << OrigOp.get()->getSourceRange(); 8894 return QualType(); 8895 } 8896 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 8897 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 8898 8899 // The id-expression was parenthesized. 8900 if (OrigOp.get() != DRE) { 8901 Diag(OpLoc, diag::err_parens_pointer_member_function) 8902 << OrigOp.get()->getSourceRange(); 8903 8904 // The method was named without a qualifier. 8905 } else if (!DRE->getQualifier()) { 8906 if (MD->getParent()->getName().empty()) 8907 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8908 << op->getSourceRange(); 8909 else { 8910 SmallString<32> Str; 8911 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 8912 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 8913 << op->getSourceRange() 8914 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 8915 } 8916 } 8917 8918 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 8919 if (isa<CXXDestructorDecl>(MD)) 8920 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 8921 8922 QualType MPTy = Context.getMemberPointerType( 8923 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 8924 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 8925 RequireCompleteType(OpLoc, MPTy, 0); 8926 return MPTy; 8927 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 8928 // C99 6.5.3.2p1 8929 // The operand must be either an l-value or a function designator 8930 if (!op->getType()->isFunctionType()) { 8931 // Use a special diagnostic for loads from property references. 8932 if (isa<PseudoObjectExpr>(op)) { 8933 AddressOfError = AO_Property_Expansion; 8934 } else { 8935 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 8936 << op->getType() << op->getSourceRange(); 8937 return QualType(); 8938 } 8939 } 8940 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 8941 // The operand cannot be a bit-field 8942 AddressOfError = AO_Bit_Field; 8943 } else if (op->getObjectKind() == OK_VectorComponent) { 8944 // The operand cannot be an element of a vector 8945 AddressOfError = AO_Vector_Element; 8946 } else if (dcl) { // C99 6.5.3.2p1 8947 // We have an lvalue with a decl. Make sure the decl is not declared 8948 // with the register storage-class specifier. 8949 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 8950 // in C++ it is not error to take address of a register 8951 // variable (c++03 7.1.1P3) 8952 if (vd->getStorageClass() == SC_Register && 8953 !getLangOpts().CPlusPlus) { 8954 AddressOfError = AO_Register_Variable; 8955 } 8956 } else if (isa<FunctionTemplateDecl>(dcl)) { 8957 return Context.OverloadTy; 8958 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 8959 // Okay: we can take the address of a field. 8960 // Could be a pointer to member, though, if there is an explicit 8961 // scope qualifier for the class. 8962 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 8963 DeclContext *Ctx = dcl->getDeclContext(); 8964 if (Ctx && Ctx->isRecord()) { 8965 if (dcl->getType()->isReferenceType()) { 8966 Diag(OpLoc, 8967 diag::err_cannot_form_pointer_to_member_of_reference_type) 8968 << dcl->getDeclName() << dcl->getType(); 8969 return QualType(); 8970 } 8971 8972 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 8973 Ctx = Ctx->getParent(); 8974 8975 QualType MPTy = Context.getMemberPointerType( 8976 op->getType(), 8977 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 8978 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 8979 RequireCompleteType(OpLoc, MPTy, 0); 8980 return MPTy; 8981 } 8982 } 8983 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 8984 llvm_unreachable("Unknown/unexpected decl type"); 8985 } 8986 8987 if (AddressOfError != AO_No_Error) { 8988 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 8989 return QualType(); 8990 } 8991 8992 if (lval == Expr::LV_IncompleteVoidType) { 8993 // Taking the address of a void variable is technically illegal, but we 8994 // allow it in cases which are otherwise valid. 8995 // Example: "extern void x; void* y = &x;". 8996 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 8997 } 8998 8999 // If the operand has type "type", the result has type "pointer to type". 9000 if (op->getType()->isObjCObjectType()) 9001 return Context.getObjCObjectPointerType(op->getType()); 9002 return Context.getPointerType(op->getType()); 9003 } 9004 9005 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 9006 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 9007 SourceLocation OpLoc) { 9008 if (Op->isTypeDependent()) 9009 return S.Context.DependentTy; 9010 9011 ExprResult ConvResult = S.UsualUnaryConversions(Op); 9012 if (ConvResult.isInvalid()) 9013 return QualType(); 9014 Op = ConvResult.take(); 9015 QualType OpTy = Op->getType(); 9016 QualType Result; 9017 9018 if (isa<CXXReinterpretCastExpr>(Op)) { 9019 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 9020 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 9021 Op->getSourceRange()); 9022 } 9023 9024 // Note that per both C89 and C99, indirection is always legal, even if OpTy 9025 // is an incomplete type or void. It would be possible to warn about 9026 // dereferencing a void pointer, but it's completely well-defined, and such a 9027 // warning is unlikely to catch any mistakes. 9028 if (const PointerType *PT = OpTy->getAs<PointerType>()) 9029 Result = PT->getPointeeType(); 9030 else if (const ObjCObjectPointerType *OPT = 9031 OpTy->getAs<ObjCObjectPointerType>()) 9032 Result = OPT->getPointeeType(); 9033 else { 9034 ExprResult PR = S.CheckPlaceholderExpr(Op); 9035 if (PR.isInvalid()) return QualType(); 9036 if (PR.take() != Op) 9037 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc); 9038 } 9039 9040 if (Result.isNull()) { 9041 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 9042 << OpTy << Op->getSourceRange(); 9043 return QualType(); 9044 } 9045 9046 // Dereferences are usually l-values... 9047 VK = VK_LValue; 9048 9049 // ...except that certain expressions are never l-values in C. 9050 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 9051 VK = VK_RValue; 9052 9053 return Result; 9054 } 9055 9056 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode( 9057 tok::TokenKind Kind) { 9058 BinaryOperatorKind Opc; 9059 switch (Kind) { 9060 default: llvm_unreachable("Unknown binop!"); 9061 case tok::periodstar: Opc = BO_PtrMemD; break; 9062 case tok::arrowstar: Opc = BO_PtrMemI; break; 9063 case tok::star: Opc = BO_Mul; break; 9064 case tok::slash: Opc = BO_Div; break; 9065 case tok::percent: Opc = BO_Rem; break; 9066 case tok::plus: Opc = BO_Add; break; 9067 case tok::minus: Opc = BO_Sub; break; 9068 case tok::lessless: Opc = BO_Shl; break; 9069 case tok::greatergreater: Opc = BO_Shr; break; 9070 case tok::lessequal: Opc = BO_LE; break; 9071 case tok::less: Opc = BO_LT; break; 9072 case tok::greaterequal: Opc = BO_GE; break; 9073 case tok::greater: Opc = BO_GT; break; 9074 case tok::exclaimequal: Opc = BO_NE; break; 9075 case tok::equalequal: Opc = BO_EQ; break; 9076 case tok::amp: Opc = BO_And; break; 9077 case tok::caret: Opc = BO_Xor; break; 9078 case tok::pipe: Opc = BO_Or; break; 9079 case tok::ampamp: Opc = BO_LAnd; break; 9080 case tok::pipepipe: Opc = BO_LOr; break; 9081 case tok::equal: Opc = BO_Assign; break; 9082 case tok::starequal: Opc = BO_MulAssign; break; 9083 case tok::slashequal: Opc = BO_DivAssign; break; 9084 case tok::percentequal: Opc = BO_RemAssign; break; 9085 case tok::plusequal: Opc = BO_AddAssign; break; 9086 case tok::minusequal: Opc = BO_SubAssign; break; 9087 case tok::lesslessequal: Opc = BO_ShlAssign; break; 9088 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 9089 case tok::ampequal: Opc = BO_AndAssign; break; 9090 case tok::caretequal: Opc = BO_XorAssign; break; 9091 case tok::pipeequal: Opc = BO_OrAssign; break; 9092 case tok::comma: Opc = BO_Comma; break; 9093 } 9094 return Opc; 9095 } 9096 9097 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 9098 tok::TokenKind Kind) { 9099 UnaryOperatorKind Opc; 9100 switch (Kind) { 9101 default: llvm_unreachable("Unknown unary op!"); 9102 case tok::plusplus: Opc = UO_PreInc; break; 9103 case tok::minusminus: Opc = UO_PreDec; break; 9104 case tok::amp: Opc = UO_AddrOf; break; 9105 case tok::star: Opc = UO_Deref; break; 9106 case tok::plus: Opc = UO_Plus; break; 9107 case tok::minus: Opc = UO_Minus; break; 9108 case tok::tilde: Opc = UO_Not; break; 9109 case tok::exclaim: Opc = UO_LNot; break; 9110 case tok::kw___real: Opc = UO_Real; break; 9111 case tok::kw___imag: Opc = UO_Imag; break; 9112 case tok::kw___extension__: Opc = UO_Extension; break; 9113 } 9114 return Opc; 9115 } 9116 9117 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 9118 /// This warning is only emitted for builtin assignment operations. It is also 9119 /// suppressed in the event of macro expansions. 9120 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 9121 SourceLocation OpLoc) { 9122 if (!S.ActiveTemplateInstantiations.empty()) 9123 return; 9124 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 9125 return; 9126 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 9127 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 9128 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 9129 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 9130 if (!LHSDeclRef || !RHSDeclRef || 9131 LHSDeclRef->getLocation().isMacroID() || 9132 RHSDeclRef->getLocation().isMacroID()) 9133 return; 9134 const ValueDecl *LHSDecl = 9135 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 9136 const ValueDecl *RHSDecl = 9137 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 9138 if (LHSDecl != RHSDecl) 9139 return; 9140 if (LHSDecl->getType().isVolatileQualified()) 9141 return; 9142 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 9143 if (RefTy->getPointeeType().isVolatileQualified()) 9144 return; 9145 9146 S.Diag(OpLoc, diag::warn_self_assignment) 9147 << LHSDeclRef->getType() 9148 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9149 } 9150 9151 /// Check if a bitwise-& is performed on an Objective-C pointer. This 9152 /// is usually indicative of introspection within the Objective-C pointer. 9153 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 9154 SourceLocation OpLoc) { 9155 if (!S.getLangOpts().ObjC1) 9156 return; 9157 9158 const Expr *ObjCPointerExpr = 0, *OtherExpr = 0; 9159 const Expr *LHS = L.get(); 9160 const Expr *RHS = R.get(); 9161 9162 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 9163 ObjCPointerExpr = LHS; 9164 OtherExpr = RHS; 9165 } 9166 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 9167 ObjCPointerExpr = RHS; 9168 OtherExpr = LHS; 9169 } 9170 9171 // This warning is deliberately made very specific to reduce false 9172 // positives with logic that uses '&' for hashing. This logic mainly 9173 // looks for code trying to introspect into tagged pointers, which 9174 // code should generally never do. 9175 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 9176 unsigned Diag = diag::warn_objc_pointer_masking; 9177 // Determine if we are introspecting the result of performSelectorXXX. 9178 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 9179 // Special case messages to -performSelector and friends, which 9180 // can return non-pointer values boxed in a pointer value. 9181 // Some clients may wish to silence warnings in this subcase. 9182 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 9183 Selector S = ME->getSelector(); 9184 StringRef SelArg0 = S.getNameForSlot(0); 9185 if (SelArg0.startswith("performSelector")) 9186 Diag = diag::warn_objc_pointer_masking_performSelector; 9187 } 9188 9189 S.Diag(OpLoc, Diag) 9190 << ObjCPointerExpr->getSourceRange(); 9191 } 9192 } 9193 9194 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 9195 /// operator @p Opc at location @c TokLoc. This routine only supports 9196 /// built-in operations; ActOnBinOp handles overloaded operators. 9197 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 9198 BinaryOperatorKind Opc, 9199 Expr *LHSExpr, Expr *RHSExpr) { 9200 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 9201 // The syntax only allows initializer lists on the RHS of assignment, 9202 // so we don't need to worry about accepting invalid code for 9203 // non-assignment operators. 9204 // C++11 5.17p9: 9205 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 9206 // of x = {} is x = T(). 9207 InitializationKind Kind = 9208 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 9209 InitializedEntity Entity = 9210 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 9211 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 9212 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 9213 if (Init.isInvalid()) 9214 return Init; 9215 RHSExpr = Init.take(); 9216 } 9217 9218 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr); 9219 QualType ResultTy; // Result type of the binary operator. 9220 // The following two variables are used for compound assignment operators 9221 QualType CompLHSTy; // Type of LHS after promotions for computation 9222 QualType CompResultTy; // Type of computation result 9223 ExprValueKind VK = VK_RValue; 9224 ExprObjectKind OK = OK_Ordinary; 9225 9226 switch (Opc) { 9227 case BO_Assign: 9228 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 9229 if (getLangOpts().CPlusPlus && 9230 LHS.get()->getObjectKind() != OK_ObjCProperty) { 9231 VK = LHS.get()->getValueKind(); 9232 OK = LHS.get()->getObjectKind(); 9233 } 9234 if (!ResultTy.isNull()) 9235 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 9236 break; 9237 case BO_PtrMemD: 9238 case BO_PtrMemI: 9239 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 9240 Opc == BO_PtrMemI); 9241 break; 9242 case BO_Mul: 9243 case BO_Div: 9244 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 9245 Opc == BO_Div); 9246 break; 9247 case BO_Rem: 9248 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 9249 break; 9250 case BO_Add: 9251 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 9252 break; 9253 case BO_Sub: 9254 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 9255 break; 9256 case BO_Shl: 9257 case BO_Shr: 9258 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 9259 break; 9260 case BO_LE: 9261 case BO_LT: 9262 case BO_GE: 9263 case BO_GT: 9264 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 9265 break; 9266 case BO_EQ: 9267 case BO_NE: 9268 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 9269 break; 9270 case BO_And: 9271 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 9272 case BO_Xor: 9273 case BO_Or: 9274 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 9275 break; 9276 case BO_LAnd: 9277 case BO_LOr: 9278 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 9279 break; 9280 case BO_MulAssign: 9281 case BO_DivAssign: 9282 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 9283 Opc == BO_DivAssign); 9284 CompLHSTy = CompResultTy; 9285 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9286 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9287 break; 9288 case BO_RemAssign: 9289 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 9290 CompLHSTy = CompResultTy; 9291 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9292 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9293 break; 9294 case BO_AddAssign: 9295 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 9296 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9297 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9298 break; 9299 case BO_SubAssign: 9300 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 9301 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9302 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9303 break; 9304 case BO_ShlAssign: 9305 case BO_ShrAssign: 9306 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 9307 CompLHSTy = CompResultTy; 9308 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9309 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9310 break; 9311 case BO_AndAssign: 9312 case BO_XorAssign: 9313 case BO_OrAssign: 9314 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 9315 CompLHSTy = CompResultTy; 9316 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9317 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9318 break; 9319 case BO_Comma: 9320 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 9321 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 9322 VK = RHS.get()->getValueKind(); 9323 OK = RHS.get()->getObjectKind(); 9324 } 9325 break; 9326 } 9327 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 9328 return ExprError(); 9329 9330 // Check for array bounds violations for both sides of the BinaryOperator 9331 CheckArrayAccess(LHS.get()); 9332 CheckArrayAccess(RHS.get()); 9333 9334 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 9335 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 9336 &Context.Idents.get("object_setClass"), 9337 SourceLocation(), LookupOrdinaryName); 9338 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 9339 SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 9340 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 9341 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 9342 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 9343 FixItHint::CreateInsertion(RHSLocEnd, ")"); 9344 } 9345 else 9346 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 9347 } 9348 else if (const ObjCIvarRefExpr *OIRE = 9349 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 9350 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 9351 9352 if (CompResultTy.isNull()) 9353 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc, 9354 ResultTy, VK, OK, OpLoc, 9355 FPFeatures.fp_contract)); 9356 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 9357 OK_ObjCProperty) { 9358 VK = VK_LValue; 9359 OK = LHS.get()->getObjectKind(); 9360 } 9361 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc, 9362 ResultTy, VK, OK, CompLHSTy, 9363 CompResultTy, OpLoc, 9364 FPFeatures.fp_contract)); 9365 } 9366 9367 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 9368 /// operators are mixed in a way that suggests that the programmer forgot that 9369 /// comparison operators have higher precedence. The most typical example of 9370 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 9371 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 9372 SourceLocation OpLoc, Expr *LHSExpr, 9373 Expr *RHSExpr) { 9374 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 9375 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 9376 9377 // Check that one of the sides is a comparison operator. 9378 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 9379 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 9380 if (!isLeftComp && !isRightComp) 9381 return; 9382 9383 // Bitwise operations are sometimes used as eager logical ops. 9384 // Don't diagnose this. 9385 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 9386 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 9387 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise)) 9388 return; 9389 9390 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 9391 OpLoc) 9392 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 9393 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 9394 SourceRange ParensRange = isLeftComp ? 9395 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 9396 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart()); 9397 9398 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 9399 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 9400 SuggestParentheses(Self, OpLoc, 9401 Self.PDiag(diag::note_precedence_silence) << OpStr, 9402 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 9403 SuggestParentheses(Self, OpLoc, 9404 Self.PDiag(diag::note_precedence_bitwise_first) 9405 << BinaryOperator::getOpcodeStr(Opc), 9406 ParensRange); 9407 } 9408 9409 /// \brief It accepts a '&' expr that is inside a '|' one. 9410 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression 9411 /// in parentheses. 9412 static void 9413 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 9414 BinaryOperator *Bop) { 9415 assert(Bop->getOpcode() == BO_And); 9416 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 9417 << Bop->getSourceRange() << OpLoc; 9418 SuggestParentheses(Self, Bop->getOperatorLoc(), 9419 Self.PDiag(diag::note_precedence_silence) 9420 << Bop->getOpcodeStr(), 9421 Bop->getSourceRange()); 9422 } 9423 9424 /// \brief It accepts a '&&' expr that is inside a '||' one. 9425 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 9426 /// in parentheses. 9427 static void 9428 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 9429 BinaryOperator *Bop) { 9430 assert(Bop->getOpcode() == BO_LAnd); 9431 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 9432 << Bop->getSourceRange() << OpLoc; 9433 SuggestParentheses(Self, Bop->getOperatorLoc(), 9434 Self.PDiag(diag::note_precedence_silence) 9435 << Bop->getOpcodeStr(), 9436 Bop->getSourceRange()); 9437 } 9438 9439 /// \brief Returns true if the given expression can be evaluated as a constant 9440 /// 'true'. 9441 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 9442 bool Res; 9443 return !E->isValueDependent() && 9444 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 9445 } 9446 9447 /// \brief Returns true if the given expression can be evaluated as a constant 9448 /// 'false'. 9449 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 9450 bool Res; 9451 return !E->isValueDependent() && 9452 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 9453 } 9454 9455 /// \brief Look for '&&' in the left hand of a '||' expr. 9456 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 9457 Expr *LHSExpr, Expr *RHSExpr) { 9458 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 9459 if (Bop->getOpcode() == BO_LAnd) { 9460 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 9461 if (EvaluatesAsFalse(S, RHSExpr)) 9462 return; 9463 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 9464 if (!EvaluatesAsTrue(S, Bop->getLHS())) 9465 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 9466 } else if (Bop->getOpcode() == BO_LOr) { 9467 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 9468 // If it's "a || b && 1 || c" we didn't warn earlier for 9469 // "a || b && 1", but warn now. 9470 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 9471 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 9472 } 9473 } 9474 } 9475 } 9476 9477 /// \brief Look for '&&' in the right hand of a '||' expr. 9478 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 9479 Expr *LHSExpr, Expr *RHSExpr) { 9480 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 9481 if (Bop->getOpcode() == BO_LAnd) { 9482 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 9483 if (EvaluatesAsFalse(S, LHSExpr)) 9484 return; 9485 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 9486 if (!EvaluatesAsTrue(S, Bop->getRHS())) 9487 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 9488 } 9489 } 9490 } 9491 9492 /// \brief Look for '&' in the left or right hand of a '|' expr. 9493 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 9494 Expr *OrArg) { 9495 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 9496 if (Bop->getOpcode() == BO_And) 9497 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 9498 } 9499 } 9500 9501 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 9502 Expr *SubExpr, StringRef Shift) { 9503 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 9504 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 9505 StringRef Op = Bop->getOpcodeStr(); 9506 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 9507 << Bop->getSourceRange() << OpLoc << Shift << Op; 9508 SuggestParentheses(S, Bop->getOperatorLoc(), 9509 S.PDiag(diag::note_precedence_silence) << Op, 9510 Bop->getSourceRange()); 9511 } 9512 } 9513 } 9514 9515 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 9516 Expr *LHSExpr, Expr *RHSExpr) { 9517 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 9518 if (!OCE) 9519 return; 9520 9521 FunctionDecl *FD = OCE->getDirectCallee(); 9522 if (!FD || !FD->isOverloadedOperator()) 9523 return; 9524 9525 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 9526 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 9527 return; 9528 9529 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 9530 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 9531 << (Kind == OO_LessLess); 9532 SuggestParentheses(S, OCE->getOperatorLoc(), 9533 S.PDiag(diag::note_precedence_silence) 9534 << (Kind == OO_LessLess ? "<<" : ">>"), 9535 OCE->getSourceRange()); 9536 SuggestParentheses(S, OpLoc, 9537 S.PDiag(diag::note_evaluate_comparison_first), 9538 SourceRange(OCE->getArg(1)->getLocStart(), 9539 RHSExpr->getLocEnd())); 9540 } 9541 9542 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 9543 /// precedence. 9544 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 9545 SourceLocation OpLoc, Expr *LHSExpr, 9546 Expr *RHSExpr){ 9547 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 9548 if (BinaryOperator::isBitwiseOp(Opc)) 9549 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 9550 9551 // Diagnose "arg1 & arg2 | arg3" 9552 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 9553 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr); 9554 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr); 9555 } 9556 9557 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 9558 // We don't warn for 'assert(a || b && "bad")' since this is safe. 9559 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 9560 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 9561 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 9562 } 9563 9564 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 9565 || Opc == BO_Shr) { 9566 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 9567 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 9568 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 9569 } 9570 9571 // Warn on overloaded shift operators and comparisons, such as: 9572 // cout << 5 == 4; 9573 if (BinaryOperator::isComparisonOp(Opc)) 9574 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 9575 } 9576 9577 // Binary Operators. 'Tok' is the token for the operator. 9578 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 9579 tok::TokenKind Kind, 9580 Expr *LHSExpr, Expr *RHSExpr) { 9581 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 9582 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression"); 9583 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression"); 9584 9585 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 9586 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 9587 9588 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 9589 } 9590 9591 /// Build an overloaded binary operator expression in the given scope. 9592 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 9593 BinaryOperatorKind Opc, 9594 Expr *LHS, Expr *RHS) { 9595 // Find all of the overloaded operators visible from this 9596 // point. We perform both an operator-name lookup from the local 9597 // scope and an argument-dependent lookup based on the types of 9598 // the arguments. 9599 UnresolvedSet<16> Functions; 9600 OverloadedOperatorKind OverOp 9601 = BinaryOperator::getOverloadedOperator(Opc); 9602 if (Sc && OverOp != OO_None) 9603 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 9604 RHS->getType(), Functions); 9605 9606 // Build the (potentially-overloaded, potentially-dependent) 9607 // binary operation. 9608 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 9609 } 9610 9611 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 9612 BinaryOperatorKind Opc, 9613 Expr *LHSExpr, Expr *RHSExpr) { 9614 // We want to end up calling one of checkPseudoObjectAssignment 9615 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 9616 // both expressions are overloadable or either is type-dependent), 9617 // or CreateBuiltinBinOp (in any other case). We also want to get 9618 // any placeholder types out of the way. 9619 9620 // Handle pseudo-objects in the LHS. 9621 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 9622 // Assignments with a pseudo-object l-value need special analysis. 9623 if (pty->getKind() == BuiltinType::PseudoObject && 9624 BinaryOperator::isAssignmentOp(Opc)) 9625 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 9626 9627 // Don't resolve overloads if the other type is overloadable. 9628 if (pty->getKind() == BuiltinType::Overload) { 9629 // We can't actually test that if we still have a placeholder, 9630 // though. Fortunately, none of the exceptions we see in that 9631 // code below are valid when the LHS is an overload set. Note 9632 // that an overload set can be dependently-typed, but it never 9633 // instantiates to having an overloadable type. 9634 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9635 if (resolvedRHS.isInvalid()) return ExprError(); 9636 RHSExpr = resolvedRHS.take(); 9637 9638 if (RHSExpr->isTypeDependent() || 9639 RHSExpr->getType()->isOverloadableType()) 9640 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9641 } 9642 9643 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 9644 if (LHS.isInvalid()) return ExprError(); 9645 LHSExpr = LHS.take(); 9646 } 9647 9648 // Handle pseudo-objects in the RHS. 9649 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 9650 // An overload in the RHS can potentially be resolved by the type 9651 // being assigned to. 9652 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 9653 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9654 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9655 9656 if (LHSExpr->getType()->isOverloadableType()) 9657 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9658 9659 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9660 } 9661 9662 // Don't resolve overloads if the other type is overloadable. 9663 if (pty->getKind() == BuiltinType::Overload && 9664 LHSExpr->getType()->isOverloadableType()) 9665 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9666 9667 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9668 if (!resolvedRHS.isUsable()) return ExprError(); 9669 RHSExpr = resolvedRHS.take(); 9670 } 9671 9672 if (getLangOpts().CPlusPlus) { 9673 // If either expression is type-dependent, always build an 9674 // overloaded op. 9675 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9676 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9677 9678 // Otherwise, build an overloaded op if either expression has an 9679 // overloadable type. 9680 if (LHSExpr->getType()->isOverloadableType() || 9681 RHSExpr->getType()->isOverloadableType()) 9682 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9683 } 9684 9685 // Build a built-in binary operation. 9686 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9687 } 9688 9689 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 9690 UnaryOperatorKind Opc, 9691 Expr *InputExpr) { 9692 ExprResult Input = Owned(InputExpr); 9693 ExprValueKind VK = VK_RValue; 9694 ExprObjectKind OK = OK_Ordinary; 9695 QualType resultType; 9696 switch (Opc) { 9697 case UO_PreInc: 9698 case UO_PreDec: 9699 case UO_PostInc: 9700 case UO_PostDec: 9701 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc, 9702 Opc == UO_PreInc || 9703 Opc == UO_PostInc, 9704 Opc == UO_PreInc || 9705 Opc == UO_PreDec); 9706 break; 9707 case UO_AddrOf: 9708 resultType = CheckAddressOfOperand(Input, OpLoc); 9709 break; 9710 case UO_Deref: { 9711 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 9712 if (Input.isInvalid()) return ExprError(); 9713 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 9714 break; 9715 } 9716 case UO_Plus: 9717 case UO_Minus: 9718 Input = UsualUnaryConversions(Input.take()); 9719 if (Input.isInvalid()) return ExprError(); 9720 resultType = Input.get()->getType(); 9721 if (resultType->isDependentType()) 9722 break; 9723 if (resultType->isArithmeticType() || // C99 6.5.3.3p1 9724 resultType->isVectorType()) 9725 break; 9726 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 9727 Opc == UO_Plus && 9728 resultType->isPointerType()) 9729 break; 9730 9731 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9732 << resultType << Input.get()->getSourceRange()); 9733 9734 case UO_Not: // bitwise complement 9735 Input = UsualUnaryConversions(Input.take()); 9736 if (Input.isInvalid()) 9737 return ExprError(); 9738 resultType = Input.get()->getType(); 9739 if (resultType->isDependentType()) 9740 break; 9741 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 9742 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 9743 // C99 does not support '~' for complex conjugation. 9744 Diag(OpLoc, diag::ext_integer_complement_complex) 9745 << resultType << Input.get()->getSourceRange(); 9746 else if (resultType->hasIntegerRepresentation()) 9747 break; 9748 else if (resultType->isExtVectorType()) { 9749 if (Context.getLangOpts().OpenCL) { 9750 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 9751 // on vector float types. 9752 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9753 if (!T->isIntegerType()) 9754 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9755 << resultType << Input.get()->getSourceRange()); 9756 } 9757 break; 9758 } else { 9759 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9760 << resultType << Input.get()->getSourceRange()); 9761 } 9762 break; 9763 9764 case UO_LNot: // logical negation 9765 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 9766 Input = DefaultFunctionArrayLvalueConversion(Input.take()); 9767 if (Input.isInvalid()) return ExprError(); 9768 resultType = Input.get()->getType(); 9769 9770 // Though we still have to promote half FP to float... 9771 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 9772 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take(); 9773 resultType = Context.FloatTy; 9774 } 9775 9776 if (resultType->isDependentType()) 9777 break; 9778 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 9779 // C99 6.5.3.3p1: ok, fallthrough; 9780 if (Context.getLangOpts().CPlusPlus) { 9781 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 9782 // operand contextually converted to bool. 9783 Input = ImpCastExprToType(Input.take(), Context.BoolTy, 9784 ScalarTypeToBooleanCastKind(resultType)); 9785 } else if (Context.getLangOpts().OpenCL && 9786 Context.getLangOpts().OpenCLVersion < 120) { 9787 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9788 // operate on scalar float types. 9789 if (!resultType->isIntegerType()) 9790 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9791 << resultType << Input.get()->getSourceRange()); 9792 } 9793 } else if (resultType->isExtVectorType()) { 9794 if (Context.getLangOpts().OpenCL && 9795 Context.getLangOpts().OpenCLVersion < 120) { 9796 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9797 // operate on vector float types. 9798 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9799 if (!T->isIntegerType()) 9800 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9801 << resultType << Input.get()->getSourceRange()); 9802 } 9803 // Vector logical not returns the signed variant of the operand type. 9804 resultType = GetSignedVectorType(resultType); 9805 break; 9806 } else { 9807 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9808 << resultType << Input.get()->getSourceRange()); 9809 } 9810 9811 // LNot always has type int. C99 6.5.3.3p5. 9812 // In C++, it's bool. C++ 5.3.1p8 9813 resultType = Context.getLogicalOperationType(); 9814 break; 9815 case UO_Real: 9816 case UO_Imag: 9817 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 9818 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 9819 // complex l-values to ordinary l-values and all other values to r-values. 9820 if (Input.isInvalid()) return ExprError(); 9821 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 9822 if (Input.get()->getValueKind() != VK_RValue && 9823 Input.get()->getObjectKind() == OK_Ordinary) 9824 VK = Input.get()->getValueKind(); 9825 } else if (!getLangOpts().CPlusPlus) { 9826 // In C, a volatile scalar is read by __imag. In C++, it is not. 9827 Input = DefaultLvalueConversion(Input.take()); 9828 } 9829 break; 9830 case UO_Extension: 9831 resultType = Input.get()->getType(); 9832 VK = Input.get()->getValueKind(); 9833 OK = Input.get()->getObjectKind(); 9834 break; 9835 } 9836 if (resultType.isNull() || Input.isInvalid()) 9837 return ExprError(); 9838 9839 // Check for array bounds violations in the operand of the UnaryOperator, 9840 // except for the '*' and '&' operators that have to be handled specially 9841 // by CheckArrayAccess (as there are special cases like &array[arraysize] 9842 // that are explicitly defined as valid by the standard). 9843 if (Opc != UO_AddrOf && Opc != UO_Deref) 9844 CheckArrayAccess(Input.get()); 9845 9846 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType, 9847 VK, OK, OpLoc)); 9848 } 9849 9850 /// \brief Determine whether the given expression is a qualified member 9851 /// access expression, of a form that could be turned into a pointer to member 9852 /// with the address-of operator. 9853 static bool isQualifiedMemberAccess(Expr *E) { 9854 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9855 if (!DRE->getQualifier()) 9856 return false; 9857 9858 ValueDecl *VD = DRE->getDecl(); 9859 if (!VD->isCXXClassMember()) 9860 return false; 9861 9862 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 9863 return true; 9864 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 9865 return Method->isInstance(); 9866 9867 return false; 9868 } 9869 9870 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 9871 if (!ULE->getQualifier()) 9872 return false; 9873 9874 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(), 9875 DEnd = ULE->decls_end(); 9876 D != DEnd; ++D) { 9877 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) { 9878 if (Method->isInstance()) 9879 return true; 9880 } else { 9881 // Overload set does not contain methods. 9882 break; 9883 } 9884 } 9885 9886 return false; 9887 } 9888 9889 return false; 9890 } 9891 9892 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 9893 UnaryOperatorKind Opc, Expr *Input) { 9894 // First things first: handle placeholders so that the 9895 // overloaded-operator check considers the right type. 9896 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 9897 // Increment and decrement of pseudo-object references. 9898 if (pty->getKind() == BuiltinType::PseudoObject && 9899 UnaryOperator::isIncrementDecrementOp(Opc)) 9900 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 9901 9902 // extension is always a builtin operator. 9903 if (Opc == UO_Extension) 9904 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9905 9906 // & gets special logic for several kinds of placeholder. 9907 // The builtin code knows what to do. 9908 if (Opc == UO_AddrOf && 9909 (pty->getKind() == BuiltinType::Overload || 9910 pty->getKind() == BuiltinType::UnknownAny || 9911 pty->getKind() == BuiltinType::BoundMember)) 9912 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9913 9914 // Anything else needs to be handled now. 9915 ExprResult Result = CheckPlaceholderExpr(Input); 9916 if (Result.isInvalid()) return ExprError(); 9917 Input = Result.take(); 9918 } 9919 9920 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 9921 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 9922 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 9923 // Find all of the overloaded operators visible from this 9924 // point. We perform both an operator-name lookup from the local 9925 // scope and an argument-dependent lookup based on the types of 9926 // the arguments. 9927 UnresolvedSet<16> Functions; 9928 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 9929 if (S && OverOp != OO_None) 9930 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 9931 Functions); 9932 9933 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 9934 } 9935 9936 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 9937 } 9938 9939 // Unary Operators. 'Tok' is the token for the operator. 9940 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 9941 tok::TokenKind Op, Expr *Input) { 9942 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 9943 } 9944 9945 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 9946 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 9947 LabelDecl *TheDecl) { 9948 TheDecl->markUsed(Context); 9949 // Create the AST node. The address of a label always has type 'void*'. 9950 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 9951 Context.getPointerType(Context.VoidTy))); 9952 } 9953 9954 /// Given the last statement in a statement-expression, check whether 9955 /// the result is a producing expression (like a call to an 9956 /// ns_returns_retained function) and, if so, rebuild it to hoist the 9957 /// release out of the full-expression. Otherwise, return null. 9958 /// Cannot fail. 9959 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 9960 // Should always be wrapped with one of these. 9961 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 9962 if (!cleanups) return 0; 9963 9964 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 9965 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 9966 return 0; 9967 9968 // Splice out the cast. This shouldn't modify any interesting 9969 // features of the statement. 9970 Expr *producer = cast->getSubExpr(); 9971 assert(producer->getType() == cast->getType()); 9972 assert(producer->getValueKind() == cast->getValueKind()); 9973 cleanups->setSubExpr(producer); 9974 return cleanups; 9975 } 9976 9977 void Sema::ActOnStartStmtExpr() { 9978 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 9979 } 9980 9981 void Sema::ActOnStmtExprError() { 9982 // Note that function is also called by TreeTransform when leaving a 9983 // StmtExpr scope without rebuilding anything. 9984 9985 DiscardCleanupsInEvaluationContext(); 9986 PopExpressionEvaluationContext(); 9987 } 9988 9989 ExprResult 9990 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 9991 SourceLocation RPLoc) { // "({..})" 9992 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 9993 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 9994 9995 if (hasAnyUnrecoverableErrorsInThisFunction()) 9996 DiscardCleanupsInEvaluationContext(); 9997 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 9998 PopExpressionEvaluationContext(); 9999 10000 bool isFileScope 10001 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0); 10002 if (isFileScope) 10003 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 10004 10005 // FIXME: there are a variety of strange constraints to enforce here, for 10006 // example, it is not possible to goto into a stmt expression apparently. 10007 // More semantic analysis is needed. 10008 10009 // If there are sub-stmts in the compound stmt, take the type of the last one 10010 // as the type of the stmtexpr. 10011 QualType Ty = Context.VoidTy; 10012 bool StmtExprMayBindToTemp = false; 10013 if (!Compound->body_empty()) { 10014 Stmt *LastStmt = Compound->body_back(); 10015 LabelStmt *LastLabelStmt = 0; 10016 // If LastStmt is a label, skip down through into the body. 10017 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 10018 LastLabelStmt = Label; 10019 LastStmt = Label->getSubStmt(); 10020 } 10021 10022 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 10023 // Do function/array conversion on the last expression, but not 10024 // lvalue-to-rvalue. However, initialize an unqualified type. 10025 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 10026 if (LastExpr.isInvalid()) 10027 return ExprError(); 10028 Ty = LastExpr.get()->getType().getUnqualifiedType(); 10029 10030 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 10031 // In ARC, if the final expression ends in a consume, splice 10032 // the consume out and bind it later. In the alternate case 10033 // (when dealing with a retainable type), the result 10034 // initialization will create a produce. In both cases the 10035 // result will be +1, and we'll need to balance that out with 10036 // a bind. 10037 if (Expr *rebuiltLastStmt 10038 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 10039 LastExpr = rebuiltLastStmt; 10040 } else { 10041 LastExpr = PerformCopyInitialization( 10042 InitializedEntity::InitializeResult(LPLoc, 10043 Ty, 10044 false), 10045 SourceLocation(), 10046 LastExpr); 10047 } 10048 10049 if (LastExpr.isInvalid()) 10050 return ExprError(); 10051 if (LastExpr.get() != 0) { 10052 if (!LastLabelStmt) 10053 Compound->setLastStmt(LastExpr.take()); 10054 else 10055 LastLabelStmt->setSubStmt(LastExpr.take()); 10056 StmtExprMayBindToTemp = true; 10057 } 10058 } 10059 } 10060 } 10061 10062 // FIXME: Check that expression type is complete/non-abstract; statement 10063 // expressions are not lvalues. 10064 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 10065 if (StmtExprMayBindToTemp) 10066 return MaybeBindToTemporary(ResStmtExpr); 10067 return Owned(ResStmtExpr); 10068 } 10069 10070 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 10071 TypeSourceInfo *TInfo, 10072 OffsetOfComponent *CompPtr, 10073 unsigned NumComponents, 10074 SourceLocation RParenLoc) { 10075 QualType ArgTy = TInfo->getType(); 10076 bool Dependent = ArgTy->isDependentType(); 10077 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 10078 10079 // We must have at least one component that refers to the type, and the first 10080 // one is known to be a field designator. Verify that the ArgTy represents 10081 // a struct/union/class. 10082 if (!Dependent && !ArgTy->isRecordType()) 10083 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 10084 << ArgTy << TypeRange); 10085 10086 // Type must be complete per C99 7.17p3 because a declaring a variable 10087 // with an incomplete type would be ill-formed. 10088 if (!Dependent 10089 && RequireCompleteType(BuiltinLoc, ArgTy, 10090 diag::err_offsetof_incomplete_type, TypeRange)) 10091 return ExprError(); 10092 10093 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 10094 // GCC extension, diagnose them. 10095 // FIXME: This diagnostic isn't actually visible because the location is in 10096 // a system header! 10097 if (NumComponents != 1) 10098 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 10099 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 10100 10101 bool DidWarnAboutNonPOD = false; 10102 QualType CurrentType = ArgTy; 10103 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 10104 SmallVector<OffsetOfNode, 4> Comps; 10105 SmallVector<Expr*, 4> Exprs; 10106 for (unsigned i = 0; i != NumComponents; ++i) { 10107 const OffsetOfComponent &OC = CompPtr[i]; 10108 if (OC.isBrackets) { 10109 // Offset of an array sub-field. TODO: Should we allow vector elements? 10110 if (!CurrentType->isDependentType()) { 10111 const ArrayType *AT = Context.getAsArrayType(CurrentType); 10112 if(!AT) 10113 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 10114 << CurrentType); 10115 CurrentType = AT->getElementType(); 10116 } else 10117 CurrentType = Context.DependentTy; 10118 10119 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 10120 if (IdxRval.isInvalid()) 10121 return ExprError(); 10122 Expr *Idx = IdxRval.take(); 10123 10124 // The expression must be an integral expression. 10125 // FIXME: An integral constant expression? 10126 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 10127 !Idx->getType()->isIntegerType()) 10128 return ExprError(Diag(Idx->getLocStart(), 10129 diag::err_typecheck_subscript_not_integer) 10130 << Idx->getSourceRange()); 10131 10132 // Record this array index. 10133 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 10134 Exprs.push_back(Idx); 10135 continue; 10136 } 10137 10138 // Offset of a field. 10139 if (CurrentType->isDependentType()) { 10140 // We have the offset of a field, but we can't look into the dependent 10141 // type. Just record the identifier of the field. 10142 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 10143 CurrentType = Context.DependentTy; 10144 continue; 10145 } 10146 10147 // We need to have a complete type to look into. 10148 if (RequireCompleteType(OC.LocStart, CurrentType, 10149 diag::err_offsetof_incomplete_type)) 10150 return ExprError(); 10151 10152 // Look for the designated field. 10153 const RecordType *RC = CurrentType->getAs<RecordType>(); 10154 if (!RC) 10155 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 10156 << CurrentType); 10157 RecordDecl *RD = RC->getDecl(); 10158 10159 // C++ [lib.support.types]p5: 10160 // The macro offsetof accepts a restricted set of type arguments in this 10161 // International Standard. type shall be a POD structure or a POD union 10162 // (clause 9). 10163 // C++11 [support.types]p4: 10164 // If type is not a standard-layout class (Clause 9), the results are 10165 // undefined. 10166 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 10167 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 10168 unsigned DiagID = 10169 LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type 10170 : diag::warn_offsetof_non_pod_type; 10171 10172 if (!IsSafe && !DidWarnAboutNonPOD && 10173 DiagRuntimeBehavior(BuiltinLoc, 0, 10174 PDiag(DiagID) 10175 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 10176 << CurrentType)) 10177 DidWarnAboutNonPOD = true; 10178 } 10179 10180 // Look for the field. 10181 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 10182 LookupQualifiedName(R, RD); 10183 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 10184 IndirectFieldDecl *IndirectMemberDecl = 0; 10185 if (!MemberDecl) { 10186 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 10187 MemberDecl = IndirectMemberDecl->getAnonField(); 10188 } 10189 10190 if (!MemberDecl) 10191 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 10192 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 10193 OC.LocEnd)); 10194 10195 // C99 7.17p3: 10196 // (If the specified member is a bit-field, the behavior is undefined.) 10197 // 10198 // We diagnose this as an error. 10199 if (MemberDecl->isBitField()) { 10200 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 10201 << MemberDecl->getDeclName() 10202 << SourceRange(BuiltinLoc, RParenLoc); 10203 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 10204 return ExprError(); 10205 } 10206 10207 RecordDecl *Parent = MemberDecl->getParent(); 10208 if (IndirectMemberDecl) 10209 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 10210 10211 // If the member was found in a base class, introduce OffsetOfNodes for 10212 // the base class indirections. 10213 CXXBasePaths Paths; 10214 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 10215 if (Paths.getDetectedVirtual()) { 10216 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 10217 << MemberDecl->getDeclName() 10218 << SourceRange(BuiltinLoc, RParenLoc); 10219 return ExprError(); 10220 } 10221 10222 CXXBasePath &Path = Paths.front(); 10223 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 10224 B != BEnd; ++B) 10225 Comps.push_back(OffsetOfNode(B->Base)); 10226 } 10227 10228 if (IndirectMemberDecl) { 10229 for (auto *FI : IndirectMemberDecl->chain()) { 10230 assert(isa<FieldDecl>(FI)); 10231 Comps.push_back(OffsetOfNode(OC.LocStart, 10232 cast<FieldDecl>(FI), OC.LocEnd)); 10233 } 10234 } else 10235 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 10236 10237 CurrentType = MemberDecl->getType().getNonReferenceType(); 10238 } 10239 10240 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 10241 TInfo, Comps, Exprs, RParenLoc)); 10242 } 10243 10244 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 10245 SourceLocation BuiltinLoc, 10246 SourceLocation TypeLoc, 10247 ParsedType ParsedArgTy, 10248 OffsetOfComponent *CompPtr, 10249 unsigned NumComponents, 10250 SourceLocation RParenLoc) { 10251 10252 TypeSourceInfo *ArgTInfo; 10253 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 10254 if (ArgTy.isNull()) 10255 return ExprError(); 10256 10257 if (!ArgTInfo) 10258 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 10259 10260 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 10261 RParenLoc); 10262 } 10263 10264 10265 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 10266 Expr *CondExpr, 10267 Expr *LHSExpr, Expr *RHSExpr, 10268 SourceLocation RPLoc) { 10269 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 10270 10271 ExprValueKind VK = VK_RValue; 10272 ExprObjectKind OK = OK_Ordinary; 10273 QualType resType; 10274 bool ValueDependent = false; 10275 bool CondIsTrue = false; 10276 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 10277 resType = Context.DependentTy; 10278 ValueDependent = true; 10279 } else { 10280 // The conditional expression is required to be a constant expression. 10281 llvm::APSInt condEval(32); 10282 ExprResult CondICE 10283 = VerifyIntegerConstantExpression(CondExpr, &condEval, 10284 diag::err_typecheck_choose_expr_requires_constant, false); 10285 if (CondICE.isInvalid()) 10286 return ExprError(); 10287 CondExpr = CondICE.take(); 10288 CondIsTrue = condEval.getZExtValue(); 10289 10290 // If the condition is > zero, then the AST type is the same as the LSHExpr. 10291 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 10292 10293 resType = ActiveExpr->getType(); 10294 ValueDependent = ActiveExpr->isValueDependent(); 10295 VK = ActiveExpr->getValueKind(); 10296 OK = ActiveExpr->getObjectKind(); 10297 } 10298 10299 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 10300 resType, VK, OK, RPLoc, CondIsTrue, 10301 resType->isDependentType(), 10302 ValueDependent)); 10303 } 10304 10305 //===----------------------------------------------------------------------===// 10306 // Clang Extensions. 10307 //===----------------------------------------------------------------------===// 10308 10309 /// ActOnBlockStart - This callback is invoked when a block literal is started. 10310 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 10311 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 10312 10313 if (LangOpts.CPlusPlus) { 10314 Decl *ManglingContextDecl; 10315 if (MangleNumberingContext *MCtx = 10316 getCurrentMangleNumberContext(Block->getDeclContext(), 10317 ManglingContextDecl)) { 10318 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 10319 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 10320 } 10321 } 10322 10323 PushBlockScope(CurScope, Block); 10324 CurContext->addDecl(Block); 10325 if (CurScope) 10326 PushDeclContext(CurScope, Block); 10327 else 10328 CurContext = Block; 10329 10330 getCurBlock()->HasImplicitReturnType = true; 10331 10332 // Enter a new evaluation context to insulate the block from any 10333 // cleanups from the enclosing full-expression. 10334 PushExpressionEvaluationContext(PotentiallyEvaluated); 10335 } 10336 10337 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 10338 Scope *CurScope) { 10339 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!"); 10340 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 10341 BlockScopeInfo *CurBlock = getCurBlock(); 10342 10343 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 10344 QualType T = Sig->getType(); 10345 10346 // FIXME: We should allow unexpanded parameter packs here, but that would, 10347 // in turn, make the block expression contain unexpanded parameter packs. 10348 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 10349 // Drop the parameters. 10350 FunctionProtoType::ExtProtoInfo EPI; 10351 EPI.HasTrailingReturn = false; 10352 EPI.TypeQuals |= DeclSpec::TQ_const; 10353 T = Context.getFunctionType(Context.DependentTy, None, EPI); 10354 Sig = Context.getTrivialTypeSourceInfo(T); 10355 } 10356 10357 // GetTypeForDeclarator always produces a function type for a block 10358 // literal signature. Furthermore, it is always a FunctionProtoType 10359 // unless the function was written with a typedef. 10360 assert(T->isFunctionType() && 10361 "GetTypeForDeclarator made a non-function block signature"); 10362 10363 // Look for an explicit signature in that function type. 10364 FunctionProtoTypeLoc ExplicitSignature; 10365 10366 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 10367 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 10368 10369 // Check whether that explicit signature was synthesized by 10370 // GetTypeForDeclarator. If so, don't save that as part of the 10371 // written signature. 10372 if (ExplicitSignature.getLocalRangeBegin() == 10373 ExplicitSignature.getLocalRangeEnd()) { 10374 // This would be much cheaper if we stored TypeLocs instead of 10375 // TypeSourceInfos. 10376 TypeLoc Result = ExplicitSignature.getReturnLoc(); 10377 unsigned Size = Result.getFullDataSize(); 10378 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 10379 Sig->getTypeLoc().initializeFullCopy(Result, Size); 10380 10381 ExplicitSignature = FunctionProtoTypeLoc(); 10382 } 10383 } 10384 10385 CurBlock->TheDecl->setSignatureAsWritten(Sig); 10386 CurBlock->FunctionType = T; 10387 10388 const FunctionType *Fn = T->getAs<FunctionType>(); 10389 QualType RetTy = Fn->getReturnType(); 10390 bool isVariadic = 10391 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 10392 10393 CurBlock->TheDecl->setIsVariadic(isVariadic); 10394 10395 // Context.DependentTy is used as a placeholder for a missing block 10396 // return type. TODO: what should we do with declarators like: 10397 // ^ * { ... } 10398 // If the answer is "apply template argument deduction".... 10399 if (RetTy != Context.DependentTy) { 10400 CurBlock->ReturnType = RetTy; 10401 CurBlock->TheDecl->setBlockMissingReturnType(false); 10402 CurBlock->HasImplicitReturnType = false; 10403 } 10404 10405 // Push block parameters from the declarator if we had them. 10406 SmallVector<ParmVarDecl*, 8> Params; 10407 if (ExplicitSignature) { 10408 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 10409 ParmVarDecl *Param = ExplicitSignature.getParam(I); 10410 if (Param->getIdentifier() == 0 && 10411 !Param->isImplicit() && 10412 !Param->isInvalidDecl() && 10413 !getLangOpts().CPlusPlus) 10414 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 10415 Params.push_back(Param); 10416 } 10417 10418 // Fake up parameter variables if we have a typedef, like 10419 // ^ fntype { ... } 10420 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 10421 for (const auto &I : Fn->param_types()) { 10422 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 10423 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 10424 Params.push_back(Param); 10425 } 10426 } 10427 10428 // Set the parameters on the block decl. 10429 if (!Params.empty()) { 10430 CurBlock->TheDecl->setParams(Params); 10431 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 10432 CurBlock->TheDecl->param_end(), 10433 /*CheckParameterNames=*/false); 10434 } 10435 10436 // Finally we can process decl attributes. 10437 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 10438 10439 // Put the parameter variables in scope. 10440 for (auto AI : CurBlock->TheDecl->params()) { 10441 AI->setOwningFunction(CurBlock->TheDecl); 10442 10443 // If this has an identifier, add it to the scope stack. 10444 if (AI->getIdentifier()) { 10445 CheckShadow(CurBlock->TheScope, AI); 10446 10447 PushOnScopeChains(AI, CurBlock->TheScope); 10448 } 10449 } 10450 } 10451 10452 /// ActOnBlockError - If there is an error parsing a block, this callback 10453 /// is invoked to pop the information about the block from the action impl. 10454 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 10455 // Leave the expression-evaluation context. 10456 DiscardCleanupsInEvaluationContext(); 10457 PopExpressionEvaluationContext(); 10458 10459 // Pop off CurBlock, handle nested blocks. 10460 PopDeclContext(); 10461 PopFunctionScopeInfo(); 10462 } 10463 10464 /// ActOnBlockStmtExpr - This is called when the body of a block statement 10465 /// literal was successfully completed. ^(int x){...} 10466 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 10467 Stmt *Body, Scope *CurScope) { 10468 // If blocks are disabled, emit an error. 10469 if (!LangOpts.Blocks) 10470 Diag(CaretLoc, diag::err_blocks_disable); 10471 10472 // Leave the expression-evaluation context. 10473 if (hasAnyUnrecoverableErrorsInThisFunction()) 10474 DiscardCleanupsInEvaluationContext(); 10475 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 10476 PopExpressionEvaluationContext(); 10477 10478 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 10479 10480 if (BSI->HasImplicitReturnType) 10481 deduceClosureReturnType(*BSI); 10482 10483 PopDeclContext(); 10484 10485 QualType RetTy = Context.VoidTy; 10486 if (!BSI->ReturnType.isNull()) 10487 RetTy = BSI->ReturnType; 10488 10489 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 10490 QualType BlockTy; 10491 10492 // Set the captured variables on the block. 10493 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 10494 SmallVector<BlockDecl::Capture, 4> Captures; 10495 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) { 10496 CapturingScopeInfo::Capture &Cap = BSI->Captures[i]; 10497 if (Cap.isThisCapture()) 10498 continue; 10499 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 10500 Cap.isNested(), Cap.getInitExpr()); 10501 Captures.push_back(NewCap); 10502 } 10503 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(), 10504 BSI->CXXThisCaptureIndex != 0); 10505 10506 // If the user wrote a function type in some form, try to use that. 10507 if (!BSI->FunctionType.isNull()) { 10508 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 10509 10510 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 10511 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 10512 10513 // Turn protoless block types into nullary block types. 10514 if (isa<FunctionNoProtoType>(FTy)) { 10515 FunctionProtoType::ExtProtoInfo EPI; 10516 EPI.ExtInfo = Ext; 10517 BlockTy = Context.getFunctionType(RetTy, None, EPI); 10518 10519 // Otherwise, if we don't need to change anything about the function type, 10520 // preserve its sugar structure. 10521 } else if (FTy->getReturnType() == RetTy && 10522 (!NoReturn || FTy->getNoReturnAttr())) { 10523 BlockTy = BSI->FunctionType; 10524 10525 // Otherwise, make the minimal modifications to the function type. 10526 } else { 10527 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 10528 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10529 EPI.TypeQuals = 0; // FIXME: silently? 10530 EPI.ExtInfo = Ext; 10531 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 10532 } 10533 10534 // If we don't have a function type, just build one from nothing. 10535 } else { 10536 FunctionProtoType::ExtProtoInfo EPI; 10537 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 10538 BlockTy = Context.getFunctionType(RetTy, None, EPI); 10539 } 10540 10541 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 10542 BSI->TheDecl->param_end()); 10543 BlockTy = Context.getBlockPointerType(BlockTy); 10544 10545 // If needed, diagnose invalid gotos and switches in the block. 10546 if (getCurFunction()->NeedsScopeChecking() && 10547 !hasAnyUnrecoverableErrorsInThisFunction() && 10548 !PP.isCodeCompletionEnabled()) 10549 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 10550 10551 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 10552 10553 // Try to apply the named return value optimization. We have to check again 10554 // if we can do this, though, because blocks keep return statements around 10555 // to deduce an implicit return type. 10556 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 10557 !BSI->TheDecl->isDependentContext()) 10558 computeNRVO(Body, getCurBlock()); 10559 10560 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 10561 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 10562 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 10563 10564 // If the block isn't obviously global, i.e. it captures anything at 10565 // all, then we need to do a few things in the surrounding context: 10566 if (Result->getBlockDecl()->hasCaptures()) { 10567 // First, this expression has a new cleanup object. 10568 ExprCleanupObjects.push_back(Result->getBlockDecl()); 10569 ExprNeedsCleanups = true; 10570 10571 // It also gets a branch-protected scope if any of the captured 10572 // variables needs destruction. 10573 for (const auto &CI : Result->getBlockDecl()->captures()) { 10574 const VarDecl *var = CI.getVariable(); 10575 if (var->getType().isDestructedType() != QualType::DK_none) { 10576 getCurFunction()->setHasBranchProtectedScope(); 10577 break; 10578 } 10579 } 10580 } 10581 10582 return Owned(Result); 10583 } 10584 10585 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 10586 Expr *E, ParsedType Ty, 10587 SourceLocation RPLoc) { 10588 TypeSourceInfo *TInfo; 10589 GetTypeFromParser(Ty, &TInfo); 10590 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 10591 } 10592 10593 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 10594 Expr *E, TypeSourceInfo *TInfo, 10595 SourceLocation RPLoc) { 10596 Expr *OrigExpr = E; 10597 10598 // Get the va_list type 10599 QualType VaListType = Context.getBuiltinVaListType(); 10600 if (VaListType->isArrayType()) { 10601 // Deal with implicit array decay; for example, on x86-64, 10602 // va_list is an array, but it's supposed to decay to 10603 // a pointer for va_arg. 10604 VaListType = Context.getArrayDecayedType(VaListType); 10605 // Make sure the input expression also decays appropriately. 10606 ExprResult Result = UsualUnaryConversions(E); 10607 if (Result.isInvalid()) 10608 return ExprError(); 10609 E = Result.take(); 10610 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 10611 // If va_list is a record type and we are compiling in C++ mode, 10612 // check the argument using reference binding. 10613 InitializedEntity Entity 10614 = InitializedEntity::InitializeParameter(Context, 10615 Context.getLValueReferenceType(VaListType), false); 10616 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 10617 if (Init.isInvalid()) 10618 return ExprError(); 10619 E = Init.takeAs<Expr>(); 10620 } else { 10621 // Otherwise, the va_list argument must be an l-value because 10622 // it is modified by va_arg. 10623 if (!E->isTypeDependent() && 10624 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 10625 return ExprError(); 10626 } 10627 10628 if (!E->isTypeDependent() && 10629 !Context.hasSameType(VaListType, E->getType())) { 10630 return ExprError(Diag(E->getLocStart(), 10631 diag::err_first_argument_to_va_arg_not_of_type_va_list) 10632 << OrigExpr->getType() << E->getSourceRange()); 10633 } 10634 10635 if (!TInfo->getType()->isDependentType()) { 10636 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 10637 diag::err_second_parameter_to_va_arg_incomplete, 10638 TInfo->getTypeLoc())) 10639 return ExprError(); 10640 10641 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 10642 TInfo->getType(), 10643 diag::err_second_parameter_to_va_arg_abstract, 10644 TInfo->getTypeLoc())) 10645 return ExprError(); 10646 10647 if (!TInfo->getType().isPODType(Context)) { 10648 Diag(TInfo->getTypeLoc().getBeginLoc(), 10649 TInfo->getType()->isObjCLifetimeType() 10650 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 10651 : diag::warn_second_parameter_to_va_arg_not_pod) 10652 << TInfo->getType() 10653 << TInfo->getTypeLoc().getSourceRange(); 10654 } 10655 10656 // Check for va_arg where arguments of the given type will be promoted 10657 // (i.e. this va_arg is guaranteed to have undefined behavior). 10658 QualType PromoteType; 10659 if (TInfo->getType()->isPromotableIntegerType()) { 10660 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 10661 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 10662 PromoteType = QualType(); 10663 } 10664 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 10665 PromoteType = Context.DoubleTy; 10666 if (!PromoteType.isNull()) 10667 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 10668 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 10669 << TInfo->getType() 10670 << PromoteType 10671 << TInfo->getTypeLoc().getSourceRange()); 10672 } 10673 10674 QualType T = TInfo->getType().getNonLValueExprType(Context); 10675 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T)); 10676 } 10677 10678 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 10679 // The type of __null will be int or long, depending on the size of 10680 // pointers on the target. 10681 QualType Ty; 10682 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 10683 if (pw == Context.getTargetInfo().getIntWidth()) 10684 Ty = Context.IntTy; 10685 else if (pw == Context.getTargetInfo().getLongWidth()) 10686 Ty = Context.LongTy; 10687 else if (pw == Context.getTargetInfo().getLongLongWidth()) 10688 Ty = Context.LongLongTy; 10689 else { 10690 llvm_unreachable("I don't know size of pointer!"); 10691 } 10692 10693 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc)); 10694 } 10695 10696 bool 10697 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) { 10698 if (!getLangOpts().ObjC1) 10699 return false; 10700 10701 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 10702 if (!PT) 10703 return false; 10704 10705 if (!PT->isObjCIdType()) { 10706 // Check if the destination is the 'NSString' interface. 10707 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 10708 if (!ID || !ID->getIdentifier()->isStr("NSString")) 10709 return false; 10710 } 10711 10712 // Ignore any parens, implicit casts (should only be 10713 // array-to-pointer decays), and not-so-opaque values. The last is 10714 // important for making this trigger for property assignments. 10715 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 10716 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 10717 if (OV->getSourceExpr()) 10718 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 10719 10720 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 10721 if (!SL || !SL->isAscii()) 10722 return false; 10723 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 10724 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 10725 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).take(); 10726 return true; 10727 } 10728 10729 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 10730 SourceLocation Loc, 10731 QualType DstType, QualType SrcType, 10732 Expr *SrcExpr, AssignmentAction Action, 10733 bool *Complained) { 10734 if (Complained) 10735 *Complained = false; 10736 10737 // Decode the result (notice that AST's are still created for extensions). 10738 bool CheckInferredResultType = false; 10739 bool isInvalid = false; 10740 unsigned DiagKind = 0; 10741 FixItHint Hint; 10742 ConversionFixItGenerator ConvHints; 10743 bool MayHaveConvFixit = false; 10744 bool MayHaveFunctionDiff = false; 10745 10746 switch (ConvTy) { 10747 case Compatible: 10748 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 10749 return false; 10750 10751 case PointerToInt: 10752 DiagKind = diag::ext_typecheck_convert_pointer_int; 10753 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10754 MayHaveConvFixit = true; 10755 break; 10756 case IntToPointer: 10757 DiagKind = diag::ext_typecheck_convert_int_pointer; 10758 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10759 MayHaveConvFixit = true; 10760 break; 10761 case IncompatiblePointer: 10762 DiagKind = 10763 (Action == AA_Passing_CFAudited ? 10764 diag::err_arc_typecheck_convert_incompatible_pointer : 10765 diag::ext_typecheck_convert_incompatible_pointer); 10766 CheckInferredResultType = DstType->isObjCObjectPointerType() && 10767 SrcType->isObjCObjectPointerType(); 10768 if (Hint.isNull() && !CheckInferredResultType) { 10769 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10770 } 10771 else if (CheckInferredResultType) { 10772 SrcType = SrcType.getUnqualifiedType(); 10773 DstType = DstType.getUnqualifiedType(); 10774 } 10775 MayHaveConvFixit = true; 10776 break; 10777 case IncompatiblePointerSign: 10778 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 10779 break; 10780 case FunctionVoidPointer: 10781 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 10782 break; 10783 case IncompatiblePointerDiscardsQualifiers: { 10784 // Perform array-to-pointer decay if necessary. 10785 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 10786 10787 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 10788 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 10789 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 10790 DiagKind = diag::err_typecheck_incompatible_address_space; 10791 break; 10792 10793 10794 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 10795 DiagKind = diag::err_typecheck_incompatible_ownership; 10796 break; 10797 } 10798 10799 llvm_unreachable("unknown error case for discarding qualifiers!"); 10800 // fallthrough 10801 } 10802 case CompatiblePointerDiscardsQualifiers: 10803 // If the qualifiers lost were because we were applying the 10804 // (deprecated) C++ conversion from a string literal to a char* 10805 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 10806 // Ideally, this check would be performed in 10807 // checkPointerTypesForAssignment. However, that would require a 10808 // bit of refactoring (so that the second argument is an 10809 // expression, rather than a type), which should be done as part 10810 // of a larger effort to fix checkPointerTypesForAssignment for 10811 // C++ semantics. 10812 if (getLangOpts().CPlusPlus && 10813 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 10814 return false; 10815 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 10816 break; 10817 case IncompatibleNestedPointerQualifiers: 10818 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 10819 break; 10820 case IntToBlockPointer: 10821 DiagKind = diag::err_int_to_block_pointer; 10822 break; 10823 case IncompatibleBlockPointer: 10824 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 10825 break; 10826 case IncompatibleObjCQualifiedId: 10827 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since 10828 // it can give a more specific diagnostic. 10829 DiagKind = diag::warn_incompatible_qualified_id; 10830 break; 10831 case IncompatibleVectors: 10832 DiagKind = diag::warn_incompatible_vectors; 10833 break; 10834 case IncompatibleObjCWeakRef: 10835 DiagKind = diag::err_arc_weak_unavailable_assign; 10836 break; 10837 case Incompatible: 10838 DiagKind = diag::err_typecheck_convert_incompatible; 10839 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10840 MayHaveConvFixit = true; 10841 isInvalid = true; 10842 MayHaveFunctionDiff = true; 10843 break; 10844 } 10845 10846 QualType FirstType, SecondType; 10847 switch (Action) { 10848 case AA_Assigning: 10849 case AA_Initializing: 10850 // The destination type comes first. 10851 FirstType = DstType; 10852 SecondType = SrcType; 10853 break; 10854 10855 case AA_Returning: 10856 case AA_Passing: 10857 case AA_Passing_CFAudited: 10858 case AA_Converting: 10859 case AA_Sending: 10860 case AA_Casting: 10861 // The source type comes first. 10862 FirstType = SrcType; 10863 SecondType = DstType; 10864 break; 10865 } 10866 10867 PartialDiagnostic FDiag = PDiag(DiagKind); 10868 if (Action == AA_Passing_CFAudited) 10869 FDiag << FirstType << SecondType << SrcExpr->getSourceRange(); 10870 else 10871 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 10872 10873 // If we can fix the conversion, suggest the FixIts. 10874 assert(ConvHints.isNull() || Hint.isNull()); 10875 if (!ConvHints.isNull()) { 10876 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(), 10877 HE = ConvHints.Hints.end(); HI != HE; ++HI) 10878 FDiag << *HI; 10879 } else { 10880 FDiag << Hint; 10881 } 10882 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 10883 10884 if (MayHaveFunctionDiff) 10885 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 10886 10887 Diag(Loc, FDiag); 10888 10889 if (SecondType == Context.OverloadTy) 10890 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 10891 FirstType); 10892 10893 if (CheckInferredResultType) 10894 EmitRelatedResultTypeNote(SrcExpr); 10895 10896 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 10897 EmitRelatedResultTypeNoteForReturn(DstType); 10898 10899 if (Complained) 10900 *Complained = true; 10901 return isInvalid; 10902 } 10903 10904 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 10905 llvm::APSInt *Result) { 10906 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 10907 public: 10908 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 10909 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 10910 } 10911 } Diagnoser; 10912 10913 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 10914 } 10915 10916 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 10917 llvm::APSInt *Result, 10918 unsigned DiagID, 10919 bool AllowFold) { 10920 class IDDiagnoser : public VerifyICEDiagnoser { 10921 unsigned DiagID; 10922 10923 public: 10924 IDDiagnoser(unsigned DiagID) 10925 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 10926 10927 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 10928 S.Diag(Loc, DiagID) << SR; 10929 } 10930 } Diagnoser(DiagID); 10931 10932 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 10933 } 10934 10935 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 10936 SourceRange SR) { 10937 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 10938 } 10939 10940 ExprResult 10941 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 10942 VerifyICEDiagnoser &Diagnoser, 10943 bool AllowFold) { 10944 SourceLocation DiagLoc = E->getLocStart(); 10945 10946 if (getLangOpts().CPlusPlus11) { 10947 // C++11 [expr.const]p5: 10948 // If an expression of literal class type is used in a context where an 10949 // integral constant expression is required, then that class type shall 10950 // have a single non-explicit conversion function to an integral or 10951 // unscoped enumeration type 10952 ExprResult Converted; 10953 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 10954 public: 10955 CXX11ConvertDiagnoser(bool Silent) 10956 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 10957 Silent, true) {} 10958 10959 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 10960 QualType T) override { 10961 return S.Diag(Loc, diag::err_ice_not_integral) << T; 10962 } 10963 10964 SemaDiagnosticBuilder diagnoseIncomplete( 10965 Sema &S, SourceLocation Loc, QualType T) override { 10966 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 10967 } 10968 10969 SemaDiagnosticBuilder diagnoseExplicitConv( 10970 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 10971 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 10972 } 10973 10974 SemaDiagnosticBuilder noteExplicitConv( 10975 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 10976 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10977 << ConvTy->isEnumeralType() << ConvTy; 10978 } 10979 10980 SemaDiagnosticBuilder diagnoseAmbiguous( 10981 Sema &S, SourceLocation Loc, QualType T) override { 10982 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 10983 } 10984 10985 SemaDiagnosticBuilder noteAmbiguous( 10986 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 10987 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 10988 << ConvTy->isEnumeralType() << ConvTy; 10989 } 10990 10991 SemaDiagnosticBuilder diagnoseConversion( 10992 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 10993 llvm_unreachable("conversion functions are permitted"); 10994 } 10995 } ConvertDiagnoser(Diagnoser.Suppress); 10996 10997 Converted = PerformContextualImplicitConversion(DiagLoc, E, 10998 ConvertDiagnoser); 10999 if (Converted.isInvalid()) 11000 return Converted; 11001 E = Converted.take(); 11002 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 11003 return ExprError(); 11004 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 11005 // An ICE must be of integral or unscoped enumeration type. 11006 if (!Diagnoser.Suppress) 11007 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 11008 return ExprError(); 11009 } 11010 11011 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 11012 // in the non-ICE case. 11013 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 11014 if (Result) 11015 *Result = E->EvaluateKnownConstInt(Context); 11016 return Owned(E); 11017 } 11018 11019 Expr::EvalResult EvalResult; 11020 SmallVector<PartialDiagnosticAt, 8> Notes; 11021 EvalResult.Diag = &Notes; 11022 11023 // Try to evaluate the expression, and produce diagnostics explaining why it's 11024 // not a constant expression as a side-effect. 11025 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 11026 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 11027 11028 // In C++11, we can rely on diagnostics being produced for any expression 11029 // which is not a constant expression. If no diagnostics were produced, then 11030 // this is a constant expression. 11031 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 11032 if (Result) 11033 *Result = EvalResult.Val.getInt(); 11034 return Owned(E); 11035 } 11036 11037 // If our only note is the usual "invalid subexpression" note, just point 11038 // the caret at its location rather than producing an essentially 11039 // redundant note. 11040 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 11041 diag::note_invalid_subexpr_in_const_expr) { 11042 DiagLoc = Notes[0].first; 11043 Notes.clear(); 11044 } 11045 11046 if (!Folded || !AllowFold) { 11047 if (!Diagnoser.Suppress) { 11048 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 11049 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11050 Diag(Notes[I].first, Notes[I].second); 11051 } 11052 11053 return ExprError(); 11054 } 11055 11056 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 11057 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11058 Diag(Notes[I].first, Notes[I].second); 11059 11060 if (Result) 11061 *Result = EvalResult.Val.getInt(); 11062 return Owned(E); 11063 } 11064 11065 namespace { 11066 // Handle the case where we conclude a expression which we speculatively 11067 // considered to be unevaluated is actually evaluated. 11068 class TransformToPE : public TreeTransform<TransformToPE> { 11069 typedef TreeTransform<TransformToPE> BaseTransform; 11070 11071 public: 11072 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 11073 11074 // Make sure we redo semantic analysis 11075 bool AlwaysRebuild() { return true; } 11076 11077 // Make sure we handle LabelStmts correctly. 11078 // FIXME: This does the right thing, but maybe we need a more general 11079 // fix to TreeTransform? 11080 StmtResult TransformLabelStmt(LabelStmt *S) { 11081 S->getDecl()->setStmt(0); 11082 return BaseTransform::TransformLabelStmt(S); 11083 } 11084 11085 // We need to special-case DeclRefExprs referring to FieldDecls which 11086 // are not part of a member pointer formation; normal TreeTransforming 11087 // doesn't catch this case because of the way we represent them in the AST. 11088 // FIXME: This is a bit ugly; is it really the best way to handle this 11089 // case? 11090 // 11091 // Error on DeclRefExprs referring to FieldDecls. 11092 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 11093 if (isa<FieldDecl>(E->getDecl()) && 11094 !SemaRef.isUnevaluatedContext()) 11095 return SemaRef.Diag(E->getLocation(), 11096 diag::err_invalid_non_static_member_use) 11097 << E->getDecl() << E->getSourceRange(); 11098 11099 return BaseTransform::TransformDeclRefExpr(E); 11100 } 11101 11102 // Exception: filter out member pointer formation 11103 ExprResult TransformUnaryOperator(UnaryOperator *E) { 11104 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 11105 return E; 11106 11107 return BaseTransform::TransformUnaryOperator(E); 11108 } 11109 11110 ExprResult TransformLambdaExpr(LambdaExpr *E) { 11111 // Lambdas never need to be transformed. 11112 return E; 11113 } 11114 }; 11115 } 11116 11117 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 11118 assert(isUnevaluatedContext() && 11119 "Should only transform unevaluated expressions"); 11120 ExprEvalContexts.back().Context = 11121 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 11122 if (isUnevaluatedContext()) 11123 return E; 11124 return TransformToPE(*this).TransformExpr(E); 11125 } 11126 11127 void 11128 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 11129 Decl *LambdaContextDecl, 11130 bool IsDecltype) { 11131 ExprEvalContexts.push_back( 11132 ExpressionEvaluationContextRecord(NewContext, 11133 ExprCleanupObjects.size(), 11134 ExprNeedsCleanups, 11135 LambdaContextDecl, 11136 IsDecltype)); 11137 ExprNeedsCleanups = false; 11138 if (!MaybeODRUseExprs.empty()) 11139 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 11140 } 11141 11142 void 11143 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 11144 ReuseLambdaContextDecl_t, 11145 bool IsDecltype) { 11146 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 11147 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 11148 } 11149 11150 void Sema::PopExpressionEvaluationContext() { 11151 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 11152 11153 if (!Rec.Lambdas.empty()) { 11154 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 11155 unsigned D; 11156 if (Rec.isUnevaluated()) { 11157 // C++11 [expr.prim.lambda]p2: 11158 // A lambda-expression shall not appear in an unevaluated operand 11159 // (Clause 5). 11160 D = diag::err_lambda_unevaluated_operand; 11161 } else { 11162 // C++1y [expr.const]p2: 11163 // A conditional-expression e is a core constant expression unless the 11164 // evaluation of e, following the rules of the abstract machine, would 11165 // evaluate [...] a lambda-expression. 11166 D = diag::err_lambda_in_constant_expression; 11167 } 11168 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) 11169 Diag(Rec.Lambdas[I]->getLocStart(), D); 11170 } else { 11171 // Mark the capture expressions odr-used. This was deferred 11172 // during lambda expression creation. 11173 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) { 11174 LambdaExpr *Lambda = Rec.Lambdas[I]; 11175 for (LambdaExpr::capture_init_iterator 11176 C = Lambda->capture_init_begin(), 11177 CEnd = Lambda->capture_init_end(); 11178 C != CEnd; ++C) { 11179 MarkDeclarationsReferencedInExpr(*C); 11180 } 11181 } 11182 } 11183 } 11184 11185 // When are coming out of an unevaluated context, clear out any 11186 // temporaries that we may have created as part of the evaluation of 11187 // the expression in that context: they aren't relevant because they 11188 // will never be constructed. 11189 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 11190 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 11191 ExprCleanupObjects.end()); 11192 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 11193 CleanupVarDeclMarking(); 11194 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 11195 // Otherwise, merge the contexts together. 11196 } else { 11197 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 11198 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 11199 Rec.SavedMaybeODRUseExprs.end()); 11200 } 11201 11202 // Pop the current expression evaluation context off the stack. 11203 ExprEvalContexts.pop_back(); 11204 } 11205 11206 void Sema::DiscardCleanupsInEvaluationContext() { 11207 ExprCleanupObjects.erase( 11208 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 11209 ExprCleanupObjects.end()); 11210 ExprNeedsCleanups = false; 11211 MaybeODRUseExprs.clear(); 11212 } 11213 11214 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 11215 if (!E->getType()->isVariablyModifiedType()) 11216 return E; 11217 return TransformToPotentiallyEvaluated(E); 11218 } 11219 11220 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 11221 // Do not mark anything as "used" within a dependent context; wait for 11222 // an instantiation. 11223 if (SemaRef.CurContext->isDependentContext()) 11224 return false; 11225 11226 switch (SemaRef.ExprEvalContexts.back().Context) { 11227 case Sema::Unevaluated: 11228 case Sema::UnevaluatedAbstract: 11229 // We are in an expression that is not potentially evaluated; do nothing. 11230 // (Depending on how you read the standard, we actually do need to do 11231 // something here for null pointer constants, but the standard's 11232 // definition of a null pointer constant is completely crazy.) 11233 return false; 11234 11235 case Sema::ConstantEvaluated: 11236 case Sema::PotentiallyEvaluated: 11237 // We are in a potentially evaluated expression (or a constant-expression 11238 // in C++03); we need to do implicit template instantiation, implicitly 11239 // define class members, and mark most declarations as used. 11240 return true; 11241 11242 case Sema::PotentiallyEvaluatedIfUsed: 11243 // Referenced declarations will only be used if the construct in the 11244 // containing expression is used. 11245 return false; 11246 } 11247 llvm_unreachable("Invalid context"); 11248 } 11249 11250 /// \brief Mark a function referenced, and check whether it is odr-used 11251 /// (C++ [basic.def.odr]p2, C99 6.9p3) 11252 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) { 11253 assert(Func && "No function?"); 11254 11255 Func->setReferenced(); 11256 11257 // C++11 [basic.def.odr]p3: 11258 // A function whose name appears as a potentially-evaluated expression is 11259 // odr-used if it is the unique lookup result or the selected member of a 11260 // set of overloaded functions [...]. 11261 // 11262 // We (incorrectly) mark overload resolution as an unevaluated context, so we 11263 // can just check that here. Skip the rest of this function if we've already 11264 // marked the function as used. 11265 if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) { 11266 // C++11 [temp.inst]p3: 11267 // Unless a function template specialization has been explicitly 11268 // instantiated or explicitly specialized, the function template 11269 // specialization is implicitly instantiated when the specialization is 11270 // referenced in a context that requires a function definition to exist. 11271 // 11272 // We consider constexpr function templates to be referenced in a context 11273 // that requires a definition to exist whenever they are referenced. 11274 // 11275 // FIXME: This instantiates constexpr functions too frequently. If this is 11276 // really an unevaluated context (and we're not just in the definition of a 11277 // function template or overload resolution or other cases which we 11278 // incorrectly consider to be unevaluated contexts), and we're not in a 11279 // subexpression which we actually need to evaluate (for instance, a 11280 // template argument, array bound or an expression in a braced-init-list), 11281 // we are not permitted to instantiate this constexpr function definition. 11282 // 11283 // FIXME: This also implicitly defines special members too frequently. They 11284 // are only supposed to be implicitly defined if they are odr-used, but they 11285 // are not odr-used from constant expressions in unevaluated contexts. 11286 // However, they cannot be referenced if they are deleted, and they are 11287 // deleted whenever the implicit definition of the special member would 11288 // fail. 11289 if (!Func->isConstexpr() || Func->getBody()) 11290 return; 11291 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 11292 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 11293 return; 11294 } 11295 11296 // Note that this declaration has been used. 11297 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 11298 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 11299 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 11300 if (Constructor->isDefaultConstructor()) { 11301 if (Constructor->isTrivial()) 11302 return; 11303 DefineImplicitDefaultConstructor(Loc, Constructor); 11304 } else if (Constructor->isCopyConstructor()) { 11305 DefineImplicitCopyConstructor(Loc, Constructor); 11306 } else if (Constructor->isMoveConstructor()) { 11307 DefineImplicitMoveConstructor(Loc, Constructor); 11308 } 11309 } else if (Constructor->getInheritedConstructor()) { 11310 DefineInheritingConstructor(Loc, Constructor); 11311 } 11312 11313 MarkVTableUsed(Loc, Constructor->getParent()); 11314 } else if (CXXDestructorDecl *Destructor = 11315 dyn_cast<CXXDestructorDecl>(Func)) { 11316 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 11317 if (Destructor->isDefaulted() && !Destructor->isDeleted()) 11318 DefineImplicitDestructor(Loc, Destructor); 11319 if (Destructor->isVirtual()) 11320 MarkVTableUsed(Loc, Destructor->getParent()); 11321 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 11322 if (MethodDecl->isOverloadedOperator() && 11323 MethodDecl->getOverloadedOperator() == OO_Equal) { 11324 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 11325 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 11326 if (MethodDecl->isCopyAssignmentOperator()) 11327 DefineImplicitCopyAssignment(Loc, MethodDecl); 11328 else 11329 DefineImplicitMoveAssignment(Loc, MethodDecl); 11330 } 11331 } else if (isa<CXXConversionDecl>(MethodDecl) && 11332 MethodDecl->getParent()->isLambda()) { 11333 CXXConversionDecl *Conversion = 11334 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 11335 if (Conversion->isLambdaToBlockPointerConversion()) 11336 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 11337 else 11338 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 11339 } else if (MethodDecl->isVirtual()) 11340 MarkVTableUsed(Loc, MethodDecl->getParent()); 11341 } 11342 11343 // Recursive functions should be marked when used from another function. 11344 // FIXME: Is this really right? 11345 if (CurContext == Func) return; 11346 11347 // Resolve the exception specification for any function which is 11348 // used: CodeGen will need it. 11349 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 11350 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 11351 ResolveExceptionSpec(Loc, FPT); 11352 11353 // Implicit instantiation of function templates and member functions of 11354 // class templates. 11355 if (Func->isImplicitlyInstantiable()) { 11356 bool AlreadyInstantiated = false; 11357 SourceLocation PointOfInstantiation = Loc; 11358 if (FunctionTemplateSpecializationInfo *SpecInfo 11359 = Func->getTemplateSpecializationInfo()) { 11360 if (SpecInfo->getPointOfInstantiation().isInvalid()) 11361 SpecInfo->setPointOfInstantiation(Loc); 11362 else if (SpecInfo->getTemplateSpecializationKind() 11363 == TSK_ImplicitInstantiation) { 11364 AlreadyInstantiated = true; 11365 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 11366 } 11367 } else if (MemberSpecializationInfo *MSInfo 11368 = Func->getMemberSpecializationInfo()) { 11369 if (MSInfo->getPointOfInstantiation().isInvalid()) 11370 MSInfo->setPointOfInstantiation(Loc); 11371 else if (MSInfo->getTemplateSpecializationKind() 11372 == TSK_ImplicitInstantiation) { 11373 AlreadyInstantiated = true; 11374 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 11375 } 11376 } 11377 11378 if (!AlreadyInstantiated || Func->isConstexpr()) { 11379 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 11380 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 11381 ActiveTemplateInstantiations.size()) 11382 PendingLocalImplicitInstantiations.push_back( 11383 std::make_pair(Func, PointOfInstantiation)); 11384 else if (Func->isConstexpr()) 11385 // Do not defer instantiations of constexpr functions, to avoid the 11386 // expression evaluator needing to call back into Sema if it sees a 11387 // call to such a function. 11388 InstantiateFunctionDefinition(PointOfInstantiation, Func); 11389 else { 11390 PendingInstantiations.push_back(std::make_pair(Func, 11391 PointOfInstantiation)); 11392 // Notify the consumer that a function was implicitly instantiated. 11393 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 11394 } 11395 } 11396 } else { 11397 // Walk redefinitions, as some of them may be instantiable. 11398 for (auto i : Func->redecls()) { 11399 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 11400 MarkFunctionReferenced(Loc, i); 11401 } 11402 } 11403 11404 // Keep track of used but undefined functions. 11405 if (!Func->isDefined()) { 11406 if (mightHaveNonExternalLinkage(Func)) 11407 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 11408 else if (Func->getMostRecentDecl()->isInlined() && 11409 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 11410 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 11411 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 11412 } 11413 11414 // Normally the most current decl is marked used while processing the use and 11415 // any subsequent decls are marked used by decl merging. This fails with 11416 // template instantiation since marking can happen at the end of the file 11417 // and, because of the two phase lookup, this function is called with at 11418 // decl in the middle of a decl chain. We loop to maintain the invariant 11419 // that once a decl is used, all decls after it are also used. 11420 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) { 11421 F->markUsed(Context); 11422 if (F == Func) 11423 break; 11424 } 11425 } 11426 11427 static void 11428 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 11429 VarDecl *var, DeclContext *DC) { 11430 DeclContext *VarDC = var->getDeclContext(); 11431 11432 // If the parameter still belongs to the translation unit, then 11433 // we're actually just using one parameter in the declaration of 11434 // the next. 11435 if (isa<ParmVarDecl>(var) && 11436 isa<TranslationUnitDecl>(VarDC)) 11437 return; 11438 11439 // For C code, don't diagnose about capture if we're not actually in code 11440 // right now; it's impossible to write a non-constant expression outside of 11441 // function context, so we'll get other (more useful) diagnostics later. 11442 // 11443 // For C++, things get a bit more nasty... it would be nice to suppress this 11444 // diagnostic for certain cases like using a local variable in an array bound 11445 // for a member of a local class, but the correct predicate is not obvious. 11446 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 11447 return; 11448 11449 if (isa<CXXMethodDecl>(VarDC) && 11450 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 11451 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 11452 << var->getIdentifier(); 11453 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 11454 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 11455 << var->getIdentifier() << fn->getDeclName(); 11456 } else if (isa<BlockDecl>(VarDC)) { 11457 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 11458 << var->getIdentifier(); 11459 } else { 11460 // FIXME: Is there any other context where a local variable can be 11461 // declared? 11462 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 11463 << var->getIdentifier(); 11464 } 11465 11466 S.Diag(var->getLocation(), diag::note_local_variable_declared_here) 11467 << var->getIdentifier(); 11468 11469 // FIXME: Add additional diagnostic info about class etc. which prevents 11470 // capture. 11471 } 11472 11473 11474 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 11475 bool &SubCapturesAreNested, 11476 QualType &CaptureType, 11477 QualType &DeclRefType) { 11478 // Check whether we've already captured it. 11479 if (CSI->CaptureMap.count(Var)) { 11480 // If we found a capture, any subcaptures are nested. 11481 SubCapturesAreNested = true; 11482 11483 // Retrieve the capture type for this variable. 11484 CaptureType = CSI->getCapture(Var).getCaptureType(); 11485 11486 // Compute the type of an expression that refers to this variable. 11487 DeclRefType = CaptureType.getNonReferenceType(); 11488 11489 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 11490 if (Cap.isCopyCapture() && 11491 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable)) 11492 DeclRefType.addConst(); 11493 return true; 11494 } 11495 return false; 11496 } 11497 11498 // Only block literals, captured statements, and lambda expressions can 11499 // capture; other scopes don't work. 11500 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 11501 SourceLocation Loc, 11502 const bool Diagnose, Sema &S) { 11503 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 11504 return getLambdaAwareParentOfDeclContext(DC); 11505 else { 11506 if (Diagnose) 11507 diagnoseUncapturableValueReference(S, Loc, Var, DC); 11508 } 11509 return 0; 11510 } 11511 11512 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 11513 // certain types of variables (unnamed, variably modified types etc.) 11514 // so check for eligibility. 11515 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 11516 SourceLocation Loc, 11517 const bool Diagnose, Sema &S) { 11518 11519 bool IsBlock = isa<BlockScopeInfo>(CSI); 11520 bool IsLambda = isa<LambdaScopeInfo>(CSI); 11521 11522 // Lambdas are not allowed to capture unnamed variables 11523 // (e.g. anonymous unions). 11524 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 11525 // assuming that's the intent. 11526 if (IsLambda && !Var->getDeclName()) { 11527 if (Diagnose) { 11528 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 11529 S.Diag(Var->getLocation(), diag::note_declared_at); 11530 } 11531 return false; 11532 } 11533 11534 // Prohibit variably-modified types; they're difficult to deal with. 11535 if (Var->getType()->isVariablyModifiedType()) { 11536 if (Diagnose) { 11537 if (IsBlock) 11538 S.Diag(Loc, diag::err_ref_vm_type); 11539 else 11540 S.Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName(); 11541 S.Diag(Var->getLocation(), diag::note_previous_decl) 11542 << Var->getDeclName(); 11543 } 11544 return false; 11545 } 11546 // Prohibit structs with flexible array members too. 11547 // We cannot capture what is in the tail end of the struct. 11548 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 11549 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 11550 if (Diagnose) { 11551 if (IsBlock) 11552 S.Diag(Loc, diag::err_ref_flexarray_type); 11553 else 11554 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 11555 << Var->getDeclName(); 11556 S.Diag(Var->getLocation(), diag::note_previous_decl) 11557 << Var->getDeclName(); 11558 } 11559 return false; 11560 } 11561 } 11562 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 11563 // Lambdas and captured statements are not allowed to capture __block 11564 // variables; they don't support the expected semantics. 11565 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 11566 if (Diagnose) { 11567 S.Diag(Loc, diag::err_capture_block_variable) 11568 << Var->getDeclName() << !IsLambda; 11569 S.Diag(Var->getLocation(), diag::note_previous_decl) 11570 << Var->getDeclName(); 11571 } 11572 return false; 11573 } 11574 11575 return true; 11576 } 11577 11578 // Returns true if the capture by block was successful. 11579 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 11580 SourceLocation Loc, 11581 const bool BuildAndDiagnose, 11582 QualType &CaptureType, 11583 QualType &DeclRefType, 11584 const bool Nested, 11585 Sema &S) { 11586 Expr *CopyExpr = 0; 11587 bool ByRef = false; 11588 11589 // Blocks are not allowed to capture arrays. 11590 if (CaptureType->isArrayType()) { 11591 if (BuildAndDiagnose) { 11592 S.Diag(Loc, diag::err_ref_array_type); 11593 S.Diag(Var->getLocation(), diag::note_previous_decl) 11594 << Var->getDeclName(); 11595 } 11596 return false; 11597 } 11598 11599 // Forbid the block-capture of autoreleasing variables. 11600 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11601 if (BuildAndDiagnose) { 11602 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 11603 << /*block*/ 0; 11604 S.Diag(Var->getLocation(), diag::note_previous_decl) 11605 << Var->getDeclName(); 11606 } 11607 return false; 11608 } 11609 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 11610 if (HasBlocksAttr || CaptureType->isReferenceType()) { 11611 // Block capture by reference does not change the capture or 11612 // declaration reference types. 11613 ByRef = true; 11614 } else { 11615 // Block capture by copy introduces 'const'. 11616 CaptureType = CaptureType.getNonReferenceType().withConst(); 11617 DeclRefType = CaptureType; 11618 11619 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 11620 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 11621 // The capture logic needs the destructor, so make sure we mark it. 11622 // Usually this is unnecessary because most local variables have 11623 // their destructors marked at declaration time, but parameters are 11624 // an exception because it's technically only the call site that 11625 // actually requires the destructor. 11626 if (isa<ParmVarDecl>(Var)) 11627 S.FinalizeVarWithDestructor(Var, Record); 11628 11629 // Enter a new evaluation context to insulate the copy 11630 // full-expression. 11631 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 11632 11633 // According to the blocks spec, the capture of a variable from 11634 // the stack requires a const copy constructor. This is not true 11635 // of the copy/move done to move a __block variable to the heap. 11636 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 11637 DeclRefType.withConst(), 11638 VK_LValue, Loc); 11639 11640 ExprResult Result 11641 = S.PerformCopyInitialization( 11642 InitializedEntity::InitializeBlock(Var->getLocation(), 11643 CaptureType, false), 11644 Loc, S.Owned(DeclRef)); 11645 11646 // Build a full-expression copy expression if initialization 11647 // succeeded and used a non-trivial constructor. Recover from 11648 // errors by pretending that the copy isn't necessary. 11649 if (!Result.isInvalid() && 11650 !cast<CXXConstructExpr>(Result.get())->getConstructor() 11651 ->isTrivial()) { 11652 Result = S.MaybeCreateExprWithCleanups(Result); 11653 CopyExpr = Result.take(); 11654 } 11655 } 11656 } 11657 } 11658 11659 // Actually capture the variable. 11660 if (BuildAndDiagnose) 11661 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 11662 SourceLocation(), CaptureType, CopyExpr); 11663 11664 return true; 11665 11666 } 11667 11668 11669 /// \brief Capture the given variable in the captured region. 11670 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 11671 VarDecl *Var, 11672 SourceLocation Loc, 11673 const bool BuildAndDiagnose, 11674 QualType &CaptureType, 11675 QualType &DeclRefType, 11676 const bool RefersToEnclosingLocal, 11677 Sema &S) { 11678 11679 // By default, capture variables by reference. 11680 bool ByRef = true; 11681 // Using an LValue reference type is consistent with Lambdas (see below). 11682 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 11683 Expr *CopyExpr = 0; 11684 if (BuildAndDiagnose) { 11685 // The current implementation assumes that all variables are captured 11686 // by references. Since there is no capture by copy, no expression evaluation 11687 // will be needed. 11688 // 11689 RecordDecl *RD = RSI->TheRecordDecl; 11690 11691 FieldDecl *Field 11692 = FieldDecl::Create(S.Context, RD, Loc, Loc, 0, CaptureType, 11693 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 11694 0, false, ICIS_NoInit); 11695 Field->setImplicit(true); 11696 Field->setAccess(AS_private); 11697 RD->addDecl(Field); 11698 11699 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 11700 DeclRefType, VK_LValue, Loc); 11701 Var->setReferenced(true); 11702 Var->markUsed(S.Context); 11703 } 11704 11705 // Actually capture the variable. 11706 if (BuildAndDiagnose) 11707 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc, 11708 SourceLocation(), CaptureType, CopyExpr); 11709 11710 11711 return true; 11712 } 11713 11714 /// \brief Create a field within the lambda class for the variable 11715 /// being captured. Handle Array captures. 11716 static ExprResult addAsFieldToClosureType(Sema &S, 11717 LambdaScopeInfo *LSI, 11718 VarDecl *Var, QualType FieldType, 11719 QualType DeclRefType, 11720 SourceLocation Loc, 11721 bool RefersToEnclosingLocal) { 11722 CXXRecordDecl *Lambda = LSI->Lambda; 11723 11724 // Build the non-static data member. 11725 FieldDecl *Field 11726 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType, 11727 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 11728 0, false, ICIS_NoInit); 11729 Field->setImplicit(true); 11730 Field->setAccess(AS_private); 11731 Lambda->addDecl(Field); 11732 11733 // C++11 [expr.prim.lambda]p21: 11734 // When the lambda-expression is evaluated, the entities that 11735 // are captured by copy are used to direct-initialize each 11736 // corresponding non-static data member of the resulting closure 11737 // object. (For array members, the array elements are 11738 // direct-initialized in increasing subscript order.) These 11739 // initializations are performed in the (unspecified) order in 11740 // which the non-static data members are declared. 11741 11742 // Introduce a new evaluation context for the initialization, so 11743 // that temporaries introduced as part of the capture are retained 11744 // to be re-"exported" from the lambda expression itself. 11745 EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated); 11746 11747 // C++ [expr.prim.labda]p12: 11748 // An entity captured by a lambda-expression is odr-used (3.2) in 11749 // the scope containing the lambda-expression. 11750 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 11751 DeclRefType, VK_LValue, Loc); 11752 Var->setReferenced(true); 11753 Var->markUsed(S.Context); 11754 11755 // When the field has array type, create index variables for each 11756 // dimension of the array. We use these index variables to subscript 11757 // the source array, and other clients (e.g., CodeGen) will perform 11758 // the necessary iteration with these index variables. 11759 SmallVector<VarDecl *, 4> IndexVariables; 11760 QualType BaseType = FieldType; 11761 QualType SizeType = S.Context.getSizeType(); 11762 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size()); 11763 while (const ConstantArrayType *Array 11764 = S.Context.getAsConstantArrayType(BaseType)) { 11765 // Create the iteration variable for this array index. 11766 IdentifierInfo *IterationVarName = 0; 11767 { 11768 SmallString<8> Str; 11769 llvm::raw_svector_ostream OS(Str); 11770 OS << "__i" << IndexVariables.size(); 11771 IterationVarName = &S.Context.Idents.get(OS.str()); 11772 } 11773 VarDecl *IterationVar 11774 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11775 IterationVarName, SizeType, 11776 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11777 SC_None); 11778 IndexVariables.push_back(IterationVar); 11779 LSI->ArrayIndexVars.push_back(IterationVar); 11780 11781 // Create a reference to the iteration variable. 11782 ExprResult IterationVarRef 11783 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 11784 assert(!IterationVarRef.isInvalid() && 11785 "Reference to invented variable cannot fail!"); 11786 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take()); 11787 assert(!IterationVarRef.isInvalid() && 11788 "Conversion of invented variable cannot fail!"); 11789 11790 // Subscript the array with this iteration variable. 11791 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr( 11792 Ref, Loc, IterationVarRef.take(), Loc); 11793 if (Subscript.isInvalid()) { 11794 S.CleanupVarDeclMarking(); 11795 S.DiscardCleanupsInEvaluationContext(); 11796 return ExprError(); 11797 } 11798 11799 Ref = Subscript.take(); 11800 BaseType = Array->getElementType(); 11801 } 11802 11803 // Construct the entity that we will be initializing. For an array, this 11804 // will be first element in the array, which may require several levels 11805 // of array-subscript entities. 11806 SmallVector<InitializedEntity, 4> Entities; 11807 Entities.reserve(1 + IndexVariables.size()); 11808 Entities.push_back( 11809 InitializedEntity::InitializeLambdaCapture(Var->getIdentifier(), 11810 Field->getType(), Loc)); 11811 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 11812 Entities.push_back(InitializedEntity::InitializeElement(S.Context, 11813 0, 11814 Entities.back())); 11815 11816 InitializationKind InitKind 11817 = InitializationKind::CreateDirect(Loc, Loc, Loc); 11818 InitializationSequence Init(S, Entities.back(), InitKind, Ref); 11819 ExprResult Result(true); 11820 if (!Init.Diagnose(S, Entities.back(), InitKind, Ref)) 11821 Result = Init.Perform(S, Entities.back(), InitKind, Ref); 11822 11823 // If this initialization requires any cleanups (e.g., due to a 11824 // default argument to a copy constructor), note that for the 11825 // lambda. 11826 if (S.ExprNeedsCleanups) 11827 LSI->ExprNeedsCleanups = true; 11828 11829 // Exit the expression evaluation context used for the capture. 11830 S.CleanupVarDeclMarking(); 11831 S.DiscardCleanupsInEvaluationContext(); 11832 return Result; 11833 } 11834 11835 11836 11837 /// \brief Capture the given variable in the lambda. 11838 static bool captureInLambda(LambdaScopeInfo *LSI, 11839 VarDecl *Var, 11840 SourceLocation Loc, 11841 const bool BuildAndDiagnose, 11842 QualType &CaptureType, 11843 QualType &DeclRefType, 11844 const bool RefersToEnclosingLocal, 11845 const Sema::TryCaptureKind Kind, 11846 SourceLocation EllipsisLoc, 11847 const bool IsTopScope, 11848 Sema &S) { 11849 11850 // Determine whether we are capturing by reference or by value. 11851 bool ByRef = false; 11852 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 11853 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 11854 } else { 11855 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 11856 } 11857 11858 // Compute the type of the field that will capture this variable. 11859 if (ByRef) { 11860 // C++11 [expr.prim.lambda]p15: 11861 // An entity is captured by reference if it is implicitly or 11862 // explicitly captured but not captured by copy. It is 11863 // unspecified whether additional unnamed non-static data 11864 // members are declared in the closure type for entities 11865 // captured by reference. 11866 // 11867 // FIXME: It is not clear whether we want to build an lvalue reference 11868 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 11869 // to do the former, while EDG does the latter. Core issue 1249 will 11870 // clarify, but for now we follow GCC because it's a more permissive and 11871 // easily defensible position. 11872 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 11873 } else { 11874 // C++11 [expr.prim.lambda]p14: 11875 // For each entity captured by copy, an unnamed non-static 11876 // data member is declared in the closure type. The 11877 // declaration order of these members is unspecified. The type 11878 // of such a data member is the type of the corresponding 11879 // captured entity if the entity is not a reference to an 11880 // object, or the referenced type otherwise. [Note: If the 11881 // captured entity is a reference to a function, the 11882 // corresponding data member is also a reference to a 11883 // function. - end note ] 11884 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 11885 if (!RefType->getPointeeType()->isFunctionType()) 11886 CaptureType = RefType->getPointeeType(); 11887 } 11888 11889 // Forbid the lambda copy-capture of autoreleasing variables. 11890 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11891 if (BuildAndDiagnose) { 11892 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 11893 S.Diag(Var->getLocation(), diag::note_previous_decl) 11894 << Var->getDeclName(); 11895 } 11896 return false; 11897 } 11898 11899 // Make sure that by-copy captures are of a complete and non-abstract type. 11900 if (BuildAndDiagnose) { 11901 if (!CaptureType->isDependentType() && 11902 S.RequireCompleteType(Loc, CaptureType, 11903 diag::err_capture_of_incomplete_type, 11904 Var->getDeclName())) 11905 return false; 11906 11907 if (S.RequireNonAbstractType(Loc, CaptureType, 11908 diag::err_capture_of_abstract_type)) 11909 return false; 11910 } 11911 } 11912 11913 // Capture this variable in the lambda. 11914 Expr *CopyExpr = 0; 11915 if (BuildAndDiagnose) { 11916 ExprResult Result = addAsFieldToClosureType(S, LSI, Var, 11917 CaptureType, DeclRefType, Loc, 11918 RefersToEnclosingLocal); 11919 if (!Result.isInvalid()) 11920 CopyExpr = Result.take(); 11921 } 11922 11923 // Compute the type of a reference to this captured variable. 11924 if (ByRef) 11925 DeclRefType = CaptureType.getNonReferenceType(); 11926 else { 11927 // C++ [expr.prim.lambda]p5: 11928 // The closure type for a lambda-expression has a public inline 11929 // function call operator [...]. This function call operator is 11930 // declared const (9.3.1) if and only if the lambda-expression’s 11931 // parameter-declaration-clause is not followed by mutable. 11932 DeclRefType = CaptureType.getNonReferenceType(); 11933 if (!LSI->Mutable && !CaptureType->isReferenceType()) 11934 DeclRefType.addConst(); 11935 } 11936 11937 // Add the capture. 11938 if (BuildAndDiagnose) 11939 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal, 11940 Loc, EllipsisLoc, CaptureType, CopyExpr); 11941 11942 return true; 11943 } 11944 11945 11946 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc, 11947 TryCaptureKind Kind, SourceLocation EllipsisLoc, 11948 bool BuildAndDiagnose, 11949 QualType &CaptureType, 11950 QualType &DeclRefType, 11951 const unsigned *const FunctionScopeIndexToStopAt) { 11952 bool Nested = false; 11953 11954 DeclContext *DC = CurContext; 11955 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 11956 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 11957 // We need to sync up the Declaration Context with the 11958 // FunctionScopeIndexToStopAt 11959 if (FunctionScopeIndexToStopAt) { 11960 unsigned FSIndex = FunctionScopes.size() - 1; 11961 while (FSIndex != MaxFunctionScopesIndex) { 11962 DC = getLambdaAwareParentOfDeclContext(DC); 11963 --FSIndex; 11964 } 11965 } 11966 11967 11968 // If the variable is declared in the current context (and is not an 11969 // init-capture), there is no need to capture it. 11970 if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true; 11971 if (!Var->hasLocalStorage()) return true; 11972 11973 // Walk up the stack to determine whether we can capture the variable, 11974 // performing the "simple" checks that don't depend on type. We stop when 11975 // we've either hit the declared scope of the variable or find an existing 11976 // capture of that variable. We start from the innermost capturing-entity 11977 // (the DC) and ensure that all intervening capturing-entities 11978 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 11979 // declcontext can either capture the variable or have already captured 11980 // the variable. 11981 CaptureType = Var->getType(); 11982 DeclRefType = CaptureType.getNonReferenceType(); 11983 bool Explicit = (Kind != TryCapture_Implicit); 11984 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 11985 do { 11986 // Only block literals, captured statements, and lambda expressions can 11987 // capture; other scopes don't work. 11988 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 11989 ExprLoc, 11990 BuildAndDiagnose, 11991 *this); 11992 if (!ParentDC) return true; 11993 11994 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 11995 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 11996 11997 11998 // Check whether we've already captured it. 11999 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 12000 DeclRefType)) 12001 break; 12002 // If we are instantiating a generic lambda call operator body, 12003 // we do not want to capture new variables. What was captured 12004 // during either a lambdas transformation or initial parsing 12005 // should be used. 12006 if (isGenericLambdaCallOperatorSpecialization(DC)) { 12007 if (BuildAndDiagnose) { 12008 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 12009 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 12010 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 12011 Diag(Var->getLocation(), diag::note_previous_decl) 12012 << Var->getDeclName(); 12013 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 12014 } else 12015 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 12016 } 12017 return true; 12018 } 12019 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 12020 // certain types of variables (unnamed, variably modified types etc.) 12021 // so check for eligibility. 12022 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 12023 return true; 12024 12025 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 12026 // No capture-default, and this is not an explicit capture 12027 // so cannot capture this variable. 12028 if (BuildAndDiagnose) { 12029 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 12030 Diag(Var->getLocation(), diag::note_previous_decl) 12031 << Var->getDeclName(); 12032 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 12033 diag::note_lambda_decl); 12034 // FIXME: If we error out because an outer lambda can not implicitly 12035 // capture a variable that an inner lambda explicitly captures, we 12036 // should have the inner lambda do the explicit capture - because 12037 // it makes for cleaner diagnostics later. This would purely be done 12038 // so that the diagnostic does not misleadingly claim that a variable 12039 // can not be captured by a lambda implicitly even though it is captured 12040 // explicitly. Suggestion: 12041 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 12042 // at the function head 12043 // - cache the StartingDeclContext - this must be a lambda 12044 // - captureInLambda in the innermost lambda the variable. 12045 } 12046 return true; 12047 } 12048 12049 FunctionScopesIndex--; 12050 DC = ParentDC; 12051 Explicit = false; 12052 } while (!Var->getDeclContext()->Equals(DC)); 12053 12054 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 12055 // computing the type of the capture at each step, checking type-specific 12056 // requirements, and adding captures if requested. 12057 // If the variable had already been captured previously, we start capturing 12058 // at the lambda nested within that one. 12059 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 12060 ++I) { 12061 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 12062 12063 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 12064 if (!captureInBlock(BSI, Var, ExprLoc, 12065 BuildAndDiagnose, CaptureType, 12066 DeclRefType, Nested, *this)) 12067 return true; 12068 Nested = true; 12069 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 12070 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 12071 BuildAndDiagnose, CaptureType, 12072 DeclRefType, Nested, *this)) 12073 return true; 12074 Nested = true; 12075 } else { 12076 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 12077 if (!captureInLambda(LSI, Var, ExprLoc, 12078 BuildAndDiagnose, CaptureType, 12079 DeclRefType, Nested, Kind, EllipsisLoc, 12080 /*IsTopScope*/I == N - 1, *this)) 12081 return true; 12082 Nested = true; 12083 } 12084 } 12085 return false; 12086 } 12087 12088 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 12089 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 12090 QualType CaptureType; 12091 QualType DeclRefType; 12092 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 12093 /*BuildAndDiagnose=*/true, CaptureType, 12094 DeclRefType, 0); 12095 } 12096 12097 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 12098 QualType CaptureType; 12099 QualType DeclRefType; 12100 12101 // Determine whether we can capture this variable. 12102 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 12103 /*BuildAndDiagnose=*/false, CaptureType, 12104 DeclRefType, 0)) 12105 return QualType(); 12106 12107 return DeclRefType; 12108 } 12109 12110 12111 12112 // If either the type of the variable or the initializer is dependent, 12113 // return false. Otherwise, determine whether the variable is a constant 12114 // expression. Use this if you need to know if a variable that might or 12115 // might not be dependent is truly a constant expression. 12116 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 12117 ASTContext &Context) { 12118 12119 if (Var->getType()->isDependentType()) 12120 return false; 12121 const VarDecl *DefVD = 0; 12122 Var->getAnyInitializer(DefVD); 12123 if (!DefVD) 12124 return false; 12125 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 12126 Expr *Init = cast<Expr>(Eval->Value); 12127 if (Init->isValueDependent()) 12128 return false; 12129 return IsVariableAConstantExpression(Var, Context); 12130 } 12131 12132 12133 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 12134 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 12135 // an object that satisfies the requirements for appearing in a 12136 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 12137 // is immediately applied." This function handles the lvalue-to-rvalue 12138 // conversion part. 12139 MaybeODRUseExprs.erase(E->IgnoreParens()); 12140 12141 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 12142 // to a variable that is a constant expression, and if so, identify it as 12143 // a reference to a variable that does not involve an odr-use of that 12144 // variable. 12145 if (LambdaScopeInfo *LSI = getCurLambda()) { 12146 Expr *SansParensExpr = E->IgnoreParens(); 12147 VarDecl *Var = 0; 12148 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 12149 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 12150 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 12151 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 12152 12153 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 12154 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 12155 } 12156 } 12157 12158 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 12159 if (!Res.isUsable()) 12160 return Res; 12161 12162 // If a constant-expression is a reference to a variable where we delay 12163 // deciding whether it is an odr-use, just assume we will apply the 12164 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 12165 // (a non-type template argument), we have special handling anyway. 12166 UpdateMarkingForLValueToRValue(Res.get()); 12167 return Res; 12168 } 12169 12170 void Sema::CleanupVarDeclMarking() { 12171 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(), 12172 e = MaybeODRUseExprs.end(); 12173 i != e; ++i) { 12174 VarDecl *Var; 12175 SourceLocation Loc; 12176 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) { 12177 Var = cast<VarDecl>(DRE->getDecl()); 12178 Loc = DRE->getLocation(); 12179 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) { 12180 Var = cast<VarDecl>(ME->getMemberDecl()); 12181 Loc = ME->getMemberLoc(); 12182 } else { 12183 llvm_unreachable("Unexpcted expression"); 12184 } 12185 12186 MarkVarDeclODRUsed(Var, Loc, *this, /*MaxFunctionScopeIndex Pointer*/ 0); 12187 } 12188 12189 MaybeODRUseExprs.clear(); 12190 } 12191 12192 12193 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 12194 VarDecl *Var, Expr *E) { 12195 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 12196 "Invalid Expr argument to DoMarkVarDeclReferenced"); 12197 Var->setReferenced(); 12198 12199 // If the context is not potentially evaluated, this is not an odr-use and 12200 // does not trigger instantiation. 12201 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 12202 if (SemaRef.isUnevaluatedContext()) 12203 return; 12204 12205 // If we don't yet know whether this context is going to end up being an 12206 // evaluated context, and we're referencing a variable from an enclosing 12207 // scope, add a potential capture. 12208 // 12209 // FIXME: Is this necessary? These contexts are only used for default 12210 // arguments, where local variables can't be used. 12211 const bool RefersToEnclosingScope = 12212 (SemaRef.CurContext != Var->getDeclContext() && 12213 Var->getDeclContext()->isFunctionOrMethod() && 12214 Var->hasLocalStorage()); 12215 if (!RefersToEnclosingScope) 12216 return; 12217 12218 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 12219 // If a variable could potentially be odr-used, defer marking it so 12220 // until we finish analyzing the full expression for any lvalue-to-rvalue 12221 // or discarded value conversions that would obviate odr-use. 12222 // Add it to the list of potential captures that will be analyzed 12223 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 12224 // unless the variable is a reference that was initialized by a constant 12225 // expression (this will never need to be captured or odr-used). 12226 assert(E && "Capture variable should be used in an expression."); 12227 if (!Var->getType()->isReferenceType() || 12228 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 12229 LSI->addPotentialCapture(E->IgnoreParens()); 12230 } 12231 return; 12232 } 12233 12234 VarTemplateSpecializationDecl *VarSpec = 12235 dyn_cast<VarTemplateSpecializationDecl>(Var); 12236 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 12237 "Can't instantiate a partial template specialization."); 12238 12239 // Perform implicit instantiation of static data members, static data member 12240 // templates of class templates, and variable template specializations. Delay 12241 // instantiations of variable templates, except for those that could be used 12242 // in a constant expression. 12243 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 12244 if (isTemplateInstantiation(TSK)) { 12245 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 12246 12247 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 12248 if (Var->getPointOfInstantiation().isInvalid()) { 12249 // This is a modification of an existing AST node. Notify listeners. 12250 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 12251 L->StaticDataMemberInstantiated(Var); 12252 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 12253 // Don't bother trying to instantiate it again, unless we might need 12254 // its initializer before we get to the end of the TU. 12255 TryInstantiating = false; 12256 } 12257 12258 if (Var->getPointOfInstantiation().isInvalid()) 12259 Var->setTemplateSpecializationKind(TSK, Loc); 12260 12261 if (TryInstantiating) { 12262 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 12263 bool InstantiationDependent = false; 12264 bool IsNonDependent = 12265 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 12266 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 12267 : true; 12268 12269 // Do not instantiate specializations that are still type-dependent. 12270 if (IsNonDependent) { 12271 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 12272 // Do not defer instantiations of variables which could be used in a 12273 // constant expression. 12274 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 12275 } else { 12276 SemaRef.PendingInstantiations 12277 .push_back(std::make_pair(Var, PointOfInstantiation)); 12278 } 12279 } 12280 } 12281 } 12282 12283 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 12284 // the requirements for appearing in a constant expression (5.19) and, if 12285 // it is an object, the lvalue-to-rvalue conversion (4.1) 12286 // is immediately applied." We check the first part here, and 12287 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 12288 // Note that we use the C++11 definition everywhere because nothing in 12289 // C++03 depends on whether we get the C++03 version correct. The second 12290 // part does not apply to references, since they are not objects. 12291 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 12292 // A reference initialized by a constant expression can never be 12293 // odr-used, so simply ignore it. 12294 if (!Var->getType()->isReferenceType()) 12295 SemaRef.MaybeODRUseExprs.insert(E); 12296 } else 12297 MarkVarDeclODRUsed(Var, Loc, SemaRef, /*MaxFunctionScopeIndex ptr*/0); 12298 } 12299 12300 /// \brief Mark a variable referenced, and check whether it is odr-used 12301 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 12302 /// used directly for normal expressions referring to VarDecl. 12303 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 12304 DoMarkVarDeclReferenced(*this, Loc, Var, 0); 12305 } 12306 12307 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 12308 Decl *D, Expr *E, bool OdrUse) { 12309 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 12310 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 12311 return; 12312 } 12313 12314 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse); 12315 12316 // If this is a call to a method via a cast, also mark the method in the 12317 // derived class used in case codegen can devirtualize the call. 12318 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12319 if (!ME) 12320 return; 12321 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 12322 if (!MD) 12323 return; 12324 const Expr *Base = ME->getBase(); 12325 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 12326 if (!MostDerivedClassDecl) 12327 return; 12328 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 12329 if (!DM || DM->isPure()) 12330 return; 12331 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse); 12332 } 12333 12334 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 12335 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 12336 // TODO: update this with DR# once a defect report is filed. 12337 // C++11 defect. The address of a pure member should not be an ODR use, even 12338 // if it's a qualified reference. 12339 bool OdrUse = true; 12340 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 12341 if (Method->isVirtual()) 12342 OdrUse = false; 12343 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 12344 } 12345 12346 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 12347 void Sema::MarkMemberReferenced(MemberExpr *E) { 12348 // C++11 [basic.def.odr]p2: 12349 // A non-overloaded function whose name appears as a potentially-evaluated 12350 // expression or a member of a set of candidate functions, if selected by 12351 // overload resolution when referred to from a potentially-evaluated 12352 // expression, is odr-used, unless it is a pure virtual function and its 12353 // name is not explicitly qualified. 12354 bool OdrUse = true; 12355 if (!E->hasQualifier()) { 12356 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 12357 if (Method->isPure()) 12358 OdrUse = false; 12359 } 12360 SourceLocation Loc = E->getMemberLoc().isValid() ? 12361 E->getMemberLoc() : E->getLocStart(); 12362 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse); 12363 } 12364 12365 /// \brief Perform marking for a reference to an arbitrary declaration. It 12366 /// marks the declaration referenced, and performs odr-use checking for functions 12367 /// and variables. This method should not be used when building an normal 12368 /// expression which refers to a variable. 12369 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) { 12370 if (OdrUse) { 12371 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 12372 MarkVariableReferenced(Loc, VD); 12373 return; 12374 } 12375 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 12376 MarkFunctionReferenced(Loc, FD); 12377 return; 12378 } 12379 } 12380 D->setReferenced(); 12381 } 12382 12383 namespace { 12384 // Mark all of the declarations referenced 12385 // FIXME: Not fully implemented yet! We need to have a better understanding 12386 // of when we're entering 12387 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 12388 Sema &S; 12389 SourceLocation Loc; 12390 12391 public: 12392 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 12393 12394 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 12395 12396 bool TraverseTemplateArgument(const TemplateArgument &Arg); 12397 bool TraverseRecordType(RecordType *T); 12398 }; 12399 } 12400 12401 bool MarkReferencedDecls::TraverseTemplateArgument( 12402 const TemplateArgument &Arg) { 12403 if (Arg.getKind() == TemplateArgument::Declaration) { 12404 if (Decl *D = Arg.getAsDecl()) 12405 S.MarkAnyDeclReferenced(Loc, D, true); 12406 } 12407 12408 return Inherited::TraverseTemplateArgument(Arg); 12409 } 12410 12411 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 12412 if (ClassTemplateSpecializationDecl *Spec 12413 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 12414 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 12415 return TraverseTemplateArguments(Args.data(), Args.size()); 12416 } 12417 12418 return true; 12419 } 12420 12421 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 12422 MarkReferencedDecls Marker(*this, Loc); 12423 Marker.TraverseType(Context.getCanonicalType(T)); 12424 } 12425 12426 namespace { 12427 /// \brief Helper class that marks all of the declarations referenced by 12428 /// potentially-evaluated subexpressions as "referenced". 12429 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 12430 Sema &S; 12431 bool SkipLocalVariables; 12432 12433 public: 12434 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 12435 12436 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 12437 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 12438 12439 void VisitDeclRefExpr(DeclRefExpr *E) { 12440 // If we were asked not to visit local variables, don't. 12441 if (SkipLocalVariables) { 12442 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 12443 if (VD->hasLocalStorage()) 12444 return; 12445 } 12446 12447 S.MarkDeclRefReferenced(E); 12448 } 12449 12450 void VisitMemberExpr(MemberExpr *E) { 12451 S.MarkMemberReferenced(E); 12452 Inherited::VisitMemberExpr(E); 12453 } 12454 12455 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 12456 S.MarkFunctionReferenced(E->getLocStart(), 12457 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 12458 Visit(E->getSubExpr()); 12459 } 12460 12461 void VisitCXXNewExpr(CXXNewExpr *E) { 12462 if (E->getOperatorNew()) 12463 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 12464 if (E->getOperatorDelete()) 12465 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 12466 Inherited::VisitCXXNewExpr(E); 12467 } 12468 12469 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 12470 if (E->getOperatorDelete()) 12471 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 12472 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 12473 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 12474 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 12475 S.MarkFunctionReferenced(E->getLocStart(), 12476 S.LookupDestructor(Record)); 12477 } 12478 12479 Inherited::VisitCXXDeleteExpr(E); 12480 } 12481 12482 void VisitCXXConstructExpr(CXXConstructExpr *E) { 12483 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 12484 Inherited::VisitCXXConstructExpr(E); 12485 } 12486 12487 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 12488 Visit(E->getExpr()); 12489 } 12490 12491 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 12492 Inherited::VisitImplicitCastExpr(E); 12493 12494 if (E->getCastKind() == CK_LValueToRValue) 12495 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 12496 } 12497 }; 12498 } 12499 12500 /// \brief Mark any declarations that appear within this expression or any 12501 /// potentially-evaluated subexpressions as "referenced". 12502 /// 12503 /// \param SkipLocalVariables If true, don't mark local variables as 12504 /// 'referenced'. 12505 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 12506 bool SkipLocalVariables) { 12507 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 12508 } 12509 12510 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 12511 /// of the program being compiled. 12512 /// 12513 /// This routine emits the given diagnostic when the code currently being 12514 /// type-checked is "potentially evaluated", meaning that there is a 12515 /// possibility that the code will actually be executable. Code in sizeof() 12516 /// expressions, code used only during overload resolution, etc., are not 12517 /// potentially evaluated. This routine will suppress such diagnostics or, 12518 /// in the absolutely nutty case of potentially potentially evaluated 12519 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 12520 /// later. 12521 /// 12522 /// This routine should be used for all diagnostics that describe the run-time 12523 /// behavior of a program, such as passing a non-POD value through an ellipsis. 12524 /// Failure to do so will likely result in spurious diagnostics or failures 12525 /// during overload resolution or within sizeof/alignof/typeof/typeid. 12526 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 12527 const PartialDiagnostic &PD) { 12528 switch (ExprEvalContexts.back().Context) { 12529 case Unevaluated: 12530 case UnevaluatedAbstract: 12531 // The argument will never be evaluated, so don't complain. 12532 break; 12533 12534 case ConstantEvaluated: 12535 // Relevant diagnostics should be produced by constant evaluation. 12536 break; 12537 12538 case PotentiallyEvaluated: 12539 case PotentiallyEvaluatedIfUsed: 12540 if (Statement && getCurFunctionOrMethodDecl()) { 12541 FunctionScopes.back()->PossiblyUnreachableDiags. 12542 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 12543 } 12544 else 12545 Diag(Loc, PD); 12546 12547 return true; 12548 } 12549 12550 return false; 12551 } 12552 12553 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 12554 CallExpr *CE, FunctionDecl *FD) { 12555 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 12556 return false; 12557 12558 // If we're inside a decltype's expression, don't check for a valid return 12559 // type or construct temporaries until we know whether this is the last call. 12560 if (ExprEvalContexts.back().IsDecltype) { 12561 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 12562 return false; 12563 } 12564 12565 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 12566 FunctionDecl *FD; 12567 CallExpr *CE; 12568 12569 public: 12570 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 12571 : FD(FD), CE(CE) { } 12572 12573 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 12574 if (!FD) { 12575 S.Diag(Loc, diag::err_call_incomplete_return) 12576 << T << CE->getSourceRange(); 12577 return; 12578 } 12579 12580 S.Diag(Loc, diag::err_call_function_incomplete_return) 12581 << CE->getSourceRange() << FD->getDeclName() << T; 12582 S.Diag(FD->getLocation(), 12583 diag::note_function_with_incomplete_return_type_declared_here) 12584 << FD->getDeclName(); 12585 } 12586 } Diagnoser(FD, CE); 12587 12588 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 12589 return true; 12590 12591 return false; 12592 } 12593 12594 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 12595 // will prevent this condition from triggering, which is what we want. 12596 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 12597 SourceLocation Loc; 12598 12599 unsigned diagnostic = diag::warn_condition_is_assignment; 12600 bool IsOrAssign = false; 12601 12602 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 12603 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 12604 return; 12605 12606 IsOrAssign = Op->getOpcode() == BO_OrAssign; 12607 12608 // Greylist some idioms by putting them into a warning subcategory. 12609 if (ObjCMessageExpr *ME 12610 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 12611 Selector Sel = ME->getSelector(); 12612 12613 // self = [<foo> init...] 12614 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 12615 diagnostic = diag::warn_condition_is_idiomatic_assignment; 12616 12617 // <foo> = [<bar> nextObject] 12618 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 12619 diagnostic = diag::warn_condition_is_idiomatic_assignment; 12620 } 12621 12622 Loc = Op->getOperatorLoc(); 12623 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 12624 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 12625 return; 12626 12627 IsOrAssign = Op->getOperator() == OO_PipeEqual; 12628 Loc = Op->getOperatorLoc(); 12629 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 12630 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 12631 else { 12632 // Not an assignment. 12633 return; 12634 } 12635 12636 Diag(Loc, diagnostic) << E->getSourceRange(); 12637 12638 SourceLocation Open = E->getLocStart(); 12639 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 12640 Diag(Loc, diag::note_condition_assign_silence) 12641 << FixItHint::CreateInsertion(Open, "(") 12642 << FixItHint::CreateInsertion(Close, ")"); 12643 12644 if (IsOrAssign) 12645 Diag(Loc, diag::note_condition_or_assign_to_comparison) 12646 << FixItHint::CreateReplacement(Loc, "!="); 12647 else 12648 Diag(Loc, diag::note_condition_assign_to_comparison) 12649 << FixItHint::CreateReplacement(Loc, "=="); 12650 } 12651 12652 /// \brief Redundant parentheses over an equality comparison can indicate 12653 /// that the user intended an assignment used as condition. 12654 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 12655 // Don't warn if the parens came from a macro. 12656 SourceLocation parenLoc = ParenE->getLocStart(); 12657 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 12658 return; 12659 // Don't warn for dependent expressions. 12660 if (ParenE->isTypeDependent()) 12661 return; 12662 12663 Expr *E = ParenE->IgnoreParens(); 12664 12665 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 12666 if (opE->getOpcode() == BO_EQ && 12667 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 12668 == Expr::MLV_Valid) { 12669 SourceLocation Loc = opE->getOperatorLoc(); 12670 12671 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 12672 SourceRange ParenERange = ParenE->getSourceRange(); 12673 Diag(Loc, diag::note_equality_comparison_silence) 12674 << FixItHint::CreateRemoval(ParenERange.getBegin()) 12675 << FixItHint::CreateRemoval(ParenERange.getEnd()); 12676 Diag(Loc, diag::note_equality_comparison_to_assign) 12677 << FixItHint::CreateReplacement(Loc, "="); 12678 } 12679 } 12680 12681 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 12682 DiagnoseAssignmentAsCondition(E); 12683 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 12684 DiagnoseEqualityWithExtraParens(parenE); 12685 12686 ExprResult result = CheckPlaceholderExpr(E); 12687 if (result.isInvalid()) return ExprError(); 12688 E = result.take(); 12689 12690 if (!E->isTypeDependent()) { 12691 if (getLangOpts().CPlusPlus) 12692 return CheckCXXBooleanCondition(E); // C++ 6.4p4 12693 12694 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 12695 if (ERes.isInvalid()) 12696 return ExprError(); 12697 E = ERes.take(); 12698 12699 QualType T = E->getType(); 12700 if (!T->isScalarType()) { // C99 6.8.4.1p1 12701 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 12702 << T << E->getSourceRange(); 12703 return ExprError(); 12704 } 12705 } 12706 12707 return Owned(E); 12708 } 12709 12710 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 12711 Expr *SubExpr) { 12712 if (!SubExpr) 12713 return ExprError(); 12714 12715 return CheckBooleanCondition(SubExpr, Loc); 12716 } 12717 12718 namespace { 12719 /// A visitor for rebuilding a call to an __unknown_any expression 12720 /// to have an appropriate type. 12721 struct RebuildUnknownAnyFunction 12722 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 12723 12724 Sema &S; 12725 12726 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 12727 12728 ExprResult VisitStmt(Stmt *S) { 12729 llvm_unreachable("unexpected statement!"); 12730 } 12731 12732 ExprResult VisitExpr(Expr *E) { 12733 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 12734 << E->getSourceRange(); 12735 return ExprError(); 12736 } 12737 12738 /// Rebuild an expression which simply semantically wraps another 12739 /// expression which it shares the type and value kind of. 12740 template <class T> ExprResult rebuildSugarExpr(T *E) { 12741 ExprResult SubResult = Visit(E->getSubExpr()); 12742 if (SubResult.isInvalid()) return ExprError(); 12743 12744 Expr *SubExpr = SubResult.take(); 12745 E->setSubExpr(SubExpr); 12746 E->setType(SubExpr->getType()); 12747 E->setValueKind(SubExpr->getValueKind()); 12748 assert(E->getObjectKind() == OK_Ordinary); 12749 return E; 12750 } 12751 12752 ExprResult VisitParenExpr(ParenExpr *E) { 12753 return rebuildSugarExpr(E); 12754 } 12755 12756 ExprResult VisitUnaryExtension(UnaryOperator *E) { 12757 return rebuildSugarExpr(E); 12758 } 12759 12760 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 12761 ExprResult SubResult = Visit(E->getSubExpr()); 12762 if (SubResult.isInvalid()) return ExprError(); 12763 12764 Expr *SubExpr = SubResult.take(); 12765 E->setSubExpr(SubExpr); 12766 E->setType(S.Context.getPointerType(SubExpr->getType())); 12767 assert(E->getValueKind() == VK_RValue); 12768 assert(E->getObjectKind() == OK_Ordinary); 12769 return E; 12770 } 12771 12772 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 12773 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 12774 12775 E->setType(VD->getType()); 12776 12777 assert(E->getValueKind() == VK_RValue); 12778 if (S.getLangOpts().CPlusPlus && 12779 !(isa<CXXMethodDecl>(VD) && 12780 cast<CXXMethodDecl>(VD)->isInstance())) 12781 E->setValueKind(VK_LValue); 12782 12783 return E; 12784 } 12785 12786 ExprResult VisitMemberExpr(MemberExpr *E) { 12787 return resolveDecl(E, E->getMemberDecl()); 12788 } 12789 12790 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 12791 return resolveDecl(E, E->getDecl()); 12792 } 12793 }; 12794 } 12795 12796 /// Given a function expression of unknown-any type, try to rebuild it 12797 /// to have a function type. 12798 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 12799 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 12800 if (Result.isInvalid()) return ExprError(); 12801 return S.DefaultFunctionArrayConversion(Result.take()); 12802 } 12803 12804 namespace { 12805 /// A visitor for rebuilding an expression of type __unknown_anytype 12806 /// into one which resolves the type directly on the referring 12807 /// expression. Strict preservation of the original source 12808 /// structure is not a goal. 12809 struct RebuildUnknownAnyExpr 12810 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 12811 12812 Sema &S; 12813 12814 /// The current destination type. 12815 QualType DestType; 12816 12817 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 12818 : S(S), DestType(CastType) {} 12819 12820 ExprResult VisitStmt(Stmt *S) { 12821 llvm_unreachable("unexpected statement!"); 12822 } 12823 12824 ExprResult VisitExpr(Expr *E) { 12825 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 12826 << E->getSourceRange(); 12827 return ExprError(); 12828 } 12829 12830 ExprResult VisitCallExpr(CallExpr *E); 12831 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 12832 12833 /// Rebuild an expression which simply semantically wraps another 12834 /// expression which it shares the type and value kind of. 12835 template <class T> ExprResult rebuildSugarExpr(T *E) { 12836 ExprResult SubResult = Visit(E->getSubExpr()); 12837 if (SubResult.isInvalid()) return ExprError(); 12838 Expr *SubExpr = SubResult.take(); 12839 E->setSubExpr(SubExpr); 12840 E->setType(SubExpr->getType()); 12841 E->setValueKind(SubExpr->getValueKind()); 12842 assert(E->getObjectKind() == OK_Ordinary); 12843 return E; 12844 } 12845 12846 ExprResult VisitParenExpr(ParenExpr *E) { 12847 return rebuildSugarExpr(E); 12848 } 12849 12850 ExprResult VisitUnaryExtension(UnaryOperator *E) { 12851 return rebuildSugarExpr(E); 12852 } 12853 12854 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 12855 const PointerType *Ptr = DestType->getAs<PointerType>(); 12856 if (!Ptr) { 12857 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 12858 << E->getSourceRange(); 12859 return ExprError(); 12860 } 12861 assert(E->getValueKind() == VK_RValue); 12862 assert(E->getObjectKind() == OK_Ordinary); 12863 E->setType(DestType); 12864 12865 // Build the sub-expression as if it were an object of the pointee type. 12866 DestType = Ptr->getPointeeType(); 12867 ExprResult SubResult = Visit(E->getSubExpr()); 12868 if (SubResult.isInvalid()) return ExprError(); 12869 E->setSubExpr(SubResult.take()); 12870 return E; 12871 } 12872 12873 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 12874 12875 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 12876 12877 ExprResult VisitMemberExpr(MemberExpr *E) { 12878 return resolveDecl(E, E->getMemberDecl()); 12879 } 12880 12881 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 12882 return resolveDecl(E, E->getDecl()); 12883 } 12884 }; 12885 } 12886 12887 /// Rebuilds a call expression which yielded __unknown_anytype. 12888 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 12889 Expr *CalleeExpr = E->getCallee(); 12890 12891 enum FnKind { 12892 FK_MemberFunction, 12893 FK_FunctionPointer, 12894 FK_BlockPointer 12895 }; 12896 12897 FnKind Kind; 12898 QualType CalleeType = CalleeExpr->getType(); 12899 if (CalleeType == S.Context.BoundMemberTy) { 12900 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 12901 Kind = FK_MemberFunction; 12902 CalleeType = Expr::findBoundMemberType(CalleeExpr); 12903 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 12904 CalleeType = Ptr->getPointeeType(); 12905 Kind = FK_FunctionPointer; 12906 } else { 12907 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 12908 Kind = FK_BlockPointer; 12909 } 12910 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 12911 12912 // Verify that this is a legal result type of a function. 12913 if (DestType->isArrayType() || DestType->isFunctionType()) { 12914 unsigned diagID = diag::err_func_returning_array_function; 12915 if (Kind == FK_BlockPointer) 12916 diagID = diag::err_block_returning_array_function; 12917 12918 S.Diag(E->getExprLoc(), diagID) 12919 << DestType->isFunctionType() << DestType; 12920 return ExprError(); 12921 } 12922 12923 // Otherwise, go ahead and set DestType as the call's result. 12924 E->setType(DestType.getNonLValueExprType(S.Context)); 12925 E->setValueKind(Expr::getValueKindForType(DestType)); 12926 assert(E->getObjectKind() == OK_Ordinary); 12927 12928 // Rebuild the function type, replacing the result type with DestType. 12929 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 12930 if (Proto) { 12931 // __unknown_anytype(...) is a special case used by the debugger when 12932 // it has no idea what a function's signature is. 12933 // 12934 // We want to build this call essentially under the K&R 12935 // unprototyped rules, but making a FunctionNoProtoType in C++ 12936 // would foul up all sorts of assumptions. However, we cannot 12937 // simply pass all arguments as variadic arguments, nor can we 12938 // portably just call the function under a non-variadic type; see 12939 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 12940 // However, it turns out that in practice it is generally safe to 12941 // call a function declared as "A foo(B,C,D);" under the prototype 12942 // "A foo(B,C,D,...);". The only known exception is with the 12943 // Windows ABI, where any variadic function is implicitly cdecl 12944 // regardless of its normal CC. Therefore we change the parameter 12945 // types to match the types of the arguments. 12946 // 12947 // This is a hack, but it is far superior to moving the 12948 // corresponding target-specific code from IR-gen to Sema/AST. 12949 12950 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 12951 SmallVector<QualType, 8> ArgTypes; 12952 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 12953 ArgTypes.reserve(E->getNumArgs()); 12954 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 12955 Expr *Arg = E->getArg(i); 12956 QualType ArgType = Arg->getType(); 12957 if (E->isLValue()) { 12958 ArgType = S.Context.getLValueReferenceType(ArgType); 12959 } else if (E->isXValue()) { 12960 ArgType = S.Context.getRValueReferenceType(ArgType); 12961 } 12962 ArgTypes.push_back(ArgType); 12963 } 12964 ParamTypes = ArgTypes; 12965 } 12966 DestType = S.Context.getFunctionType(DestType, ParamTypes, 12967 Proto->getExtProtoInfo()); 12968 } else { 12969 DestType = S.Context.getFunctionNoProtoType(DestType, 12970 FnType->getExtInfo()); 12971 } 12972 12973 // Rebuild the appropriate pointer-to-function type. 12974 switch (Kind) { 12975 case FK_MemberFunction: 12976 // Nothing to do. 12977 break; 12978 12979 case FK_FunctionPointer: 12980 DestType = S.Context.getPointerType(DestType); 12981 break; 12982 12983 case FK_BlockPointer: 12984 DestType = S.Context.getBlockPointerType(DestType); 12985 break; 12986 } 12987 12988 // Finally, we can recurse. 12989 ExprResult CalleeResult = Visit(CalleeExpr); 12990 if (!CalleeResult.isUsable()) return ExprError(); 12991 E->setCallee(CalleeResult.take()); 12992 12993 // Bind a temporary if necessary. 12994 return S.MaybeBindToTemporary(E); 12995 } 12996 12997 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 12998 // Verify that this is a legal result type of a call. 12999 if (DestType->isArrayType() || DestType->isFunctionType()) { 13000 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 13001 << DestType->isFunctionType() << DestType; 13002 return ExprError(); 13003 } 13004 13005 // Rewrite the method result type if available. 13006 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 13007 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 13008 Method->setReturnType(DestType); 13009 } 13010 13011 // Change the type of the message. 13012 E->setType(DestType.getNonReferenceType()); 13013 E->setValueKind(Expr::getValueKindForType(DestType)); 13014 13015 return S.MaybeBindToTemporary(E); 13016 } 13017 13018 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 13019 // The only case we should ever see here is a function-to-pointer decay. 13020 if (E->getCastKind() == CK_FunctionToPointerDecay) { 13021 assert(E->getValueKind() == VK_RValue); 13022 assert(E->getObjectKind() == OK_Ordinary); 13023 13024 E->setType(DestType); 13025 13026 // Rebuild the sub-expression as the pointee (function) type. 13027 DestType = DestType->castAs<PointerType>()->getPointeeType(); 13028 13029 ExprResult Result = Visit(E->getSubExpr()); 13030 if (!Result.isUsable()) return ExprError(); 13031 13032 E->setSubExpr(Result.take()); 13033 return S.Owned(E); 13034 } else if (E->getCastKind() == CK_LValueToRValue) { 13035 assert(E->getValueKind() == VK_RValue); 13036 assert(E->getObjectKind() == OK_Ordinary); 13037 13038 assert(isa<BlockPointerType>(E->getType())); 13039 13040 E->setType(DestType); 13041 13042 // The sub-expression has to be a lvalue reference, so rebuild it as such. 13043 DestType = S.Context.getLValueReferenceType(DestType); 13044 13045 ExprResult Result = Visit(E->getSubExpr()); 13046 if (!Result.isUsable()) return ExprError(); 13047 13048 E->setSubExpr(Result.take()); 13049 return S.Owned(E); 13050 } else { 13051 llvm_unreachable("Unhandled cast type!"); 13052 } 13053 } 13054 13055 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 13056 ExprValueKind ValueKind = VK_LValue; 13057 QualType Type = DestType; 13058 13059 // We know how to make this work for certain kinds of decls: 13060 13061 // - functions 13062 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 13063 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 13064 DestType = Ptr->getPointeeType(); 13065 ExprResult Result = resolveDecl(E, VD); 13066 if (Result.isInvalid()) return ExprError(); 13067 return S.ImpCastExprToType(Result.take(), Type, 13068 CK_FunctionToPointerDecay, VK_RValue); 13069 } 13070 13071 if (!Type->isFunctionType()) { 13072 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 13073 << VD << E->getSourceRange(); 13074 return ExprError(); 13075 } 13076 13077 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 13078 if (MD->isInstance()) { 13079 ValueKind = VK_RValue; 13080 Type = S.Context.BoundMemberTy; 13081 } 13082 13083 // Function references aren't l-values in C. 13084 if (!S.getLangOpts().CPlusPlus) 13085 ValueKind = VK_RValue; 13086 13087 // - variables 13088 } else if (isa<VarDecl>(VD)) { 13089 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 13090 Type = RefTy->getPointeeType(); 13091 } else if (Type->isFunctionType()) { 13092 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 13093 << VD << E->getSourceRange(); 13094 return ExprError(); 13095 } 13096 13097 // - nothing else 13098 } else { 13099 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 13100 << VD << E->getSourceRange(); 13101 return ExprError(); 13102 } 13103 13104 // Modifying the declaration like this is friendly to IR-gen but 13105 // also really dangerous. 13106 VD->setType(DestType); 13107 E->setType(Type); 13108 E->setValueKind(ValueKind); 13109 return S.Owned(E); 13110 } 13111 13112 /// Check a cast of an unknown-any type. We intentionally only 13113 /// trigger this for C-style casts. 13114 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 13115 Expr *CastExpr, CastKind &CastKind, 13116 ExprValueKind &VK, CXXCastPath &Path) { 13117 // Rewrite the casted expression from scratch. 13118 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 13119 if (!result.isUsable()) return ExprError(); 13120 13121 CastExpr = result.take(); 13122 VK = CastExpr->getValueKind(); 13123 CastKind = CK_NoOp; 13124 13125 return CastExpr; 13126 } 13127 13128 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 13129 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 13130 } 13131 13132 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 13133 Expr *arg, QualType ¶mType) { 13134 // If the syntactic form of the argument is not an explicit cast of 13135 // any sort, just do default argument promotion. 13136 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 13137 if (!castArg) { 13138 ExprResult result = DefaultArgumentPromotion(arg); 13139 if (result.isInvalid()) return ExprError(); 13140 paramType = result.get()->getType(); 13141 return result; 13142 } 13143 13144 // Otherwise, use the type that was written in the explicit cast. 13145 assert(!arg->hasPlaceholderType()); 13146 paramType = castArg->getTypeAsWritten(); 13147 13148 // Copy-initialize a parameter of that type. 13149 InitializedEntity entity = 13150 InitializedEntity::InitializeParameter(Context, paramType, 13151 /*consumed*/ false); 13152 return PerformCopyInitialization(entity, callLoc, Owned(arg)); 13153 } 13154 13155 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 13156 Expr *orig = E; 13157 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 13158 while (true) { 13159 E = E->IgnoreParenImpCasts(); 13160 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 13161 E = call->getCallee(); 13162 diagID = diag::err_uncasted_call_of_unknown_any; 13163 } else { 13164 break; 13165 } 13166 } 13167 13168 SourceLocation loc; 13169 NamedDecl *d; 13170 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 13171 loc = ref->getLocation(); 13172 d = ref->getDecl(); 13173 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 13174 loc = mem->getMemberLoc(); 13175 d = mem->getMemberDecl(); 13176 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 13177 diagID = diag::err_uncasted_call_of_unknown_any; 13178 loc = msg->getSelectorStartLoc(); 13179 d = msg->getMethodDecl(); 13180 if (!d) { 13181 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 13182 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 13183 << orig->getSourceRange(); 13184 return ExprError(); 13185 } 13186 } else { 13187 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 13188 << E->getSourceRange(); 13189 return ExprError(); 13190 } 13191 13192 S.Diag(loc, diagID) << d << orig->getSourceRange(); 13193 13194 // Never recoverable. 13195 return ExprError(); 13196 } 13197 13198 /// Check for operands with placeholder types and complain if found. 13199 /// Returns true if there was an error and no recovery was possible. 13200 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 13201 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 13202 if (!placeholderType) return Owned(E); 13203 13204 switch (placeholderType->getKind()) { 13205 13206 // Overloaded expressions. 13207 case BuiltinType::Overload: { 13208 // Try to resolve a single function template specialization. 13209 // This is obligatory. 13210 ExprResult result = Owned(E); 13211 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 13212 return result; 13213 13214 // If that failed, try to recover with a call. 13215 } else { 13216 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 13217 /*complain*/ true); 13218 return result; 13219 } 13220 } 13221 13222 // Bound member functions. 13223 case BuiltinType::BoundMember: { 13224 ExprResult result = Owned(E); 13225 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function), 13226 /*complain*/ true); 13227 return result; 13228 } 13229 13230 // ARC unbridged casts. 13231 case BuiltinType::ARCUnbridgedCast: { 13232 Expr *realCast = stripARCUnbridgedCast(E); 13233 diagnoseARCUnbridgedCast(realCast); 13234 return Owned(realCast); 13235 } 13236 13237 // Expressions of unknown type. 13238 case BuiltinType::UnknownAny: 13239 return diagnoseUnknownAnyExpr(*this, E); 13240 13241 // Pseudo-objects. 13242 case BuiltinType::PseudoObject: 13243 return checkPseudoObjectRValue(E); 13244 13245 case BuiltinType::BuiltinFn: 13246 Diag(E->getLocStart(), diag::err_builtin_fn_use); 13247 return ExprError(); 13248 13249 // Everything else should be impossible. 13250 #define BUILTIN_TYPE(Id, SingletonId) \ 13251 case BuiltinType::Id: 13252 #define PLACEHOLDER_TYPE(Id, SingletonId) 13253 #include "clang/AST/BuiltinTypes.def" 13254 break; 13255 } 13256 13257 llvm_unreachable("invalid placeholder type!"); 13258 } 13259 13260 bool Sema::CheckCaseExpression(Expr *E) { 13261 if (E->isTypeDependent()) 13262 return true; 13263 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 13264 return E->getType()->isIntegralOrEnumerationType(); 13265 return false; 13266 } 13267 13268 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 13269 ExprResult 13270 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 13271 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 13272 "Unknown Objective-C Boolean value!"); 13273 QualType BoolT = Context.ObjCBuiltinBoolTy; 13274 if (!Context.getBOOLDecl()) { 13275 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 13276 Sema::LookupOrdinaryName); 13277 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 13278 NamedDecl *ND = Result.getFoundDecl(); 13279 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 13280 Context.setBOOLDecl(TD); 13281 } 13282 } 13283 if (Context.getBOOLDecl()) 13284 BoolT = Context.getBOOLType(); 13285 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, 13286 BoolT, OpLoc)); 13287 } 13288