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 bool ObjCPropertyAccess) { 88 // See if this declaration is unavailable or deprecated. 89 std::string Message; 90 91 // Forward class declarations get their attributes from their definition. 92 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) { 93 if (IDecl->getDefinition()) 94 D = IDecl->getDefinition(); 95 } 96 AvailabilityResult Result = D->getAvailability(&Message); 97 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 98 if (Result == AR_Available) { 99 const DeclContext *DC = ECD->getDeclContext(); 100 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 101 Result = TheEnumDecl->getAvailability(&Message); 102 } 103 104 const ObjCPropertyDecl *ObjCPDecl = nullptr; 105 if (Result == AR_Deprecated || Result == AR_Unavailable) { 106 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 107 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 108 AvailabilityResult PDeclResult = PD->getAvailability(nullptr); 109 if (PDeclResult == Result) 110 ObjCPDecl = PD; 111 } 112 } 113 } 114 115 switch (Result) { 116 case AR_Available: 117 case AR_NotYetIntroduced: 118 break; 119 120 case AR_Deprecated: 121 if (S.getCurContextAvailability() != AR_Deprecated) 122 S.EmitAvailabilityWarning(Sema::AD_Deprecation, 123 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 124 ObjCPropertyAccess); 125 break; 126 127 case AR_Unavailable: 128 if (S.getCurContextAvailability() != AR_Unavailable) 129 S.EmitAvailabilityWarning(Sema::AD_Unavailable, 130 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 131 ObjCPropertyAccess); 132 break; 133 134 } 135 return Result; 136 } 137 138 /// \brief Emit a note explaining that this function is deleted. 139 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 140 assert(Decl->isDeleted()); 141 142 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 143 144 if (Method && Method->isDeleted() && Method->isDefaulted()) { 145 // If the method was explicitly defaulted, point at that declaration. 146 if (!Method->isImplicit()) 147 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 148 149 // Try to diagnose why this special member function was implicitly 150 // deleted. This might fail, if that reason no longer applies. 151 CXXSpecialMember CSM = getSpecialMember(Method); 152 if (CSM != CXXInvalid) 153 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true); 154 155 return; 156 } 157 158 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) { 159 if (CXXConstructorDecl *BaseCD = 160 const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) { 161 Diag(Decl->getLocation(), diag::note_inherited_deleted_here); 162 if (BaseCD->isDeleted()) { 163 NoteDeletedFunction(BaseCD); 164 } else { 165 // FIXME: An explanation of why exactly it can't be inherited 166 // would be nice. 167 Diag(BaseCD->getLocation(), diag::note_cannot_inherit); 168 } 169 return; 170 } 171 } 172 173 Diag(Decl->getLocation(), diag::note_availability_specified_here) 174 << Decl << true; 175 } 176 177 /// \brief Determine whether a FunctionDecl was ever declared with an 178 /// explicit storage class. 179 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 180 for (auto I : D->redecls()) { 181 if (I->getStorageClass() != SC_None) 182 return true; 183 } 184 return false; 185 } 186 187 /// \brief Check whether we're in an extern inline function and referring to a 188 /// variable or function with internal linkage (C11 6.7.4p3). 189 /// 190 /// This is only a warning because we used to silently accept this code, but 191 /// in many cases it will not behave correctly. This is not enabled in C++ mode 192 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 193 /// and so while there may still be user mistakes, most of the time we can't 194 /// prove that there are errors. 195 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 196 const NamedDecl *D, 197 SourceLocation Loc) { 198 // This is disabled under C++; there are too many ways for this to fire in 199 // contexts where the warning is a false positive, or where it is technically 200 // correct but benign. 201 if (S.getLangOpts().CPlusPlus) 202 return; 203 204 // Check if this is an inlined function or method. 205 FunctionDecl *Current = S.getCurFunctionDecl(); 206 if (!Current) 207 return; 208 if (!Current->isInlined()) 209 return; 210 if (!Current->isExternallyVisible()) 211 return; 212 213 // Check if the decl has internal linkage. 214 if (D->getFormalLinkage() != InternalLinkage) 215 return; 216 217 // Downgrade from ExtWarn to Extension if 218 // (1) the supposedly external inline function is in the main file, 219 // and probably won't be included anywhere else. 220 // (2) the thing we're referencing is a pure function. 221 // (3) the thing we're referencing is another inline function. 222 // This last can give us false negatives, but it's better than warning on 223 // wrappers for simple C library functions. 224 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 225 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 226 if (!DowngradeWarning && UsedFn) 227 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 228 229 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline 230 : diag::warn_internal_in_extern_inline) 231 << /*IsVar=*/!UsedFn << D; 232 233 S.MaybeSuggestAddingStaticToDecl(Current); 234 235 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 236 << D; 237 } 238 239 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 240 const FunctionDecl *First = Cur->getFirstDecl(); 241 242 // Suggest "static" on the function, if possible. 243 if (!hasAnyExplicitStorageClass(First)) { 244 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 245 Diag(DeclBegin, diag::note_convert_inline_to_static) 246 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 247 } 248 } 249 250 /// \brief Determine whether the use of this declaration is valid, and 251 /// emit any corresponding diagnostics. 252 /// 253 /// This routine diagnoses various problems with referencing 254 /// declarations that can occur when using a declaration. For example, 255 /// it might warn if a deprecated or unavailable declaration is being 256 /// used, or produce an error (and return true) if a C++0x deleted 257 /// function is being used. 258 /// 259 /// \returns true if there was an error (this declaration cannot be 260 /// referenced), false otherwise. 261 /// 262 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 263 const ObjCInterfaceDecl *UnknownObjCClass, 264 bool ObjCPropertyAccess) { 265 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 266 // If there were any diagnostics suppressed by template argument deduction, 267 // emit them now. 268 SuppressedDiagnosticsMap::iterator 269 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 270 if (Pos != SuppressedDiagnostics.end()) { 271 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second; 272 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I) 273 Diag(Suppressed[I].first, Suppressed[I].second); 274 275 // Clear out the list of suppressed diagnostics, so that we don't emit 276 // them again for this specialization. However, we don't obsolete this 277 // entry from the table, because we want to avoid ever emitting these 278 // diagnostics again. 279 Suppressed.clear(); 280 } 281 282 // C++ [basic.start.main]p3: 283 // The function 'main' shall not be used within a program. 284 if (cast<FunctionDecl>(D)->isMain()) 285 Diag(Loc, diag::ext_main_used); 286 } 287 288 // See if this is an auto-typed variable whose initializer we are parsing. 289 if (ParsingInitForAutoVars.count(D)) { 290 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 291 << D->getDeclName(); 292 return true; 293 } 294 295 // See if this is a deleted function. 296 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 297 if (FD->isDeleted()) { 298 Diag(Loc, diag::err_deleted_function_use); 299 NoteDeletedFunction(FD); 300 return true; 301 } 302 303 // If the function has a deduced return type, and we can't deduce it, 304 // then we can't use it either. 305 if (getLangOpts().CPlusPlus1y && FD->getReturnType()->isUndeducedType() && 306 DeduceReturnType(FD, Loc)) 307 return true; 308 } 309 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, ObjCPropertyAccess); 310 311 DiagnoseUnusedOfDecl(*this, D, Loc); 312 313 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 314 315 return false; 316 } 317 318 /// \brief Retrieve the message suffix that should be added to a 319 /// diagnostic complaining about the given function being deleted or 320 /// unavailable. 321 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 322 std::string Message; 323 if (FD->getAvailability(&Message)) 324 return ": " + Message; 325 326 return std::string(); 327 } 328 329 /// DiagnoseSentinelCalls - This routine checks whether a call or 330 /// message-send is to a declaration with the sentinel attribute, and 331 /// if so, it checks that the requirements of the sentinel are 332 /// satisfied. 333 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 334 ArrayRef<Expr *> Args) { 335 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 336 if (!attr) 337 return; 338 339 // The number of formal parameters of the declaration. 340 unsigned numFormalParams; 341 342 // The kind of declaration. This is also an index into a %select in 343 // the diagnostic. 344 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 345 346 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 347 numFormalParams = MD->param_size(); 348 calleeType = CT_Method; 349 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 350 numFormalParams = FD->param_size(); 351 calleeType = CT_Function; 352 } else if (isa<VarDecl>(D)) { 353 QualType type = cast<ValueDecl>(D)->getType(); 354 const FunctionType *fn = nullptr; 355 if (const PointerType *ptr = type->getAs<PointerType>()) { 356 fn = ptr->getPointeeType()->getAs<FunctionType>(); 357 if (!fn) return; 358 calleeType = CT_Function; 359 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 360 fn = ptr->getPointeeType()->castAs<FunctionType>(); 361 calleeType = CT_Block; 362 } else { 363 return; 364 } 365 366 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 367 numFormalParams = proto->getNumParams(); 368 } else { 369 numFormalParams = 0; 370 } 371 } else { 372 return; 373 } 374 375 // "nullPos" is the number of formal parameters at the end which 376 // effectively count as part of the variadic arguments. This is 377 // useful if you would prefer to not have *any* formal parameters, 378 // but the language forces you to have at least one. 379 unsigned nullPos = attr->getNullPos(); 380 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 381 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 382 383 // The number of arguments which should follow the sentinel. 384 unsigned numArgsAfterSentinel = attr->getSentinel(); 385 386 // If there aren't enough arguments for all the formal parameters, 387 // the sentinel, and the args after the sentinel, complain. 388 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 389 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 390 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 391 return; 392 } 393 394 // Otherwise, find the sentinel expression. 395 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 396 if (!sentinelExpr) return; 397 if (sentinelExpr->isValueDependent()) return; 398 if (Context.isSentinelNullExpr(sentinelExpr)) return; 399 400 // Pick a reasonable string to insert. Optimistically use 'nil' or 401 // 'NULL' if those are actually defined in the context. Only use 402 // 'nil' for ObjC methods, where it's much more likely that the 403 // variadic arguments form a list of object pointers. 404 SourceLocation MissingNilLoc 405 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd()); 406 std::string NullValue; 407 if (calleeType == CT_Method && 408 PP.getIdentifierInfo("nil")->hasMacroDefinition()) 409 NullValue = "nil"; 410 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition()) 411 NullValue = "NULL"; 412 else 413 NullValue = "(void*) 0"; 414 415 if (MissingNilLoc.isInvalid()) 416 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 417 else 418 Diag(MissingNilLoc, diag::warn_missing_sentinel) 419 << int(calleeType) 420 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 421 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 422 } 423 424 SourceRange Sema::getExprRange(Expr *E) const { 425 return E ? E->getSourceRange() : SourceRange(); 426 } 427 428 //===----------------------------------------------------------------------===// 429 // Standard Promotions and Conversions 430 //===----------------------------------------------------------------------===// 431 432 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 433 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) { 434 // Handle any placeholder expressions which made it here. 435 if (E->getType()->isPlaceholderType()) { 436 ExprResult result = CheckPlaceholderExpr(E); 437 if (result.isInvalid()) return ExprError(); 438 E = result.get(); 439 } 440 441 QualType Ty = E->getType(); 442 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 443 444 if (Ty->isFunctionType()) { 445 // If we are here, we are not calling a function but taking 446 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 447 if (getLangOpts().OpenCL) { 448 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 449 return ExprError(); 450 } 451 E = ImpCastExprToType(E, Context.getPointerType(Ty), 452 CK_FunctionToPointerDecay).get(); 453 } else if (Ty->isArrayType()) { 454 // In C90 mode, arrays only promote to pointers if the array expression is 455 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 456 // type 'array of type' is converted to an expression that has type 'pointer 457 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 458 // that has type 'array of type' ...". The relevant change is "an lvalue" 459 // (C90) to "an expression" (C99). 460 // 461 // C++ 4.2p1: 462 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 463 // T" can be converted to an rvalue of type "pointer to T". 464 // 465 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 466 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 467 CK_ArrayToPointerDecay).get(); 468 } 469 return E; 470 } 471 472 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 473 // Check to see if we are dereferencing a null pointer. If so, 474 // and if not volatile-qualified, this is undefined behavior that the 475 // optimizer will delete, so warn about it. People sometimes try to use this 476 // to get a deterministic trap and are surprised by clang's behavior. This 477 // only handles the pattern "*null", which is a very syntactic check. 478 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 479 if (UO->getOpcode() == UO_Deref && 480 UO->getSubExpr()->IgnoreParenCasts()-> 481 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 482 !UO->getType().isVolatileQualified()) { 483 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 484 S.PDiag(diag::warn_indirection_through_null) 485 << UO->getSubExpr()->getSourceRange()); 486 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 487 S.PDiag(diag::note_indirection_through_null)); 488 } 489 } 490 491 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 492 SourceLocation AssignLoc, 493 const Expr* RHS) { 494 const ObjCIvarDecl *IV = OIRE->getDecl(); 495 if (!IV) 496 return; 497 498 DeclarationName MemberName = IV->getDeclName(); 499 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 500 if (!Member || !Member->isStr("isa")) 501 return; 502 503 const Expr *Base = OIRE->getBase(); 504 QualType BaseType = Base->getType(); 505 if (OIRE->isArrow()) 506 BaseType = BaseType->getPointeeType(); 507 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 508 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 509 ObjCInterfaceDecl *ClassDeclared = nullptr; 510 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 511 if (!ClassDeclared->getSuperClass() 512 && (*ClassDeclared->ivar_begin()) == IV) { 513 if (RHS) { 514 NamedDecl *ObjectSetClass = 515 S.LookupSingleName(S.TUScope, 516 &S.Context.Idents.get("object_setClass"), 517 SourceLocation(), S.LookupOrdinaryName); 518 if (ObjectSetClass) { 519 SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd()); 520 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 521 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 522 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 523 AssignLoc), ",") << 524 FixItHint::CreateInsertion(RHSLocEnd, ")"); 525 } 526 else 527 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 528 } else { 529 NamedDecl *ObjectGetClass = 530 S.LookupSingleName(S.TUScope, 531 &S.Context.Idents.get("object_getClass"), 532 SourceLocation(), S.LookupOrdinaryName); 533 if (ObjectGetClass) 534 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 535 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 536 FixItHint::CreateReplacement( 537 SourceRange(OIRE->getOpLoc(), 538 OIRE->getLocEnd()), ")"); 539 else 540 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 541 } 542 S.Diag(IV->getLocation(), diag::note_ivar_decl); 543 } 544 } 545 } 546 547 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 548 // Handle any placeholder expressions which made it here. 549 if (E->getType()->isPlaceholderType()) { 550 ExprResult result = CheckPlaceholderExpr(E); 551 if (result.isInvalid()) return ExprError(); 552 E = result.get(); 553 } 554 555 // C++ [conv.lval]p1: 556 // A glvalue of a non-function, non-array type T can be 557 // converted to a prvalue. 558 if (!E->isGLValue()) return E; 559 560 QualType T = E->getType(); 561 assert(!T.isNull() && "r-value conversion on typeless expression?"); 562 563 // We don't want to throw lvalue-to-rvalue casts on top of 564 // expressions of certain types in C++. 565 if (getLangOpts().CPlusPlus && 566 (E->getType() == Context.OverloadTy || 567 T->isDependentType() || 568 T->isRecordType())) 569 return E; 570 571 // The C standard is actually really unclear on this point, and 572 // DR106 tells us what the result should be but not why. It's 573 // generally best to say that void types just doesn't undergo 574 // lvalue-to-rvalue at all. Note that expressions of unqualified 575 // 'void' type are never l-values, but qualified void can be. 576 if (T->isVoidType()) 577 return E; 578 579 // OpenCL usually rejects direct accesses to values of 'half' type. 580 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 581 T->isHalfType()) { 582 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 583 << 0 << T; 584 return ExprError(); 585 } 586 587 CheckForNullPointerDereference(*this, E); 588 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 589 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 590 &Context.Idents.get("object_getClass"), 591 SourceLocation(), LookupOrdinaryName); 592 if (ObjectGetClass) 593 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 594 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 595 FixItHint::CreateReplacement( 596 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 597 else 598 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 599 } 600 else if (const ObjCIvarRefExpr *OIRE = 601 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 602 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 603 604 // C++ [conv.lval]p1: 605 // [...] If T is a non-class type, the type of the prvalue is the 606 // cv-unqualified version of T. Otherwise, the type of the 607 // rvalue is T. 608 // 609 // C99 6.3.2.1p2: 610 // If the lvalue has qualified type, the value has the unqualified 611 // version of the type of the lvalue; otherwise, the value has the 612 // type of the lvalue. 613 if (T.hasQualifiers()) 614 T = T.getUnqualifiedType(); 615 616 UpdateMarkingForLValueToRValue(E); 617 618 // Loading a __weak object implicitly retains the value, so we need a cleanup to 619 // balance that. 620 if (getLangOpts().ObjCAutoRefCount && 621 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 622 ExprNeedsCleanups = true; 623 624 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 625 nullptr, VK_RValue); 626 627 // C11 6.3.2.1p2: 628 // ... if the lvalue has atomic type, the value has the non-atomic version 629 // of the type of the lvalue ... 630 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 631 T = Atomic->getValueType().getUnqualifiedType(); 632 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 633 nullptr, VK_RValue); 634 } 635 636 return Res; 637 } 638 639 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 640 ExprResult Res = DefaultFunctionArrayConversion(E); 641 if (Res.isInvalid()) 642 return ExprError(); 643 Res = DefaultLvalueConversion(Res.get()); 644 if (Res.isInvalid()) 645 return ExprError(); 646 return Res; 647 } 648 649 /// CallExprUnaryConversions - a special case of an unary conversion 650 /// performed on a function designator of a call expression. 651 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 652 QualType Ty = E->getType(); 653 ExprResult Res = E; 654 // Only do implicit cast for a function type, but not for a pointer 655 // to function type. 656 if (Ty->isFunctionType()) { 657 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 658 CK_FunctionToPointerDecay).get(); 659 if (Res.isInvalid()) 660 return ExprError(); 661 } 662 Res = DefaultLvalueConversion(Res.get()); 663 if (Res.isInvalid()) 664 return ExprError(); 665 return Res.get(); 666 } 667 668 /// UsualUnaryConversions - Performs various conversions that are common to most 669 /// operators (C99 6.3). The conversions of array and function types are 670 /// sometimes suppressed. For example, the array->pointer conversion doesn't 671 /// apply if the array is an argument to the sizeof or address (&) operators. 672 /// In these instances, this routine should *not* be called. 673 ExprResult Sema::UsualUnaryConversions(Expr *E) { 674 // First, convert to an r-value. 675 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 676 if (Res.isInvalid()) 677 return ExprError(); 678 E = Res.get(); 679 680 QualType Ty = E->getType(); 681 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 682 683 // Half FP have to be promoted to float unless it is natively supported 684 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 685 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 686 687 // Try to perform integral promotions if the object has a theoretically 688 // promotable type. 689 if (Ty->isIntegralOrUnscopedEnumerationType()) { 690 // C99 6.3.1.1p2: 691 // 692 // The following may be used in an expression wherever an int or 693 // unsigned int may be used: 694 // - an object or expression with an integer type whose integer 695 // conversion rank is less than or equal to the rank of int 696 // and unsigned int. 697 // - A bit-field of type _Bool, int, signed int, or unsigned int. 698 // 699 // If an int can represent all values of the original type, the 700 // value is converted to an int; otherwise, it is converted to an 701 // unsigned int. These are called the integer promotions. All 702 // other types are unchanged by the integer promotions. 703 704 QualType PTy = Context.isPromotableBitField(E); 705 if (!PTy.isNull()) { 706 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 707 return E; 708 } 709 if (Ty->isPromotableIntegerType()) { 710 QualType PT = Context.getPromotedIntegerType(Ty); 711 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 712 return E; 713 } 714 } 715 return E; 716 } 717 718 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 719 /// do not have a prototype. Arguments that have type float or __fp16 720 /// are promoted to double. All other argument types are converted by 721 /// UsualUnaryConversions(). 722 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 723 QualType Ty = E->getType(); 724 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 725 726 ExprResult Res = UsualUnaryConversions(E); 727 if (Res.isInvalid()) 728 return ExprError(); 729 E = Res.get(); 730 731 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 732 // double. 733 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 734 if (BTy && (BTy->getKind() == BuiltinType::Half || 735 BTy->getKind() == BuiltinType::Float)) 736 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 737 738 // C++ performs lvalue-to-rvalue conversion as a default argument 739 // promotion, even on class types, but note: 740 // C++11 [conv.lval]p2: 741 // When an lvalue-to-rvalue conversion occurs in an unevaluated 742 // operand or a subexpression thereof the value contained in the 743 // referenced object is not accessed. Otherwise, if the glvalue 744 // has a class type, the conversion copy-initializes a temporary 745 // of type T from the glvalue and the result of the conversion 746 // is a prvalue for the temporary. 747 // FIXME: add some way to gate this entire thing for correctness in 748 // potentially potentially evaluated contexts. 749 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 750 ExprResult Temp = PerformCopyInitialization( 751 InitializedEntity::InitializeTemporary(E->getType()), 752 E->getExprLoc(), E); 753 if (Temp.isInvalid()) 754 return ExprError(); 755 E = Temp.get(); 756 } 757 758 return E; 759 } 760 761 /// Determine the degree of POD-ness for an expression. 762 /// Incomplete types are considered POD, since this check can be performed 763 /// when we're in an unevaluated context. 764 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 765 if (Ty->isIncompleteType()) { 766 // C++11 [expr.call]p7: 767 // After these conversions, if the argument does not have arithmetic, 768 // enumeration, pointer, pointer to member, or class type, the program 769 // is ill-formed. 770 // 771 // Since we've already performed array-to-pointer and function-to-pointer 772 // decay, the only such type in C++ is cv void. This also handles 773 // initializer lists as variadic arguments. 774 if (Ty->isVoidType()) 775 return VAK_Invalid; 776 777 if (Ty->isObjCObjectType()) 778 return VAK_Invalid; 779 return VAK_Valid; 780 } 781 782 if (Ty.isCXX98PODType(Context)) 783 return VAK_Valid; 784 785 // C++11 [expr.call]p7: 786 // Passing a potentially-evaluated argument of class type (Clause 9) 787 // having a non-trivial copy constructor, a non-trivial move constructor, 788 // or a non-trivial destructor, with no corresponding parameter, 789 // is conditionally-supported with implementation-defined semantics. 790 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 791 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 792 if (!Record->hasNonTrivialCopyConstructor() && 793 !Record->hasNonTrivialMoveConstructor() && 794 !Record->hasNonTrivialDestructor()) 795 return VAK_ValidInCXX11; 796 797 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 798 return VAK_Valid; 799 800 if (Ty->isObjCObjectType()) 801 return VAK_Invalid; 802 803 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 804 // permitted to reject them. We should consider doing so. 805 return VAK_Undefined; 806 } 807 808 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 809 // Don't allow one to pass an Objective-C interface to a vararg. 810 const QualType &Ty = E->getType(); 811 VarArgKind VAK = isValidVarArgType(Ty); 812 813 // Complain about passing non-POD types through varargs. 814 switch (VAK) { 815 case VAK_ValidInCXX11: 816 DiagRuntimeBehavior( 817 E->getLocStart(), nullptr, 818 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 819 << Ty << CT); 820 // Fall through. 821 case VAK_Valid: 822 if (Ty->isRecordType()) { 823 // This is unlikely to be what the user intended. If the class has a 824 // 'c_str' member function, the user probably meant to call that. 825 DiagRuntimeBehavior(E->getLocStart(), nullptr, 826 PDiag(diag::warn_pass_class_arg_to_vararg) 827 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 828 } 829 break; 830 831 case VAK_Undefined: 832 DiagRuntimeBehavior( 833 E->getLocStart(), nullptr, 834 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 835 << getLangOpts().CPlusPlus11 << Ty << CT); 836 break; 837 838 case VAK_Invalid: 839 if (Ty->isObjCObjectType()) 840 DiagRuntimeBehavior( 841 E->getLocStart(), nullptr, 842 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 843 << Ty << CT); 844 else 845 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 846 << isa<InitListExpr>(E) << Ty << CT; 847 break; 848 } 849 } 850 851 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 852 /// will create a trap if the resulting type is not a POD type. 853 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 854 FunctionDecl *FDecl) { 855 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 856 // Strip the unbridged-cast placeholder expression off, if applicable. 857 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 858 (CT == VariadicMethod || 859 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 860 E = stripARCUnbridgedCast(E); 861 862 // Otherwise, do normal placeholder checking. 863 } else { 864 ExprResult ExprRes = CheckPlaceholderExpr(E); 865 if (ExprRes.isInvalid()) 866 return ExprError(); 867 E = ExprRes.get(); 868 } 869 } 870 871 ExprResult ExprRes = DefaultArgumentPromotion(E); 872 if (ExprRes.isInvalid()) 873 return ExprError(); 874 E = ExprRes.get(); 875 876 // Diagnostics regarding non-POD argument types are 877 // emitted along with format string checking in Sema::CheckFunctionCall(). 878 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 879 // Turn this into a trap. 880 CXXScopeSpec SS; 881 SourceLocation TemplateKWLoc; 882 UnqualifiedId Name; 883 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 884 E->getLocStart()); 885 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 886 Name, true, false); 887 if (TrapFn.isInvalid()) 888 return ExprError(); 889 890 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 891 E->getLocStart(), None, 892 E->getLocEnd()); 893 if (Call.isInvalid()) 894 return ExprError(); 895 896 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 897 Call.get(), E); 898 if (Comma.isInvalid()) 899 return ExprError(); 900 return Comma.get(); 901 } 902 903 if (!getLangOpts().CPlusPlus && 904 RequireCompleteType(E->getExprLoc(), E->getType(), 905 diag::err_call_incomplete_argument)) 906 return ExprError(); 907 908 return E; 909 } 910 911 /// \brief Converts an integer to complex float type. Helper function of 912 /// UsualArithmeticConversions() 913 /// 914 /// \return false if the integer expression is an integer type and is 915 /// successfully converted to the complex type. 916 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 917 ExprResult &ComplexExpr, 918 QualType IntTy, 919 QualType ComplexTy, 920 bool SkipCast) { 921 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 922 if (SkipCast) return false; 923 if (IntTy->isIntegerType()) { 924 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 925 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 926 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 927 CK_FloatingRealToComplex); 928 } else { 929 assert(IntTy->isComplexIntegerType()); 930 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 931 CK_IntegralComplexToFloatingComplex); 932 } 933 return false; 934 } 935 936 /// \brief Takes two complex float types and converts them to the same type. 937 /// Helper function of UsualArithmeticConversions() 938 static QualType 939 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS, 940 ExprResult &RHS, QualType LHSType, 941 QualType RHSType, 942 bool IsCompAssign) { 943 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 944 945 if (order < 0) { 946 // _Complex float -> _Complex double 947 if (!IsCompAssign) 948 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingComplexCast); 949 return RHSType; 950 } 951 if (order > 0) 952 // _Complex float -> _Complex double 953 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingComplexCast); 954 return LHSType; 955 } 956 957 /// \brief Converts otherExpr to complex float and promotes complexExpr if 958 /// necessary. Helper function of UsualArithmeticConversions() 959 static QualType handleOtherComplexFloatConversion(Sema &S, 960 ExprResult &ComplexExpr, 961 ExprResult &OtherExpr, 962 QualType ComplexTy, 963 QualType OtherTy, 964 bool ConvertComplexExpr, 965 bool ConvertOtherExpr) { 966 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy); 967 968 // If just the complexExpr is complex, the otherExpr needs to be converted, 969 // and the complexExpr might need to be promoted. 970 if (order > 0) { // complexExpr is wider 971 // float -> _Complex double 972 if (ConvertOtherExpr) { 973 QualType fp = cast<ComplexType>(ComplexTy)->getElementType(); 974 OtherExpr = S.ImpCastExprToType(OtherExpr.get(), fp, CK_FloatingCast); 975 OtherExpr = S.ImpCastExprToType(OtherExpr.get(), ComplexTy, 976 CK_FloatingRealToComplex); 977 } 978 return ComplexTy; 979 } 980 981 // otherTy is at least as wide. Find its corresponding complex type. 982 QualType result = (order == 0 ? ComplexTy : 983 S.Context.getComplexType(OtherTy)); 984 985 // double -> _Complex double 986 if (ConvertOtherExpr) 987 OtherExpr = S.ImpCastExprToType(OtherExpr.get(), result, 988 CK_FloatingRealToComplex); 989 990 // _Complex float -> _Complex double 991 if (ConvertComplexExpr && order < 0) 992 ComplexExpr = S.ImpCastExprToType(ComplexExpr.get(), result, 993 CK_FloatingComplexCast); 994 995 return result; 996 } 997 998 /// \brief Handle arithmetic conversion with complex types. Helper function of 999 /// UsualArithmeticConversions() 1000 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1001 ExprResult &RHS, QualType LHSType, 1002 QualType RHSType, 1003 bool IsCompAssign) { 1004 // if we have an integer operand, the result is the complex type. 1005 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1006 /*skipCast*/false)) 1007 return LHSType; 1008 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1009 /*skipCast*/IsCompAssign)) 1010 return RHSType; 1011 1012 // This handles complex/complex, complex/float, or float/complex. 1013 // When both operands are complex, the shorter operand is converted to the 1014 // type of the longer, and that is the type of the result. This corresponds 1015 // to what is done when combining two real floating-point operands. 1016 // The fun begins when size promotion occur across type domains. 1017 // From H&S 6.3.4: When one operand is complex and the other is a real 1018 // floating-point type, the less precise type is converted, within it's 1019 // real or complex domain, to the precision of the other type. For example, 1020 // when combining a "long double" with a "double _Complex", the 1021 // "double _Complex" is promoted to "long double _Complex". 1022 1023 bool LHSComplexFloat = LHSType->isComplexType(); 1024 bool RHSComplexFloat = RHSType->isComplexType(); 1025 1026 // If both are complex, just cast to the more precise type. 1027 if (LHSComplexFloat && RHSComplexFloat) 1028 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS, 1029 LHSType, RHSType, 1030 IsCompAssign); 1031 1032 // If only one operand is complex, promote it if necessary and convert the 1033 // other operand to complex. 1034 if (LHSComplexFloat) 1035 return handleOtherComplexFloatConversion( 1036 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign, 1037 /*convertOtherExpr*/ true); 1038 1039 assert(RHSComplexFloat); 1040 return handleOtherComplexFloatConversion( 1041 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true, 1042 /*convertOtherExpr*/ !IsCompAssign); 1043 } 1044 1045 /// \brief Hande arithmetic conversion from integer to float. Helper function 1046 /// of UsualArithmeticConversions() 1047 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1048 ExprResult &IntExpr, 1049 QualType FloatTy, QualType IntTy, 1050 bool ConvertFloat, bool ConvertInt) { 1051 if (IntTy->isIntegerType()) { 1052 if (ConvertInt) 1053 // Convert intExpr to the lhs floating point type. 1054 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1055 CK_IntegralToFloating); 1056 return FloatTy; 1057 } 1058 1059 // Convert both sides to the appropriate complex float. 1060 assert(IntTy->isComplexIntegerType()); 1061 QualType result = S.Context.getComplexType(FloatTy); 1062 1063 // _Complex int -> _Complex float 1064 if (ConvertInt) 1065 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1066 CK_IntegralComplexToFloatingComplex); 1067 1068 // float -> _Complex float 1069 if (ConvertFloat) 1070 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1071 CK_FloatingRealToComplex); 1072 1073 return result; 1074 } 1075 1076 /// \brief Handle arithmethic conversion with floating point types. Helper 1077 /// function of UsualArithmeticConversions() 1078 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1079 ExprResult &RHS, QualType LHSType, 1080 QualType RHSType, bool IsCompAssign) { 1081 bool LHSFloat = LHSType->isRealFloatingType(); 1082 bool RHSFloat = RHSType->isRealFloatingType(); 1083 1084 // If we have two real floating types, convert the smaller operand 1085 // to the bigger result. 1086 if (LHSFloat && RHSFloat) { 1087 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1088 if (order > 0) { 1089 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1090 return LHSType; 1091 } 1092 1093 assert(order < 0 && "illegal float comparison"); 1094 if (!IsCompAssign) 1095 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1096 return RHSType; 1097 } 1098 1099 if (LHSFloat) 1100 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1101 /*convertFloat=*/!IsCompAssign, 1102 /*convertInt=*/ true); 1103 assert(RHSFloat); 1104 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1105 /*convertInt=*/ true, 1106 /*convertFloat=*/!IsCompAssign); 1107 } 1108 1109 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1110 1111 namespace { 1112 /// These helper callbacks are placed in an anonymous namespace to 1113 /// permit their use as function template parameters. 1114 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1115 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1116 } 1117 1118 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1119 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1120 CK_IntegralComplexCast); 1121 } 1122 } 1123 1124 /// \brief Handle integer arithmetic conversions. Helper function of 1125 /// UsualArithmeticConversions() 1126 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1127 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1128 ExprResult &RHS, QualType LHSType, 1129 QualType RHSType, bool IsCompAssign) { 1130 // The rules for this case are in C99 6.3.1.8 1131 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1132 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1133 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1134 if (LHSSigned == RHSSigned) { 1135 // Same signedness; use the higher-ranked type 1136 if (order >= 0) { 1137 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1138 return LHSType; 1139 } else if (!IsCompAssign) 1140 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1141 return RHSType; 1142 } else if (order != (LHSSigned ? 1 : -1)) { 1143 // The unsigned type has greater than or equal rank to the 1144 // signed type, so use the unsigned type 1145 if (RHSSigned) { 1146 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1147 return LHSType; 1148 } else if (!IsCompAssign) 1149 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1150 return RHSType; 1151 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1152 // The two types are different widths; if we are here, that 1153 // means the signed type is larger than the unsigned type, so 1154 // use the signed type. 1155 if (LHSSigned) { 1156 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1157 return LHSType; 1158 } else if (!IsCompAssign) 1159 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1160 return RHSType; 1161 } else { 1162 // The signed type is higher-ranked than the unsigned type, 1163 // but isn't actually any bigger (like unsigned int and long 1164 // on most 32-bit systems). Use the unsigned type corresponding 1165 // to the signed type. 1166 QualType result = 1167 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1168 RHS = (*doRHSCast)(S, RHS.get(), result); 1169 if (!IsCompAssign) 1170 LHS = (*doLHSCast)(S, LHS.get(), result); 1171 return result; 1172 } 1173 } 1174 1175 /// \brief Handle conversions with GCC complex int extension. Helper function 1176 /// of UsualArithmeticConversions() 1177 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1178 ExprResult &RHS, QualType LHSType, 1179 QualType RHSType, 1180 bool IsCompAssign) { 1181 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1182 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1183 1184 if (LHSComplexInt && RHSComplexInt) { 1185 QualType LHSEltType = LHSComplexInt->getElementType(); 1186 QualType RHSEltType = RHSComplexInt->getElementType(); 1187 QualType ScalarType = 1188 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1189 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1190 1191 return S.Context.getComplexType(ScalarType); 1192 } 1193 1194 if (LHSComplexInt) { 1195 QualType LHSEltType = LHSComplexInt->getElementType(); 1196 QualType ScalarType = 1197 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1198 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1199 QualType ComplexType = S.Context.getComplexType(ScalarType); 1200 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1201 CK_IntegralRealToComplex); 1202 1203 return ComplexType; 1204 } 1205 1206 assert(RHSComplexInt); 1207 1208 QualType RHSEltType = RHSComplexInt->getElementType(); 1209 QualType ScalarType = 1210 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1211 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1212 QualType ComplexType = S.Context.getComplexType(ScalarType); 1213 1214 if (!IsCompAssign) 1215 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1216 CK_IntegralRealToComplex); 1217 return ComplexType; 1218 } 1219 1220 /// UsualArithmeticConversions - Performs various conversions that are common to 1221 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1222 /// routine returns the first non-arithmetic type found. The client is 1223 /// responsible for emitting appropriate error diagnostics. 1224 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1225 bool IsCompAssign) { 1226 if (!IsCompAssign) { 1227 LHS = UsualUnaryConversions(LHS.get()); 1228 if (LHS.isInvalid()) 1229 return QualType(); 1230 } 1231 1232 RHS = UsualUnaryConversions(RHS.get()); 1233 if (RHS.isInvalid()) 1234 return QualType(); 1235 1236 // For conversion purposes, we ignore any qualifiers. 1237 // For example, "const float" and "float" are equivalent. 1238 QualType LHSType = 1239 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1240 QualType RHSType = 1241 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1242 1243 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1244 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1245 LHSType = AtomicLHS->getValueType(); 1246 1247 // If both types are identical, no conversion is needed. 1248 if (LHSType == RHSType) 1249 return LHSType; 1250 1251 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1252 // The caller can deal with this (e.g. pointer + int). 1253 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1254 return QualType(); 1255 1256 // Apply unary and bitfield promotions to the LHS's type. 1257 QualType LHSUnpromotedType = LHSType; 1258 if (LHSType->isPromotableIntegerType()) 1259 LHSType = Context.getPromotedIntegerType(LHSType); 1260 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1261 if (!LHSBitfieldPromoteTy.isNull()) 1262 LHSType = LHSBitfieldPromoteTy; 1263 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1264 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1265 1266 // If both types are identical, no conversion is needed. 1267 if (LHSType == RHSType) 1268 return LHSType; 1269 1270 // At this point, we have two different arithmetic types. 1271 1272 // Handle complex types first (C99 6.3.1.8p1). 1273 if (LHSType->isComplexType() || RHSType->isComplexType()) 1274 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1275 IsCompAssign); 1276 1277 // Now handle "real" floating types (i.e. float, double, long double). 1278 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1279 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1280 IsCompAssign); 1281 1282 // Handle GCC complex int extension. 1283 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1284 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1285 IsCompAssign); 1286 1287 // Finally, we have two differing integer types. 1288 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1289 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1290 } 1291 1292 1293 //===----------------------------------------------------------------------===// 1294 // Semantic Analysis for various Expression Types 1295 //===----------------------------------------------------------------------===// 1296 1297 1298 ExprResult 1299 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1300 SourceLocation DefaultLoc, 1301 SourceLocation RParenLoc, 1302 Expr *ControllingExpr, 1303 ArrayRef<ParsedType> ArgTypes, 1304 ArrayRef<Expr *> ArgExprs) { 1305 unsigned NumAssocs = ArgTypes.size(); 1306 assert(NumAssocs == ArgExprs.size()); 1307 1308 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1309 for (unsigned i = 0; i < NumAssocs; ++i) { 1310 if (ArgTypes[i]) 1311 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1312 else 1313 Types[i] = nullptr; 1314 } 1315 1316 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1317 ControllingExpr, 1318 llvm::makeArrayRef(Types, NumAssocs), 1319 ArgExprs); 1320 delete [] Types; 1321 return ER; 1322 } 1323 1324 ExprResult 1325 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1326 SourceLocation DefaultLoc, 1327 SourceLocation RParenLoc, 1328 Expr *ControllingExpr, 1329 ArrayRef<TypeSourceInfo *> Types, 1330 ArrayRef<Expr *> Exprs) { 1331 unsigned NumAssocs = Types.size(); 1332 assert(NumAssocs == Exprs.size()); 1333 if (ControllingExpr->getType()->isPlaceholderType()) { 1334 ExprResult result = CheckPlaceholderExpr(ControllingExpr); 1335 if (result.isInvalid()) return ExprError(); 1336 ControllingExpr = result.get(); 1337 } 1338 1339 bool TypeErrorFound = false, 1340 IsResultDependent = ControllingExpr->isTypeDependent(), 1341 ContainsUnexpandedParameterPack 1342 = ControllingExpr->containsUnexpandedParameterPack(); 1343 1344 for (unsigned i = 0; i < NumAssocs; ++i) { 1345 if (Exprs[i]->containsUnexpandedParameterPack()) 1346 ContainsUnexpandedParameterPack = true; 1347 1348 if (Types[i]) { 1349 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1350 ContainsUnexpandedParameterPack = true; 1351 1352 if (Types[i]->getType()->isDependentType()) { 1353 IsResultDependent = true; 1354 } else { 1355 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1356 // complete object type other than a variably modified type." 1357 unsigned D = 0; 1358 if (Types[i]->getType()->isIncompleteType()) 1359 D = diag::err_assoc_type_incomplete; 1360 else if (!Types[i]->getType()->isObjectType()) 1361 D = diag::err_assoc_type_nonobject; 1362 else if (Types[i]->getType()->isVariablyModifiedType()) 1363 D = diag::err_assoc_type_variably_modified; 1364 1365 if (D != 0) { 1366 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1367 << Types[i]->getTypeLoc().getSourceRange() 1368 << Types[i]->getType(); 1369 TypeErrorFound = true; 1370 } 1371 1372 // C11 6.5.1.1p2 "No two generic associations in the same generic 1373 // selection shall specify compatible types." 1374 for (unsigned j = i+1; j < NumAssocs; ++j) 1375 if (Types[j] && !Types[j]->getType()->isDependentType() && 1376 Context.typesAreCompatible(Types[i]->getType(), 1377 Types[j]->getType())) { 1378 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1379 diag::err_assoc_compatible_types) 1380 << Types[j]->getTypeLoc().getSourceRange() 1381 << Types[j]->getType() 1382 << Types[i]->getType(); 1383 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1384 diag::note_compat_assoc) 1385 << Types[i]->getTypeLoc().getSourceRange() 1386 << Types[i]->getType(); 1387 TypeErrorFound = true; 1388 } 1389 } 1390 } 1391 } 1392 if (TypeErrorFound) 1393 return ExprError(); 1394 1395 // If we determined that the generic selection is result-dependent, don't 1396 // try to compute the result expression. 1397 if (IsResultDependent) 1398 return new (Context) GenericSelectionExpr( 1399 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1400 ContainsUnexpandedParameterPack); 1401 1402 SmallVector<unsigned, 1> CompatIndices; 1403 unsigned DefaultIndex = -1U; 1404 for (unsigned i = 0; i < NumAssocs; ++i) { 1405 if (!Types[i]) 1406 DefaultIndex = i; 1407 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1408 Types[i]->getType())) 1409 CompatIndices.push_back(i); 1410 } 1411 1412 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1413 // type compatible with at most one of the types named in its generic 1414 // association list." 1415 if (CompatIndices.size() > 1) { 1416 // We strip parens here because the controlling expression is typically 1417 // parenthesized in macro definitions. 1418 ControllingExpr = ControllingExpr->IgnoreParens(); 1419 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1420 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1421 << (unsigned) CompatIndices.size(); 1422 for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(), 1423 E = CompatIndices.end(); I != E; ++I) { 1424 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1425 diag::note_compat_assoc) 1426 << Types[*I]->getTypeLoc().getSourceRange() 1427 << Types[*I]->getType(); 1428 } 1429 return ExprError(); 1430 } 1431 1432 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1433 // its controlling expression shall have type compatible with exactly one of 1434 // the types named in its generic association list." 1435 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1436 // We strip parens here because the controlling expression is typically 1437 // parenthesized in macro definitions. 1438 ControllingExpr = ControllingExpr->IgnoreParens(); 1439 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1440 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1441 return ExprError(); 1442 } 1443 1444 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1445 // type name that is compatible with the type of the controlling expression, 1446 // then the result expression of the generic selection is the expression 1447 // in that generic association. Otherwise, the result expression of the 1448 // generic selection is the expression in the default generic association." 1449 unsigned ResultIndex = 1450 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1451 1452 return new (Context) GenericSelectionExpr( 1453 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1454 ContainsUnexpandedParameterPack, ResultIndex); 1455 } 1456 1457 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1458 /// location of the token and the offset of the ud-suffix within it. 1459 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1460 unsigned Offset) { 1461 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1462 S.getLangOpts()); 1463 } 1464 1465 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1466 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1467 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1468 IdentifierInfo *UDSuffix, 1469 SourceLocation UDSuffixLoc, 1470 ArrayRef<Expr*> Args, 1471 SourceLocation LitEndLoc) { 1472 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1473 1474 QualType ArgTy[2]; 1475 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1476 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1477 if (ArgTy[ArgIdx]->isArrayType()) 1478 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1479 } 1480 1481 DeclarationName OpName = 1482 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1483 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1484 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1485 1486 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1487 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1488 /*AllowRaw*/false, /*AllowTemplate*/false, 1489 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1490 return ExprError(); 1491 1492 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1493 } 1494 1495 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1496 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1497 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1498 /// multiple tokens. However, the common case is that StringToks points to one 1499 /// string. 1500 /// 1501 ExprResult 1502 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks, 1503 Scope *UDLScope) { 1504 assert(NumStringToks && "Must have at least one string!"); 1505 1506 StringLiteralParser Literal(StringToks, NumStringToks, PP); 1507 if (Literal.hadError) 1508 return ExprError(); 1509 1510 SmallVector<SourceLocation, 4> StringTokLocs; 1511 for (unsigned i = 0; i != NumStringToks; ++i) 1512 StringTokLocs.push_back(StringToks[i].getLocation()); 1513 1514 QualType CharTy = Context.CharTy; 1515 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1516 if (Literal.isWide()) { 1517 CharTy = Context.getWideCharType(); 1518 Kind = StringLiteral::Wide; 1519 } else if (Literal.isUTF8()) { 1520 Kind = StringLiteral::UTF8; 1521 } else if (Literal.isUTF16()) { 1522 CharTy = Context.Char16Ty; 1523 Kind = StringLiteral::UTF16; 1524 } else if (Literal.isUTF32()) { 1525 CharTy = Context.Char32Ty; 1526 Kind = StringLiteral::UTF32; 1527 } else if (Literal.isPascal()) { 1528 CharTy = Context.UnsignedCharTy; 1529 } 1530 1531 QualType CharTyConst = CharTy; 1532 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1533 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1534 CharTyConst.addConst(); 1535 1536 // Get an array type for the string, according to C99 6.4.5. This includes 1537 // the nul terminator character as well as the string length for pascal 1538 // strings. 1539 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1540 llvm::APInt(32, Literal.GetNumStringChars()+1), 1541 ArrayType::Normal, 0); 1542 1543 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1544 if (getLangOpts().OpenCL) { 1545 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1546 } 1547 1548 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1549 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1550 Kind, Literal.Pascal, StrTy, 1551 &StringTokLocs[0], 1552 StringTokLocs.size()); 1553 if (Literal.getUDSuffix().empty()) 1554 return Lit; 1555 1556 // We're building a user-defined literal. 1557 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1558 SourceLocation UDSuffixLoc = 1559 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1560 Literal.getUDSuffixOffset()); 1561 1562 // Make sure we're allowed user-defined literals here. 1563 if (!UDLScope) 1564 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1565 1566 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1567 // operator "" X (str, len) 1568 QualType SizeType = Context.getSizeType(); 1569 1570 DeclarationName OpName = 1571 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1572 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1573 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1574 1575 QualType ArgTy[] = { 1576 Context.getArrayDecayedType(StrTy), SizeType 1577 }; 1578 1579 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1580 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1581 /*AllowRaw*/false, /*AllowTemplate*/false, 1582 /*AllowStringTemplate*/true)) { 1583 1584 case LOLR_Cooked: { 1585 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1586 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1587 StringTokLocs[0]); 1588 Expr *Args[] = { Lit, LenArg }; 1589 1590 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1591 } 1592 1593 case LOLR_StringTemplate: { 1594 TemplateArgumentListInfo ExplicitArgs; 1595 1596 unsigned CharBits = Context.getIntWidth(CharTy); 1597 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1598 llvm::APSInt Value(CharBits, CharIsUnsigned); 1599 1600 TemplateArgument TypeArg(CharTy); 1601 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1602 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1603 1604 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1605 Value = Lit->getCodeUnit(I); 1606 TemplateArgument Arg(Context, Value, CharTy); 1607 TemplateArgumentLocInfo ArgInfo; 1608 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1609 } 1610 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1611 &ExplicitArgs); 1612 } 1613 case LOLR_Raw: 1614 case LOLR_Template: 1615 llvm_unreachable("unexpected literal operator lookup result"); 1616 case LOLR_Error: 1617 return ExprError(); 1618 } 1619 llvm_unreachable("unexpected literal operator lookup result"); 1620 } 1621 1622 ExprResult 1623 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1624 SourceLocation Loc, 1625 const CXXScopeSpec *SS) { 1626 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1627 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1628 } 1629 1630 /// BuildDeclRefExpr - Build an expression that references a 1631 /// declaration that does not require a closure capture. 1632 ExprResult 1633 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1634 const DeclarationNameInfo &NameInfo, 1635 const CXXScopeSpec *SS, NamedDecl *FoundD, 1636 const TemplateArgumentListInfo *TemplateArgs) { 1637 if (getLangOpts().CUDA) 1638 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1639 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1640 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller), 1641 CalleeTarget = IdentifyCUDATarget(Callee); 1642 if (CheckCUDATarget(CallerTarget, CalleeTarget)) { 1643 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1644 << CalleeTarget << D->getIdentifier() << CallerTarget; 1645 Diag(D->getLocation(), diag::note_previous_decl) 1646 << D->getIdentifier(); 1647 return ExprError(); 1648 } 1649 } 1650 1651 bool refersToEnclosingScope = 1652 (CurContext != D->getDeclContext() && 1653 D->getDeclContext()->isFunctionOrMethod()) || 1654 (isa<VarDecl>(D) && 1655 cast<VarDecl>(D)->isInitCapture()); 1656 1657 DeclRefExpr *E; 1658 if (isa<VarTemplateSpecializationDecl>(D)) { 1659 VarTemplateSpecializationDecl *VarSpec = 1660 cast<VarTemplateSpecializationDecl>(D); 1661 1662 E = DeclRefExpr::Create( 1663 Context, 1664 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(), 1665 VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope, 1666 NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs); 1667 } else { 1668 assert(!TemplateArgs && "No template arguments for non-variable" 1669 " template specialization references"); 1670 E = DeclRefExpr::Create( 1671 Context, 1672 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(), 1673 SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD); 1674 } 1675 1676 MarkDeclRefReferenced(E); 1677 1678 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) && 1679 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1680 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1681 recordUseOfEvaluatedWeak(E); 1682 1683 // Just in case we're building an illegal pointer-to-member. 1684 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1685 if (FD && FD->isBitField()) 1686 E->setObjectKind(OK_BitField); 1687 1688 return E; 1689 } 1690 1691 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1692 /// possibly a list of template arguments. 1693 /// 1694 /// If this produces template arguments, it is permitted to call 1695 /// DecomposeTemplateName. 1696 /// 1697 /// This actually loses a lot of source location information for 1698 /// non-standard name kinds; we should consider preserving that in 1699 /// some way. 1700 void 1701 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1702 TemplateArgumentListInfo &Buffer, 1703 DeclarationNameInfo &NameInfo, 1704 const TemplateArgumentListInfo *&TemplateArgs) { 1705 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1706 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1707 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1708 1709 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1710 Id.TemplateId->NumArgs); 1711 translateTemplateArguments(TemplateArgsPtr, Buffer); 1712 1713 TemplateName TName = Id.TemplateId->Template.get(); 1714 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1715 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1716 TemplateArgs = &Buffer; 1717 } else { 1718 NameInfo = GetNameFromUnqualifiedId(Id); 1719 TemplateArgs = nullptr; 1720 } 1721 } 1722 1723 /// Diagnose an empty lookup. 1724 /// 1725 /// \return false if new lookup candidates were found 1726 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1727 CorrectionCandidateCallback &CCC, 1728 TemplateArgumentListInfo *ExplicitTemplateArgs, 1729 ArrayRef<Expr *> Args) { 1730 DeclarationName Name = R.getLookupName(); 1731 1732 unsigned diagnostic = diag::err_undeclared_var_use; 1733 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1734 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1735 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1736 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1737 diagnostic = diag::err_undeclared_use; 1738 diagnostic_suggest = diag::err_undeclared_use_suggest; 1739 } 1740 1741 // If the original lookup was an unqualified lookup, fake an 1742 // unqualified lookup. This is useful when (for example) the 1743 // original lookup would not have found something because it was a 1744 // dependent name. 1745 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty()) 1746 ? CurContext : nullptr; 1747 while (DC) { 1748 if (isa<CXXRecordDecl>(DC)) { 1749 LookupQualifiedName(R, DC); 1750 1751 if (!R.empty()) { 1752 // Don't give errors about ambiguities in this lookup. 1753 R.suppressDiagnostics(); 1754 1755 // During a default argument instantiation the CurContext points 1756 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1757 // function parameter list, hence add an explicit check. 1758 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1759 ActiveTemplateInstantiations.back().Kind == 1760 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1761 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1762 bool isInstance = CurMethod && 1763 CurMethod->isInstance() && 1764 DC == CurMethod->getParent() && !isDefaultArgument; 1765 1766 1767 // Give a code modification hint to insert 'this->'. 1768 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1769 // Actually quite difficult! 1770 if (getLangOpts().MSVCCompat) 1771 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1772 if (isInstance) { 1773 Diag(R.getNameLoc(), diagnostic) << Name 1774 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1775 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 1776 CallsUndergoingInstantiation.back()->getCallee()); 1777 1778 CXXMethodDecl *DepMethod; 1779 if (CurMethod->isDependentContext()) 1780 DepMethod = CurMethod; 1781 else if (CurMethod->getTemplatedKind() == 1782 FunctionDecl::TK_FunctionTemplateSpecialization) 1783 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()-> 1784 getInstantiatedFromMemberTemplate()->getTemplatedDecl()); 1785 else 1786 DepMethod = cast<CXXMethodDecl>( 1787 CurMethod->getInstantiatedFromMemberFunction()); 1788 assert(DepMethod && "No template pattern found"); 1789 1790 QualType DepThisType = DepMethod->getThisType(Context); 1791 CheckCXXThisCapture(R.getNameLoc()); 1792 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 1793 R.getNameLoc(), DepThisType, false); 1794 TemplateArgumentListInfo TList; 1795 if (ULE->hasExplicitTemplateArgs()) 1796 ULE->copyTemplateArgumentsInto(TList); 1797 1798 CXXScopeSpec SS; 1799 SS.Adopt(ULE->getQualifierLoc()); 1800 CXXDependentScopeMemberExpr *DepExpr = 1801 CXXDependentScopeMemberExpr::Create( 1802 Context, DepThis, DepThisType, true, SourceLocation(), 1803 SS.getWithLocInContext(Context), 1804 ULE->getTemplateKeywordLoc(), nullptr, 1805 R.getLookupNameInfo(), 1806 ULE->hasExplicitTemplateArgs() ? &TList : nullptr); 1807 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 1808 } else { 1809 Diag(R.getNameLoc(), diagnostic) << Name; 1810 } 1811 1812 // Do we really want to note all of these? 1813 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1814 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1815 1816 // Return true if we are inside a default argument instantiation 1817 // and the found name refers to an instance member function, otherwise 1818 // the function calling DiagnoseEmptyLookup will try to create an 1819 // implicit member call and this is wrong for default argument. 1820 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1821 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1822 return true; 1823 } 1824 1825 // Tell the callee to try to recover. 1826 return false; 1827 } 1828 1829 R.clear(); 1830 } 1831 1832 // In Microsoft mode, if we are performing lookup from within a friend 1833 // function definition declared at class scope then we must set 1834 // DC to the lexical parent to be able to search into the parent 1835 // class. 1836 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1837 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1838 DC->getLexicalParent()->isRecord()) 1839 DC = DC->getLexicalParent(); 1840 else 1841 DC = DC->getParent(); 1842 } 1843 1844 // We didn't find anything, so try to correct for a typo. 1845 TypoCorrection Corrected; 1846 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 1847 S, &SS, CCC, CTK_ErrorRecovery))) { 1848 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1849 bool DroppedSpecifier = 1850 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1851 R.setLookupName(Corrected.getCorrection()); 1852 1853 bool AcceptableWithRecovery = false; 1854 bool AcceptableWithoutRecovery = false; 1855 NamedDecl *ND = Corrected.getCorrectionDecl(); 1856 if (ND) { 1857 if (Corrected.isOverloaded()) { 1858 OverloadCandidateSet OCS(R.getNameLoc(), 1859 OverloadCandidateSet::CSK_Normal); 1860 OverloadCandidateSet::iterator Best; 1861 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1862 CDEnd = Corrected.end(); 1863 CD != CDEnd; ++CD) { 1864 if (FunctionTemplateDecl *FTD = 1865 dyn_cast<FunctionTemplateDecl>(*CD)) 1866 AddTemplateOverloadCandidate( 1867 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1868 Args, OCS); 1869 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1870 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1871 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1872 Args, OCS); 1873 } 1874 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1875 case OR_Success: 1876 ND = Best->Function; 1877 Corrected.setCorrectionDecl(ND); 1878 break; 1879 default: 1880 // FIXME: Arbitrarily pick the first declaration for the note. 1881 Corrected.setCorrectionDecl(ND); 1882 break; 1883 } 1884 } 1885 R.addDecl(ND); 1886 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1887 CXXRecordDecl *Record = nullptr; 1888 if (Corrected.getCorrectionSpecifier()) { 1889 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1890 Record = Ty->getAsCXXRecordDecl(); 1891 } 1892 if (!Record) 1893 Record = cast<CXXRecordDecl>( 1894 ND->getDeclContext()->getRedeclContext()); 1895 R.setNamingClass(Record); 1896 } 1897 1898 AcceptableWithRecovery = 1899 isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND); 1900 // FIXME: If we ended up with a typo for a type name or 1901 // Objective-C class name, we're in trouble because the parser 1902 // is in the wrong place to recover. Suggest the typo 1903 // correction, but don't make it a fix-it since we're not going 1904 // to recover well anyway. 1905 AcceptableWithoutRecovery = 1906 isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 1907 } else { 1908 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1909 // because we aren't able to recover. 1910 AcceptableWithoutRecovery = true; 1911 } 1912 1913 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1914 unsigned NoteID = (Corrected.getCorrectionDecl() && 1915 isa<ImplicitParamDecl>(Corrected.getCorrectionDecl())) 1916 ? diag::note_implicit_param_decl 1917 : diag::note_previous_decl; 1918 if (SS.isEmpty()) 1919 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1920 PDiag(NoteID), AcceptableWithRecovery); 1921 else 1922 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1923 << Name << computeDeclContext(SS, false) 1924 << DroppedSpecifier << SS.getRange(), 1925 PDiag(NoteID), AcceptableWithRecovery); 1926 1927 // Tell the callee whether to try to recover. 1928 return !AcceptableWithRecovery; 1929 } 1930 } 1931 R.clear(); 1932 1933 // Emit a special diagnostic for failed member lookups. 1934 // FIXME: computing the declaration context might fail here (?) 1935 if (!SS.isEmpty()) { 1936 Diag(R.getNameLoc(), diag::err_no_member) 1937 << Name << computeDeclContext(SS, false) 1938 << SS.getRange(); 1939 return true; 1940 } 1941 1942 // Give up, we can't recover. 1943 Diag(R.getNameLoc(), diagnostic) << Name; 1944 return true; 1945 } 1946 1947 /// In Microsoft mode, if we are inside a template class whose parent class has 1948 /// dependent base classes, and we can't resolve an unqualified identifier, then 1949 /// assume the identifier is a member of a dependent base class. We can only 1950 /// recover successfully in static methods, instance methods, and other contexts 1951 /// where 'this' is available. This doesn't precisely match MSVC's 1952 /// instantiation model, but it's close enough. 1953 static Expr * 1954 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 1955 DeclarationNameInfo &NameInfo, 1956 SourceLocation TemplateKWLoc, 1957 const TemplateArgumentListInfo *TemplateArgs) { 1958 // Only try to recover from lookup into dependent bases in static methods or 1959 // contexts where 'this' is available. 1960 QualType ThisType = S.getCurrentThisType(); 1961 const CXXRecordDecl *RD = nullptr; 1962 if (!ThisType.isNull()) 1963 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 1964 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 1965 RD = MD->getParent(); 1966 if (!RD || !RD->hasAnyDependentBases()) 1967 return nullptr; 1968 1969 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 1970 // is available, suggest inserting 'this->' as a fixit. 1971 SourceLocation Loc = NameInfo.getLoc(); 1972 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 1973 DB << NameInfo.getName() << RD; 1974 1975 if (!ThisType.isNull()) { 1976 DB << FixItHint::CreateInsertion(Loc, "this->"); 1977 return CXXDependentScopeMemberExpr::Create( 1978 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 1979 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 1980 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 1981 } 1982 1983 // Synthesize a fake NNS that points to the derived class. This will 1984 // perform name lookup during template instantiation. 1985 CXXScopeSpec SS; 1986 auto *NNS = 1987 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 1988 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 1989 return DependentScopeDeclRefExpr::Create( 1990 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 1991 TemplateArgs); 1992 } 1993 1994 ExprResult Sema::ActOnIdExpression(Scope *S, 1995 CXXScopeSpec &SS, 1996 SourceLocation TemplateKWLoc, 1997 UnqualifiedId &Id, 1998 bool HasTrailingLParen, 1999 bool IsAddressOfOperand, 2000 CorrectionCandidateCallback *CCC, 2001 bool IsInlineAsmIdentifier) { 2002 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2003 "cannot be direct & operand and have a trailing lparen"); 2004 if (SS.isInvalid()) 2005 return ExprError(); 2006 2007 TemplateArgumentListInfo TemplateArgsBuffer; 2008 2009 // Decompose the UnqualifiedId into the following data. 2010 DeclarationNameInfo NameInfo; 2011 const TemplateArgumentListInfo *TemplateArgs; 2012 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2013 2014 DeclarationName Name = NameInfo.getName(); 2015 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2016 SourceLocation NameLoc = NameInfo.getLoc(); 2017 2018 // C++ [temp.dep.expr]p3: 2019 // An id-expression is type-dependent if it contains: 2020 // -- an identifier that was declared with a dependent type, 2021 // (note: handled after lookup) 2022 // -- a template-id that is dependent, 2023 // (note: handled in BuildTemplateIdExpr) 2024 // -- a conversion-function-id that specifies a dependent type, 2025 // -- a nested-name-specifier that contains a class-name that 2026 // names a dependent type. 2027 // Determine whether this is a member of an unknown specialization; 2028 // we need to handle these differently. 2029 bool DependentID = false; 2030 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2031 Name.getCXXNameType()->isDependentType()) { 2032 DependentID = true; 2033 } else if (SS.isSet()) { 2034 if (DeclContext *DC = computeDeclContext(SS, false)) { 2035 if (RequireCompleteDeclContext(SS, DC)) 2036 return ExprError(); 2037 } else { 2038 DependentID = true; 2039 } 2040 } 2041 2042 if (DependentID) 2043 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2044 IsAddressOfOperand, TemplateArgs); 2045 2046 // Perform the required lookup. 2047 LookupResult R(*this, NameInfo, 2048 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2049 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2050 if (TemplateArgs) { 2051 // Lookup the template name again to correctly establish the context in 2052 // which it was found. This is really unfortunate as we already did the 2053 // lookup to determine that it was a template name in the first place. If 2054 // this becomes a performance hit, we can work harder to preserve those 2055 // results until we get here but it's likely not worth it. 2056 bool MemberOfUnknownSpecialization; 2057 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2058 MemberOfUnknownSpecialization); 2059 2060 if (MemberOfUnknownSpecialization || 2061 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2062 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2063 IsAddressOfOperand, TemplateArgs); 2064 } else { 2065 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2066 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2067 2068 // If the result might be in a dependent base class, this is a dependent 2069 // id-expression. 2070 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2071 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2072 IsAddressOfOperand, TemplateArgs); 2073 2074 // If this reference is in an Objective-C method, then we need to do 2075 // some special Objective-C lookup, too. 2076 if (IvarLookupFollowUp) { 2077 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2078 if (E.isInvalid()) 2079 return ExprError(); 2080 2081 if (Expr *Ex = E.getAs<Expr>()) 2082 return Ex; 2083 } 2084 } 2085 2086 if (R.isAmbiguous()) 2087 return ExprError(); 2088 2089 // This could be an implicitly declared function reference (legal in C90, 2090 // extension in C99, forbidden in C++). 2091 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2092 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2093 if (D) R.addDecl(D); 2094 } 2095 2096 // Determine whether this name might be a candidate for 2097 // argument-dependent lookup. 2098 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2099 2100 if (R.empty() && !ADL) { 2101 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2102 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2103 TemplateKWLoc, TemplateArgs)) 2104 return E; 2105 } 2106 2107 // Don't diagnose an empty lookup for inline assmebly. 2108 if (IsInlineAsmIdentifier) 2109 return ExprError(); 2110 2111 // If this name wasn't predeclared and if this is not a function 2112 // call, diagnose the problem. 2113 CorrectionCandidateCallback DefaultValidator; 2114 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2115 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2116 "Typo correction callback misconfigured"); 2117 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator)) 2118 return ExprError(); 2119 2120 assert(!R.empty() && 2121 "DiagnoseEmptyLookup returned false but added no results"); 2122 2123 // If we found an Objective-C instance variable, let 2124 // LookupInObjCMethod build the appropriate expression to 2125 // reference the ivar. 2126 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2127 R.clear(); 2128 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2129 // In a hopelessly buggy code, Objective-C instance variable 2130 // lookup fails and no expression will be built to reference it. 2131 if (!E.isInvalid() && !E.get()) 2132 return ExprError(); 2133 return E; 2134 } 2135 } 2136 2137 // This is guaranteed from this point on. 2138 assert(!R.empty() || ADL); 2139 2140 // Check whether this might be a C++ implicit instance member access. 2141 // C++ [class.mfct.non-static]p3: 2142 // When an id-expression that is not part of a class member access 2143 // syntax and not used to form a pointer to member is used in the 2144 // body of a non-static member function of class X, if name lookup 2145 // resolves the name in the id-expression to a non-static non-type 2146 // member of some class C, the id-expression is transformed into a 2147 // class member access expression using (*this) as the 2148 // postfix-expression to the left of the . operator. 2149 // 2150 // But we don't actually need to do this for '&' operands if R 2151 // resolved to a function or overloaded function set, because the 2152 // expression is ill-formed if it actually works out to be a 2153 // non-static member function: 2154 // 2155 // C++ [expr.ref]p4: 2156 // Otherwise, if E1.E2 refers to a non-static member function. . . 2157 // [t]he expression can be used only as the left-hand operand of a 2158 // member function call. 2159 // 2160 // There are other safeguards against such uses, but it's important 2161 // to get this right here so that we don't end up making a 2162 // spuriously dependent expression if we're inside a dependent 2163 // instance method. 2164 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2165 bool MightBeImplicitMember; 2166 if (!IsAddressOfOperand) 2167 MightBeImplicitMember = true; 2168 else if (!SS.isEmpty()) 2169 MightBeImplicitMember = false; 2170 else if (R.isOverloadedResult()) 2171 MightBeImplicitMember = false; 2172 else if (R.isUnresolvableResult()) 2173 MightBeImplicitMember = true; 2174 else 2175 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2176 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2177 isa<MSPropertyDecl>(R.getFoundDecl()); 2178 2179 if (MightBeImplicitMember) 2180 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2181 R, TemplateArgs); 2182 } 2183 2184 if (TemplateArgs || TemplateKWLoc.isValid()) { 2185 2186 // In C++1y, if this is a variable template id, then check it 2187 // in BuildTemplateIdExpr(). 2188 // The single lookup result must be a variable template declaration. 2189 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2190 Id.TemplateId->Kind == TNK_Var_template) { 2191 assert(R.getAsSingle<VarTemplateDecl>() && 2192 "There should only be one declaration found."); 2193 } 2194 2195 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2196 } 2197 2198 return BuildDeclarationNameExpr(SS, R, ADL); 2199 } 2200 2201 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2202 /// declaration name, generally during template instantiation. 2203 /// There's a large number of things which don't need to be done along 2204 /// this path. 2205 ExprResult 2206 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 2207 const DeclarationNameInfo &NameInfo, 2208 bool IsAddressOfOperand, 2209 TypeSourceInfo **RecoveryTSI) { 2210 DeclContext *DC = computeDeclContext(SS, false); 2211 if (!DC) 2212 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2213 NameInfo, /*TemplateArgs=*/nullptr); 2214 2215 if (RequireCompleteDeclContext(SS, DC)) 2216 return ExprError(); 2217 2218 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2219 LookupQualifiedName(R, DC); 2220 2221 if (R.isAmbiguous()) 2222 return ExprError(); 2223 2224 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2225 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2226 NameInfo, /*TemplateArgs=*/nullptr); 2227 2228 if (R.empty()) { 2229 Diag(NameInfo.getLoc(), diag::err_no_member) 2230 << NameInfo.getName() << DC << SS.getRange(); 2231 return ExprError(); 2232 } 2233 2234 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2235 // Diagnose a missing typename if this resolved unambiguously to a type in 2236 // a dependent context. If we can recover with a type, downgrade this to 2237 // a warning in Microsoft compatibility mode. 2238 unsigned DiagID = diag::err_typename_missing; 2239 if (RecoveryTSI && getLangOpts().MSVCCompat) 2240 DiagID = diag::ext_typename_missing; 2241 SourceLocation Loc = SS.getBeginLoc(); 2242 auto D = Diag(Loc, DiagID); 2243 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2244 << SourceRange(Loc, NameInfo.getEndLoc()); 2245 2246 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2247 // context. 2248 if (!RecoveryTSI) 2249 return ExprError(); 2250 2251 // Only issue the fixit if we're prepared to recover. 2252 D << FixItHint::CreateInsertion(Loc, "typename "); 2253 2254 // Recover by pretending this was an elaborated type. 2255 QualType Ty = Context.getTypeDeclType(TD); 2256 TypeLocBuilder TLB; 2257 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2258 2259 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2260 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2261 QTL.setElaboratedKeywordLoc(SourceLocation()); 2262 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2263 2264 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2265 2266 return ExprEmpty(); 2267 } 2268 2269 // Defend against this resolving to an implicit member access. We usually 2270 // won't get here if this might be a legitimate a class member (we end up in 2271 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2272 // a pointer-to-member or in an unevaluated context in C++11. 2273 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2274 return BuildPossibleImplicitMemberExpr(SS, 2275 /*TemplateKWLoc=*/SourceLocation(), 2276 R, /*TemplateArgs=*/nullptr); 2277 2278 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2279 } 2280 2281 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2282 /// detected that we're currently inside an ObjC method. Perform some 2283 /// additional lookup. 2284 /// 2285 /// Ideally, most of this would be done by lookup, but there's 2286 /// actually quite a lot of extra work involved. 2287 /// 2288 /// Returns a null sentinel to indicate trivial success. 2289 ExprResult 2290 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2291 IdentifierInfo *II, bool AllowBuiltinCreation) { 2292 SourceLocation Loc = Lookup.getNameLoc(); 2293 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2294 2295 // Check for error condition which is already reported. 2296 if (!CurMethod) 2297 return ExprError(); 2298 2299 // There are two cases to handle here. 1) scoped lookup could have failed, 2300 // in which case we should look for an ivar. 2) scoped lookup could have 2301 // found a decl, but that decl is outside the current instance method (i.e. 2302 // a global variable). In these two cases, we do a lookup for an ivar with 2303 // this name, if the lookup sucedes, we replace it our current decl. 2304 2305 // If we're in a class method, we don't normally want to look for 2306 // ivars. But if we don't find anything else, and there's an 2307 // ivar, that's an error. 2308 bool IsClassMethod = CurMethod->isClassMethod(); 2309 2310 bool LookForIvars; 2311 if (Lookup.empty()) 2312 LookForIvars = true; 2313 else if (IsClassMethod) 2314 LookForIvars = false; 2315 else 2316 LookForIvars = (Lookup.isSingleResult() && 2317 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2318 ObjCInterfaceDecl *IFace = nullptr; 2319 if (LookForIvars) { 2320 IFace = CurMethod->getClassInterface(); 2321 ObjCInterfaceDecl *ClassDeclared; 2322 ObjCIvarDecl *IV = nullptr; 2323 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2324 // Diagnose using an ivar in a class method. 2325 if (IsClassMethod) 2326 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2327 << IV->getDeclName()); 2328 2329 // If we're referencing an invalid decl, just return this as a silent 2330 // error node. The error diagnostic was already emitted on the decl. 2331 if (IV->isInvalidDecl()) 2332 return ExprError(); 2333 2334 // Check if referencing a field with __attribute__((deprecated)). 2335 if (DiagnoseUseOfDecl(IV, Loc)) 2336 return ExprError(); 2337 2338 // Diagnose the use of an ivar outside of the declaring class. 2339 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2340 !declaresSameEntity(ClassDeclared, IFace) && 2341 !getLangOpts().DebuggerSupport) 2342 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2343 2344 // FIXME: This should use a new expr for a direct reference, don't 2345 // turn this into Self->ivar, just return a BareIVarExpr or something. 2346 IdentifierInfo &II = Context.Idents.get("self"); 2347 UnqualifiedId SelfName; 2348 SelfName.setIdentifier(&II, SourceLocation()); 2349 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2350 CXXScopeSpec SelfScopeSpec; 2351 SourceLocation TemplateKWLoc; 2352 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2353 SelfName, false, false); 2354 if (SelfExpr.isInvalid()) 2355 return ExprError(); 2356 2357 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2358 if (SelfExpr.isInvalid()) 2359 return ExprError(); 2360 2361 MarkAnyDeclReferenced(Loc, IV, true); 2362 2363 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2364 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2365 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2366 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2367 2368 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(), 2369 Loc, IV->getLocation(), 2370 SelfExpr.get(), 2371 true, true); 2372 2373 if (getLangOpts().ObjCAutoRefCount) { 2374 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2375 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2376 recordUseOfEvaluatedWeak(Result); 2377 } 2378 if (CurContext->isClosure()) 2379 Diag(Loc, diag::warn_implicitly_retains_self) 2380 << FixItHint::CreateInsertion(Loc, "self->"); 2381 } 2382 2383 return Result; 2384 } 2385 } else if (CurMethod->isInstanceMethod()) { 2386 // We should warn if a local variable hides an ivar. 2387 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2388 ObjCInterfaceDecl *ClassDeclared; 2389 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2390 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2391 declaresSameEntity(IFace, ClassDeclared)) 2392 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2393 } 2394 } 2395 } else if (Lookup.isSingleResult() && 2396 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2397 // If accessing a stand-alone ivar in a class method, this is an error. 2398 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2399 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2400 << IV->getDeclName()); 2401 } 2402 2403 if (Lookup.empty() && II && AllowBuiltinCreation) { 2404 // FIXME. Consolidate this with similar code in LookupName. 2405 if (unsigned BuiltinID = II->getBuiltinID()) { 2406 if (!(getLangOpts().CPlusPlus && 2407 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2408 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2409 S, Lookup.isForRedeclaration(), 2410 Lookup.getNameLoc()); 2411 if (D) Lookup.addDecl(D); 2412 } 2413 } 2414 } 2415 // Sentinel value saying that we didn't do anything special. 2416 return ExprResult((Expr *)nullptr); 2417 } 2418 2419 /// \brief Cast a base object to a member's actual type. 2420 /// 2421 /// Logically this happens in three phases: 2422 /// 2423 /// * First we cast from the base type to the naming class. 2424 /// The naming class is the class into which we were looking 2425 /// when we found the member; it's the qualifier type if a 2426 /// qualifier was provided, and otherwise it's the base type. 2427 /// 2428 /// * Next we cast from the naming class to the declaring class. 2429 /// If the member we found was brought into a class's scope by 2430 /// a using declaration, this is that class; otherwise it's 2431 /// the class declaring the member. 2432 /// 2433 /// * Finally we cast from the declaring class to the "true" 2434 /// declaring class of the member. This conversion does not 2435 /// obey access control. 2436 ExprResult 2437 Sema::PerformObjectMemberConversion(Expr *From, 2438 NestedNameSpecifier *Qualifier, 2439 NamedDecl *FoundDecl, 2440 NamedDecl *Member) { 2441 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2442 if (!RD) 2443 return From; 2444 2445 QualType DestRecordType; 2446 QualType DestType; 2447 QualType FromRecordType; 2448 QualType FromType = From->getType(); 2449 bool PointerConversions = false; 2450 if (isa<FieldDecl>(Member)) { 2451 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2452 2453 if (FromType->getAs<PointerType>()) { 2454 DestType = Context.getPointerType(DestRecordType); 2455 FromRecordType = FromType->getPointeeType(); 2456 PointerConversions = true; 2457 } else { 2458 DestType = DestRecordType; 2459 FromRecordType = FromType; 2460 } 2461 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2462 if (Method->isStatic()) 2463 return From; 2464 2465 DestType = Method->getThisType(Context); 2466 DestRecordType = DestType->getPointeeType(); 2467 2468 if (FromType->getAs<PointerType>()) { 2469 FromRecordType = FromType->getPointeeType(); 2470 PointerConversions = true; 2471 } else { 2472 FromRecordType = FromType; 2473 DestType = DestRecordType; 2474 } 2475 } else { 2476 // No conversion necessary. 2477 return From; 2478 } 2479 2480 if (DestType->isDependentType() || FromType->isDependentType()) 2481 return From; 2482 2483 // If the unqualified types are the same, no conversion is necessary. 2484 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2485 return From; 2486 2487 SourceRange FromRange = From->getSourceRange(); 2488 SourceLocation FromLoc = FromRange.getBegin(); 2489 2490 ExprValueKind VK = From->getValueKind(); 2491 2492 // C++ [class.member.lookup]p8: 2493 // [...] Ambiguities can often be resolved by qualifying a name with its 2494 // class name. 2495 // 2496 // If the member was a qualified name and the qualified referred to a 2497 // specific base subobject type, we'll cast to that intermediate type 2498 // first and then to the object in which the member is declared. That allows 2499 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2500 // 2501 // class Base { public: int x; }; 2502 // class Derived1 : public Base { }; 2503 // class Derived2 : public Base { }; 2504 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2505 // 2506 // void VeryDerived::f() { 2507 // x = 17; // error: ambiguous base subobjects 2508 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2509 // } 2510 if (Qualifier && Qualifier->getAsType()) { 2511 QualType QType = QualType(Qualifier->getAsType(), 0); 2512 assert(QType->isRecordType() && "lookup done with non-record type"); 2513 2514 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2515 2516 // In C++98, the qualifier type doesn't actually have to be a base 2517 // type of the object type, in which case we just ignore it. 2518 // Otherwise build the appropriate casts. 2519 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2520 CXXCastPath BasePath; 2521 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2522 FromLoc, FromRange, &BasePath)) 2523 return ExprError(); 2524 2525 if (PointerConversions) 2526 QType = Context.getPointerType(QType); 2527 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2528 VK, &BasePath).get(); 2529 2530 FromType = QType; 2531 FromRecordType = QRecordType; 2532 2533 // If the qualifier type was the same as the destination type, 2534 // we're done. 2535 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2536 return From; 2537 } 2538 } 2539 2540 bool IgnoreAccess = false; 2541 2542 // If we actually found the member through a using declaration, cast 2543 // down to the using declaration's type. 2544 // 2545 // Pointer equality is fine here because only one declaration of a 2546 // class ever has member declarations. 2547 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2548 assert(isa<UsingShadowDecl>(FoundDecl)); 2549 QualType URecordType = Context.getTypeDeclType( 2550 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2551 2552 // We only need to do this if the naming-class to declaring-class 2553 // conversion is non-trivial. 2554 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2555 assert(IsDerivedFrom(FromRecordType, URecordType)); 2556 CXXCastPath BasePath; 2557 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2558 FromLoc, FromRange, &BasePath)) 2559 return ExprError(); 2560 2561 QualType UType = URecordType; 2562 if (PointerConversions) 2563 UType = Context.getPointerType(UType); 2564 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2565 VK, &BasePath).get(); 2566 FromType = UType; 2567 FromRecordType = URecordType; 2568 } 2569 2570 // We don't do access control for the conversion from the 2571 // declaring class to the true declaring class. 2572 IgnoreAccess = true; 2573 } 2574 2575 CXXCastPath BasePath; 2576 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2577 FromLoc, FromRange, &BasePath, 2578 IgnoreAccess)) 2579 return ExprError(); 2580 2581 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2582 VK, &BasePath); 2583 } 2584 2585 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2586 const LookupResult &R, 2587 bool HasTrailingLParen) { 2588 // Only when used directly as the postfix-expression of a call. 2589 if (!HasTrailingLParen) 2590 return false; 2591 2592 // Never if a scope specifier was provided. 2593 if (SS.isSet()) 2594 return false; 2595 2596 // Only in C++ or ObjC++. 2597 if (!getLangOpts().CPlusPlus) 2598 return false; 2599 2600 // Turn off ADL when we find certain kinds of declarations during 2601 // normal lookup: 2602 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2603 NamedDecl *D = *I; 2604 2605 // C++0x [basic.lookup.argdep]p3: 2606 // -- a declaration of a class member 2607 // Since using decls preserve this property, we check this on the 2608 // original decl. 2609 if (D->isCXXClassMember()) 2610 return false; 2611 2612 // C++0x [basic.lookup.argdep]p3: 2613 // -- a block-scope function declaration that is not a 2614 // using-declaration 2615 // NOTE: we also trigger this for function templates (in fact, we 2616 // don't check the decl type at all, since all other decl types 2617 // turn off ADL anyway). 2618 if (isa<UsingShadowDecl>(D)) 2619 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2620 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2621 return false; 2622 2623 // C++0x [basic.lookup.argdep]p3: 2624 // -- a declaration that is neither a function or a function 2625 // template 2626 // And also for builtin functions. 2627 if (isa<FunctionDecl>(D)) { 2628 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2629 2630 // But also builtin functions. 2631 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2632 return false; 2633 } else if (!isa<FunctionTemplateDecl>(D)) 2634 return false; 2635 } 2636 2637 return true; 2638 } 2639 2640 2641 /// Diagnoses obvious problems with the use of the given declaration 2642 /// as an expression. This is only actually called for lookups that 2643 /// were not overloaded, and it doesn't promise that the declaration 2644 /// will in fact be used. 2645 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2646 if (isa<TypedefNameDecl>(D)) { 2647 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2648 return true; 2649 } 2650 2651 if (isa<ObjCInterfaceDecl>(D)) { 2652 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2653 return true; 2654 } 2655 2656 if (isa<NamespaceDecl>(D)) { 2657 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2658 return true; 2659 } 2660 2661 return false; 2662 } 2663 2664 ExprResult 2665 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2666 LookupResult &R, 2667 bool NeedsADL) { 2668 // If this is a single, fully-resolved result and we don't need ADL, 2669 // just build an ordinary singleton decl ref. 2670 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2671 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2672 R.getRepresentativeDecl()); 2673 2674 // We only need to check the declaration if there's exactly one 2675 // result, because in the overloaded case the results can only be 2676 // functions and function templates. 2677 if (R.isSingleResult() && 2678 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2679 return ExprError(); 2680 2681 // Otherwise, just build an unresolved lookup expression. Suppress 2682 // any lookup-related diagnostics; we'll hash these out later, when 2683 // we've picked a target. 2684 R.suppressDiagnostics(); 2685 2686 UnresolvedLookupExpr *ULE 2687 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2688 SS.getWithLocInContext(Context), 2689 R.getLookupNameInfo(), 2690 NeedsADL, R.isOverloadedResult(), 2691 R.begin(), R.end()); 2692 2693 return ULE; 2694 } 2695 2696 /// \brief Complete semantic analysis for a reference to the given declaration. 2697 ExprResult Sema::BuildDeclarationNameExpr( 2698 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2699 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) { 2700 assert(D && "Cannot refer to a NULL declaration"); 2701 assert(!isa<FunctionTemplateDecl>(D) && 2702 "Cannot refer unambiguously to a function template"); 2703 2704 SourceLocation Loc = NameInfo.getLoc(); 2705 if (CheckDeclInExpr(*this, Loc, D)) 2706 return ExprError(); 2707 2708 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2709 // Specifically diagnose references to class templates that are missing 2710 // a template argument list. 2711 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2712 << Template << SS.getRange(); 2713 Diag(Template->getLocation(), diag::note_template_decl_here); 2714 return ExprError(); 2715 } 2716 2717 // Make sure that we're referring to a value. 2718 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2719 if (!VD) { 2720 Diag(Loc, diag::err_ref_non_value) 2721 << D << SS.getRange(); 2722 Diag(D->getLocation(), diag::note_declared_at); 2723 return ExprError(); 2724 } 2725 2726 // Check whether this declaration can be used. Note that we suppress 2727 // this check when we're going to perform argument-dependent lookup 2728 // on this function name, because this might not be the function 2729 // that overload resolution actually selects. 2730 if (DiagnoseUseOfDecl(VD, Loc)) 2731 return ExprError(); 2732 2733 // Only create DeclRefExpr's for valid Decl's. 2734 if (VD->isInvalidDecl()) 2735 return ExprError(); 2736 2737 // Handle members of anonymous structs and unions. If we got here, 2738 // and the reference is to a class member indirect field, then this 2739 // must be the subject of a pointer-to-member expression. 2740 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2741 if (!indirectField->isCXXClassMember()) 2742 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2743 indirectField); 2744 2745 { 2746 QualType type = VD->getType(); 2747 ExprValueKind valueKind = VK_RValue; 2748 2749 switch (D->getKind()) { 2750 // Ignore all the non-ValueDecl kinds. 2751 #define ABSTRACT_DECL(kind) 2752 #define VALUE(type, base) 2753 #define DECL(type, base) \ 2754 case Decl::type: 2755 #include "clang/AST/DeclNodes.inc" 2756 llvm_unreachable("invalid value decl kind"); 2757 2758 // These shouldn't make it here. 2759 case Decl::ObjCAtDefsField: 2760 case Decl::ObjCIvar: 2761 llvm_unreachable("forming non-member reference to ivar?"); 2762 2763 // Enum constants are always r-values and never references. 2764 // Unresolved using declarations are dependent. 2765 case Decl::EnumConstant: 2766 case Decl::UnresolvedUsingValue: 2767 valueKind = VK_RValue; 2768 break; 2769 2770 // Fields and indirect fields that got here must be for 2771 // pointer-to-member expressions; we just call them l-values for 2772 // internal consistency, because this subexpression doesn't really 2773 // exist in the high-level semantics. 2774 case Decl::Field: 2775 case Decl::IndirectField: 2776 assert(getLangOpts().CPlusPlus && 2777 "building reference to field in C?"); 2778 2779 // These can't have reference type in well-formed programs, but 2780 // for internal consistency we do this anyway. 2781 type = type.getNonReferenceType(); 2782 valueKind = VK_LValue; 2783 break; 2784 2785 // Non-type template parameters are either l-values or r-values 2786 // depending on the type. 2787 case Decl::NonTypeTemplateParm: { 2788 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2789 type = reftype->getPointeeType(); 2790 valueKind = VK_LValue; // even if the parameter is an r-value reference 2791 break; 2792 } 2793 2794 // For non-references, we need to strip qualifiers just in case 2795 // the template parameter was declared as 'const int' or whatever. 2796 valueKind = VK_RValue; 2797 type = type.getUnqualifiedType(); 2798 break; 2799 } 2800 2801 case Decl::Var: 2802 case Decl::VarTemplateSpecialization: 2803 case Decl::VarTemplatePartialSpecialization: 2804 // In C, "extern void blah;" is valid and is an r-value. 2805 if (!getLangOpts().CPlusPlus && 2806 !type.hasQualifiers() && 2807 type->isVoidType()) { 2808 valueKind = VK_RValue; 2809 break; 2810 } 2811 // fallthrough 2812 2813 case Decl::ImplicitParam: 2814 case Decl::ParmVar: { 2815 // These are always l-values. 2816 valueKind = VK_LValue; 2817 type = type.getNonReferenceType(); 2818 2819 // FIXME: Does the addition of const really only apply in 2820 // potentially-evaluated contexts? Since the variable isn't actually 2821 // captured in an unevaluated context, it seems that the answer is no. 2822 if (!isUnevaluatedContext()) { 2823 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2824 if (!CapturedType.isNull()) 2825 type = CapturedType; 2826 } 2827 2828 break; 2829 } 2830 2831 case Decl::Function: { 2832 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2833 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2834 type = Context.BuiltinFnTy; 2835 valueKind = VK_RValue; 2836 break; 2837 } 2838 } 2839 2840 const FunctionType *fty = type->castAs<FunctionType>(); 2841 2842 // If we're referring to a function with an __unknown_anytype 2843 // result type, make the entire expression __unknown_anytype. 2844 if (fty->getReturnType() == Context.UnknownAnyTy) { 2845 type = Context.UnknownAnyTy; 2846 valueKind = VK_RValue; 2847 break; 2848 } 2849 2850 // Functions are l-values in C++. 2851 if (getLangOpts().CPlusPlus) { 2852 valueKind = VK_LValue; 2853 break; 2854 } 2855 2856 // C99 DR 316 says that, if a function type comes from a 2857 // function definition (without a prototype), that type is only 2858 // used for checking compatibility. Therefore, when referencing 2859 // the function, we pretend that we don't have the full function 2860 // type. 2861 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2862 isa<FunctionProtoType>(fty)) 2863 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2864 fty->getExtInfo()); 2865 2866 // Functions are r-values in C. 2867 valueKind = VK_RValue; 2868 break; 2869 } 2870 2871 case Decl::MSProperty: 2872 valueKind = VK_LValue; 2873 break; 2874 2875 case Decl::CXXMethod: 2876 // If we're referring to a method with an __unknown_anytype 2877 // result type, make the entire expression __unknown_anytype. 2878 // This should only be possible with a type written directly. 2879 if (const FunctionProtoType *proto 2880 = dyn_cast<FunctionProtoType>(VD->getType())) 2881 if (proto->getReturnType() == Context.UnknownAnyTy) { 2882 type = Context.UnknownAnyTy; 2883 valueKind = VK_RValue; 2884 break; 2885 } 2886 2887 // C++ methods are l-values if static, r-values if non-static. 2888 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2889 valueKind = VK_LValue; 2890 break; 2891 } 2892 // fallthrough 2893 2894 case Decl::CXXConversion: 2895 case Decl::CXXDestructor: 2896 case Decl::CXXConstructor: 2897 valueKind = VK_RValue; 2898 break; 2899 } 2900 2901 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2902 TemplateArgs); 2903 } 2904 } 2905 2906 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 2907 PredefinedExpr::IdentType IT) { 2908 // Pick the current block, lambda, captured statement or function. 2909 Decl *currentDecl = nullptr; 2910 if (const BlockScopeInfo *BSI = getCurBlock()) 2911 currentDecl = BSI->TheDecl; 2912 else if (const LambdaScopeInfo *LSI = getCurLambda()) 2913 currentDecl = LSI->CallOperator; 2914 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 2915 currentDecl = CSI->TheCapturedDecl; 2916 else 2917 currentDecl = getCurFunctionOrMethodDecl(); 2918 2919 if (!currentDecl) { 2920 Diag(Loc, diag::ext_predef_outside_function); 2921 currentDecl = Context.getTranslationUnitDecl(); 2922 } 2923 2924 QualType ResTy; 2925 if (cast<DeclContext>(currentDecl)->isDependentContext()) 2926 ResTy = Context.DependentTy; 2927 else { 2928 // Pre-defined identifiers are of type char[x], where x is the length of 2929 // the string. 2930 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length(); 2931 2932 llvm::APInt LengthI(32, Length + 1); 2933 if (IT == PredefinedExpr::LFunction) 2934 ResTy = Context.WideCharTy.withConst(); 2935 else 2936 ResTy = Context.CharTy.withConst(); 2937 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0); 2938 } 2939 2940 return new (Context) PredefinedExpr(Loc, ResTy, IT); 2941 } 2942 2943 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 2944 PredefinedExpr::IdentType IT; 2945 2946 switch (Kind) { 2947 default: llvm_unreachable("Unknown simple primary expr!"); 2948 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 2949 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 2950 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 2951 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 2952 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 2953 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 2954 } 2955 2956 return BuildPredefinedExpr(Loc, IT); 2957 } 2958 2959 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 2960 SmallString<16> CharBuffer; 2961 bool Invalid = false; 2962 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 2963 if (Invalid) 2964 return ExprError(); 2965 2966 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 2967 PP, Tok.getKind()); 2968 if (Literal.hadError()) 2969 return ExprError(); 2970 2971 QualType Ty; 2972 if (Literal.isWide()) 2973 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 2974 else if (Literal.isUTF16()) 2975 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 2976 else if (Literal.isUTF32()) 2977 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 2978 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 2979 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 2980 else 2981 Ty = Context.CharTy; // 'x' -> char in C++ 2982 2983 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 2984 if (Literal.isWide()) 2985 Kind = CharacterLiteral::Wide; 2986 else if (Literal.isUTF16()) 2987 Kind = CharacterLiteral::UTF16; 2988 else if (Literal.isUTF32()) 2989 Kind = CharacterLiteral::UTF32; 2990 2991 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 2992 Tok.getLocation()); 2993 2994 if (Literal.getUDSuffix().empty()) 2995 return Lit; 2996 2997 // We're building a user-defined literal. 2998 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2999 SourceLocation UDSuffixLoc = 3000 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3001 3002 // Make sure we're allowed user-defined literals here. 3003 if (!UDLScope) 3004 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3005 3006 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3007 // operator "" X (ch) 3008 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3009 Lit, Tok.getLocation()); 3010 } 3011 3012 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3013 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3014 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3015 Context.IntTy, Loc); 3016 } 3017 3018 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3019 QualType Ty, SourceLocation Loc) { 3020 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3021 3022 using llvm::APFloat; 3023 APFloat Val(Format); 3024 3025 APFloat::opStatus result = Literal.GetFloatValue(Val); 3026 3027 // Overflow is always an error, but underflow is only an error if 3028 // we underflowed to zero (APFloat reports denormals as underflow). 3029 if ((result & APFloat::opOverflow) || 3030 ((result & APFloat::opUnderflow) && Val.isZero())) { 3031 unsigned diagnostic; 3032 SmallString<20> buffer; 3033 if (result & APFloat::opOverflow) { 3034 diagnostic = diag::warn_float_overflow; 3035 APFloat::getLargest(Format).toString(buffer); 3036 } else { 3037 diagnostic = diag::warn_float_underflow; 3038 APFloat::getSmallest(Format).toString(buffer); 3039 } 3040 3041 S.Diag(Loc, diagnostic) 3042 << Ty 3043 << StringRef(buffer.data(), buffer.size()); 3044 } 3045 3046 bool isExact = (result == APFloat::opOK); 3047 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3048 } 3049 3050 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3051 // Fast path for a single digit (which is quite common). A single digit 3052 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3053 if (Tok.getLength() == 1) { 3054 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3055 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3056 } 3057 3058 SmallString<128> SpellingBuffer; 3059 // NumericLiteralParser wants to overread by one character. Add padding to 3060 // the buffer in case the token is copied to the buffer. If getSpelling() 3061 // returns a StringRef to the memory buffer, it should have a null char at 3062 // the EOF, so it is also safe. 3063 SpellingBuffer.resize(Tok.getLength() + 1); 3064 3065 // Get the spelling of the token, which eliminates trigraphs, etc. 3066 bool Invalid = false; 3067 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3068 if (Invalid) 3069 return ExprError(); 3070 3071 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3072 if (Literal.hadError) 3073 return ExprError(); 3074 3075 if (Literal.hasUDSuffix()) { 3076 // We're building a user-defined literal. 3077 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3078 SourceLocation UDSuffixLoc = 3079 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3080 3081 // Make sure we're allowed user-defined literals here. 3082 if (!UDLScope) 3083 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3084 3085 QualType CookedTy; 3086 if (Literal.isFloatingLiteral()) { 3087 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3088 // long double, the literal is treated as a call of the form 3089 // operator "" X (f L) 3090 CookedTy = Context.LongDoubleTy; 3091 } else { 3092 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3093 // unsigned long long, the literal is treated as a call of the form 3094 // operator "" X (n ULL) 3095 CookedTy = Context.UnsignedLongLongTy; 3096 } 3097 3098 DeclarationName OpName = 3099 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3100 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3101 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3102 3103 SourceLocation TokLoc = Tok.getLocation(); 3104 3105 // Perform literal operator lookup to determine if we're building a raw 3106 // literal or a cooked one. 3107 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3108 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3109 /*AllowRaw*/true, /*AllowTemplate*/true, 3110 /*AllowStringTemplate*/false)) { 3111 case LOLR_Error: 3112 return ExprError(); 3113 3114 case LOLR_Cooked: { 3115 Expr *Lit; 3116 if (Literal.isFloatingLiteral()) { 3117 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3118 } else { 3119 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3120 if (Literal.GetIntegerValue(ResultVal)) 3121 Diag(Tok.getLocation(), diag::err_integer_too_large); 3122 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3123 Tok.getLocation()); 3124 } 3125 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3126 } 3127 3128 case LOLR_Raw: { 3129 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3130 // literal is treated as a call of the form 3131 // operator "" X ("n") 3132 unsigned Length = Literal.getUDSuffixOffset(); 3133 QualType StrTy = Context.getConstantArrayType( 3134 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3135 ArrayType::Normal, 0); 3136 Expr *Lit = StringLiteral::Create( 3137 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3138 /*Pascal*/false, StrTy, &TokLoc, 1); 3139 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3140 } 3141 3142 case LOLR_Template: { 3143 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3144 // template), L is treated as a call fo the form 3145 // operator "" X <'c1', 'c2', ... 'ck'>() 3146 // where n is the source character sequence c1 c2 ... ck. 3147 TemplateArgumentListInfo ExplicitArgs; 3148 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3149 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3150 llvm::APSInt Value(CharBits, CharIsUnsigned); 3151 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3152 Value = TokSpelling[I]; 3153 TemplateArgument Arg(Context, Value, Context.CharTy); 3154 TemplateArgumentLocInfo ArgInfo; 3155 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3156 } 3157 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3158 &ExplicitArgs); 3159 } 3160 case LOLR_StringTemplate: 3161 llvm_unreachable("unexpected literal operator lookup result"); 3162 } 3163 } 3164 3165 Expr *Res; 3166 3167 if (Literal.isFloatingLiteral()) { 3168 QualType Ty; 3169 if (Literal.isFloat) 3170 Ty = Context.FloatTy; 3171 else if (!Literal.isLong) 3172 Ty = Context.DoubleTy; 3173 else 3174 Ty = Context.LongDoubleTy; 3175 3176 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3177 3178 if (Ty == Context.DoubleTy) { 3179 if (getLangOpts().SinglePrecisionConstants) { 3180 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3181 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) { 3182 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3183 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3184 } 3185 } 3186 } else if (!Literal.isIntegerLiteral()) { 3187 return ExprError(); 3188 } else { 3189 QualType Ty; 3190 3191 // 'long long' is a C99 or C++11 feature. 3192 if (!getLangOpts().C99 && Literal.isLongLong) { 3193 if (getLangOpts().CPlusPlus) 3194 Diag(Tok.getLocation(), 3195 getLangOpts().CPlusPlus11 ? 3196 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3197 else 3198 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3199 } 3200 3201 // Get the value in the widest-possible width. 3202 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3203 // The microsoft literal suffix extensions support 128-bit literals, which 3204 // may be wider than [u]intmax_t. 3205 // FIXME: Actually, they don't. We seem to have accidentally invented the 3206 // i128 suffix. 3207 if (Literal.MicrosoftInteger == 128 && MaxWidth < 128 && 3208 Context.getTargetInfo().hasInt128Type()) 3209 MaxWidth = 128; 3210 llvm::APInt ResultVal(MaxWidth, 0); 3211 3212 if (Literal.GetIntegerValue(ResultVal)) { 3213 // If this value didn't fit into uintmax_t, error and force to ull. 3214 Diag(Tok.getLocation(), diag::err_integer_too_large); 3215 Ty = Context.UnsignedLongLongTy; 3216 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3217 "long long is not intmax_t?"); 3218 } else { 3219 // If this value fits into a ULL, try to figure out what else it fits into 3220 // according to the rules of C99 6.4.4.1p5. 3221 3222 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3223 // be an unsigned int. 3224 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3225 3226 // Check from smallest to largest, picking the smallest type we can. 3227 unsigned Width = 0; 3228 3229 // Microsoft specific integer suffixes are explicitly sized. 3230 if (Literal.MicrosoftInteger) { 3231 if (Literal.MicrosoftInteger > MaxWidth) { 3232 // If this target doesn't support __int128, error and force to ull. 3233 Diag(Tok.getLocation(), diag::err_int128_unsupported); 3234 Width = MaxWidth; 3235 Ty = Context.getIntMaxType(); 3236 } else { 3237 Width = Literal.MicrosoftInteger; 3238 Ty = Context.getIntTypeForBitwidth(Width, 3239 /*Signed=*/!Literal.isUnsigned); 3240 } 3241 } 3242 3243 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3244 // Are int/unsigned possibilities? 3245 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3246 3247 // Does it fit in a unsigned int? 3248 if (ResultVal.isIntN(IntSize)) { 3249 // Does it fit in a signed int? 3250 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3251 Ty = Context.IntTy; 3252 else if (AllowUnsigned) 3253 Ty = Context.UnsignedIntTy; 3254 Width = IntSize; 3255 } 3256 } 3257 3258 // Are long/unsigned long possibilities? 3259 if (Ty.isNull() && !Literal.isLongLong) { 3260 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3261 3262 // Does it fit in a unsigned long? 3263 if (ResultVal.isIntN(LongSize)) { 3264 // Does it fit in a signed long? 3265 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3266 Ty = Context.LongTy; 3267 else if (AllowUnsigned) 3268 Ty = Context.UnsignedLongTy; 3269 Width = LongSize; 3270 } 3271 } 3272 3273 // Check long long if needed. 3274 if (Ty.isNull()) { 3275 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3276 3277 // Does it fit in a unsigned long long? 3278 if (ResultVal.isIntN(LongLongSize)) { 3279 // Does it fit in a signed long long? 3280 // To be compatible with MSVC, hex integer literals ending with the 3281 // LL or i64 suffix are always signed in Microsoft mode. 3282 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3283 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3284 Ty = Context.LongLongTy; 3285 else if (AllowUnsigned) 3286 Ty = Context.UnsignedLongLongTy; 3287 Width = LongLongSize; 3288 } 3289 } 3290 3291 // If we still couldn't decide a type, we probably have something that 3292 // does not fit in a signed long long, but has no U suffix. 3293 if (Ty.isNull()) { 3294 Diag(Tok.getLocation(), diag::ext_integer_too_large_for_signed); 3295 Ty = Context.UnsignedLongLongTy; 3296 Width = Context.getTargetInfo().getLongLongWidth(); 3297 } 3298 3299 if (ResultVal.getBitWidth() != Width) 3300 ResultVal = ResultVal.trunc(Width); 3301 } 3302 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3303 } 3304 3305 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3306 if (Literal.isImaginary) 3307 Res = new (Context) ImaginaryLiteral(Res, 3308 Context.getComplexType(Res->getType())); 3309 3310 return Res; 3311 } 3312 3313 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3314 assert(E && "ActOnParenExpr() missing expr"); 3315 return new (Context) ParenExpr(L, R, E); 3316 } 3317 3318 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3319 SourceLocation Loc, 3320 SourceRange ArgRange) { 3321 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3322 // scalar or vector data type argument..." 3323 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3324 // type (C99 6.2.5p18) or void. 3325 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3326 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3327 << T << ArgRange; 3328 return true; 3329 } 3330 3331 assert((T->isVoidType() || !T->isIncompleteType()) && 3332 "Scalar types should always be complete"); 3333 return false; 3334 } 3335 3336 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3337 SourceLocation Loc, 3338 SourceRange ArgRange, 3339 UnaryExprOrTypeTrait TraitKind) { 3340 // Invalid types must be hard errors for SFINAE in C++. 3341 if (S.LangOpts.CPlusPlus) 3342 return true; 3343 3344 // C99 6.5.3.4p1: 3345 if (T->isFunctionType() && 3346 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3347 // sizeof(function)/alignof(function) is allowed as an extension. 3348 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3349 << TraitKind << ArgRange; 3350 return false; 3351 } 3352 3353 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3354 // this is an error (OpenCL v1.1 s6.3.k) 3355 if (T->isVoidType()) { 3356 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3357 : diag::ext_sizeof_alignof_void_type; 3358 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3359 return false; 3360 } 3361 3362 return true; 3363 } 3364 3365 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3366 SourceLocation Loc, 3367 SourceRange ArgRange, 3368 UnaryExprOrTypeTrait TraitKind) { 3369 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3370 // runtime doesn't allow it. 3371 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3372 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3373 << T << (TraitKind == UETT_SizeOf) 3374 << ArgRange; 3375 return true; 3376 } 3377 3378 return false; 3379 } 3380 3381 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3382 /// pointer type is equal to T) and emit a warning if it is. 3383 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3384 Expr *E) { 3385 // Don't warn if the operation changed the type. 3386 if (T != E->getType()) 3387 return; 3388 3389 // Now look for array decays. 3390 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3391 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3392 return; 3393 3394 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3395 << ICE->getType() 3396 << ICE->getSubExpr()->getType(); 3397 } 3398 3399 /// \brief Check the constraints on expression operands to unary type expression 3400 /// and type traits. 3401 /// 3402 /// Completes any types necessary and validates the constraints on the operand 3403 /// expression. The logic mostly mirrors the type-based overload, but may modify 3404 /// the expression as it completes the type for that expression through template 3405 /// instantiation, etc. 3406 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3407 UnaryExprOrTypeTrait ExprKind) { 3408 QualType ExprTy = E->getType(); 3409 assert(!ExprTy->isReferenceType()); 3410 3411 if (ExprKind == UETT_VecStep) 3412 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3413 E->getSourceRange()); 3414 3415 // Whitelist some types as extensions 3416 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3417 E->getSourceRange(), ExprKind)) 3418 return false; 3419 3420 // 'alignof' applied to an expression only requires the base element type of 3421 // the expression to be complete. 'sizeof' requires the expression's type to 3422 // be complete (and will attempt to complete it if it's an array of unknown 3423 // bound). 3424 if (ExprKind == UETT_AlignOf) { 3425 if (RequireCompleteType(E->getExprLoc(), 3426 Context.getBaseElementType(E->getType()), 3427 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3428 E->getSourceRange())) 3429 return true; 3430 } else { 3431 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3432 ExprKind, E->getSourceRange())) 3433 return true; 3434 } 3435 3436 // Completing the expression's type may have changed it. 3437 ExprTy = E->getType(); 3438 assert(!ExprTy->isReferenceType()); 3439 3440 if (ExprTy->isFunctionType()) { 3441 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3442 << ExprKind << E->getSourceRange(); 3443 return true; 3444 } 3445 3446 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3447 E->getSourceRange(), ExprKind)) 3448 return true; 3449 3450 if (ExprKind == UETT_SizeOf) { 3451 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3452 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3453 QualType OType = PVD->getOriginalType(); 3454 QualType Type = PVD->getType(); 3455 if (Type->isPointerType() && OType->isArrayType()) { 3456 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3457 << Type << OType; 3458 Diag(PVD->getLocation(), diag::note_declared_at); 3459 } 3460 } 3461 } 3462 3463 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3464 // decays into a pointer and returns an unintended result. This is most 3465 // likely a typo for "sizeof(array) op x". 3466 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3467 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3468 BO->getLHS()); 3469 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3470 BO->getRHS()); 3471 } 3472 } 3473 3474 return false; 3475 } 3476 3477 /// \brief Check the constraints on operands to unary expression and type 3478 /// traits. 3479 /// 3480 /// This will complete any types necessary, and validate the various constraints 3481 /// on those operands. 3482 /// 3483 /// The UsualUnaryConversions() function is *not* called by this routine. 3484 /// C99 6.3.2.1p[2-4] all state: 3485 /// Except when it is the operand of the sizeof operator ... 3486 /// 3487 /// C++ [expr.sizeof]p4 3488 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3489 /// standard conversions are not applied to the operand of sizeof. 3490 /// 3491 /// This policy is followed for all of the unary trait expressions. 3492 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3493 SourceLocation OpLoc, 3494 SourceRange ExprRange, 3495 UnaryExprOrTypeTrait ExprKind) { 3496 if (ExprType->isDependentType()) 3497 return false; 3498 3499 // C++ [expr.sizeof]p2: 3500 // When applied to a reference or a reference type, the result 3501 // is the size of the referenced type. 3502 // C++11 [expr.alignof]p3: 3503 // When alignof is applied to a reference type, the result 3504 // shall be the alignment of the referenced type. 3505 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3506 ExprType = Ref->getPointeeType(); 3507 3508 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3509 // When alignof or _Alignof is applied to an array type, the result 3510 // is the alignment of the element type. 3511 if (ExprKind == UETT_AlignOf) 3512 ExprType = Context.getBaseElementType(ExprType); 3513 3514 if (ExprKind == UETT_VecStep) 3515 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3516 3517 // Whitelist some types as extensions 3518 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3519 ExprKind)) 3520 return false; 3521 3522 if (RequireCompleteType(OpLoc, ExprType, 3523 diag::err_sizeof_alignof_incomplete_type, 3524 ExprKind, ExprRange)) 3525 return true; 3526 3527 if (ExprType->isFunctionType()) { 3528 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3529 << ExprKind << ExprRange; 3530 return true; 3531 } 3532 3533 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3534 ExprKind)) 3535 return true; 3536 3537 return false; 3538 } 3539 3540 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3541 E = E->IgnoreParens(); 3542 3543 // Cannot know anything else if the expression is dependent. 3544 if (E->isTypeDependent()) 3545 return false; 3546 3547 if (E->getObjectKind() == OK_BitField) { 3548 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) 3549 << 1 << E->getSourceRange(); 3550 return true; 3551 } 3552 3553 ValueDecl *D = nullptr; 3554 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3555 D = DRE->getDecl(); 3556 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3557 D = ME->getMemberDecl(); 3558 } 3559 3560 // If it's a field, require the containing struct to have a 3561 // complete definition so that we can compute the layout. 3562 // 3563 // This can happen in C++11 onwards, either by naming the member 3564 // in a way that is not transformed into a member access expression 3565 // (in an unevaluated operand, for instance), or by naming the member 3566 // in a trailing-return-type. 3567 // 3568 // For the record, since __alignof__ on expressions is a GCC 3569 // extension, GCC seems to permit this but always gives the 3570 // nonsensical answer 0. 3571 // 3572 // We don't really need the layout here --- we could instead just 3573 // directly check for all the appropriate alignment-lowing 3574 // attributes --- but that would require duplicating a lot of 3575 // logic that just isn't worth duplicating for such a marginal 3576 // use-case. 3577 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3578 // Fast path this check, since we at least know the record has a 3579 // definition if we can find a member of it. 3580 if (!FD->getParent()->isCompleteDefinition()) { 3581 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3582 << E->getSourceRange(); 3583 return true; 3584 } 3585 3586 // Otherwise, if it's a field, and the field doesn't have 3587 // reference type, then it must have a complete type (or be a 3588 // flexible array member, which we explicitly want to 3589 // white-list anyway), which makes the following checks trivial. 3590 if (!FD->getType()->isReferenceType()) 3591 return false; 3592 } 3593 3594 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3595 } 3596 3597 bool Sema::CheckVecStepExpr(Expr *E) { 3598 E = E->IgnoreParens(); 3599 3600 // Cannot know anything else if the expression is dependent. 3601 if (E->isTypeDependent()) 3602 return false; 3603 3604 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3605 } 3606 3607 /// \brief Build a sizeof or alignof expression given a type operand. 3608 ExprResult 3609 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3610 SourceLocation OpLoc, 3611 UnaryExprOrTypeTrait ExprKind, 3612 SourceRange R) { 3613 if (!TInfo) 3614 return ExprError(); 3615 3616 QualType T = TInfo->getType(); 3617 3618 if (!T->isDependentType() && 3619 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3620 return ExprError(); 3621 3622 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3623 return new (Context) UnaryExprOrTypeTraitExpr( 3624 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3625 } 3626 3627 /// \brief Build a sizeof or alignof expression given an expression 3628 /// operand. 3629 ExprResult 3630 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3631 UnaryExprOrTypeTrait ExprKind) { 3632 ExprResult PE = CheckPlaceholderExpr(E); 3633 if (PE.isInvalid()) 3634 return ExprError(); 3635 3636 E = PE.get(); 3637 3638 // Verify that the operand is valid. 3639 bool isInvalid = false; 3640 if (E->isTypeDependent()) { 3641 // Delay type-checking for type-dependent expressions. 3642 } else if (ExprKind == UETT_AlignOf) { 3643 isInvalid = CheckAlignOfExpr(*this, E); 3644 } else if (ExprKind == UETT_VecStep) { 3645 isInvalid = CheckVecStepExpr(E); 3646 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3647 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0; 3648 isInvalid = true; 3649 } else { 3650 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3651 } 3652 3653 if (isInvalid) 3654 return ExprError(); 3655 3656 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3657 PE = TransformToPotentiallyEvaluated(E); 3658 if (PE.isInvalid()) return ExprError(); 3659 E = PE.get(); 3660 } 3661 3662 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3663 return new (Context) UnaryExprOrTypeTraitExpr( 3664 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 3665 } 3666 3667 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3668 /// expr and the same for @c alignof and @c __alignof 3669 /// Note that the ArgRange is invalid if isType is false. 3670 ExprResult 3671 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3672 UnaryExprOrTypeTrait ExprKind, bool IsType, 3673 void *TyOrEx, const SourceRange &ArgRange) { 3674 // If error parsing type, ignore. 3675 if (!TyOrEx) return ExprError(); 3676 3677 if (IsType) { 3678 TypeSourceInfo *TInfo; 3679 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3680 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3681 } 3682 3683 Expr *ArgEx = (Expr *)TyOrEx; 3684 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3685 return Result; 3686 } 3687 3688 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3689 bool IsReal) { 3690 if (V.get()->isTypeDependent()) 3691 return S.Context.DependentTy; 3692 3693 // _Real and _Imag are only l-values for normal l-values. 3694 if (V.get()->getObjectKind() != OK_Ordinary) { 3695 V = S.DefaultLvalueConversion(V.get()); 3696 if (V.isInvalid()) 3697 return QualType(); 3698 } 3699 3700 // These operators return the element type of a complex type. 3701 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3702 return CT->getElementType(); 3703 3704 // Otherwise they pass through real integer and floating point types here. 3705 if (V.get()->getType()->isArithmeticType()) 3706 return V.get()->getType(); 3707 3708 // Test for placeholders. 3709 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3710 if (PR.isInvalid()) return QualType(); 3711 if (PR.get() != V.get()) { 3712 V = PR; 3713 return CheckRealImagOperand(S, V, Loc, IsReal); 3714 } 3715 3716 // Reject anything else. 3717 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3718 << (IsReal ? "__real" : "__imag"); 3719 return QualType(); 3720 } 3721 3722 3723 3724 ExprResult 3725 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3726 tok::TokenKind Kind, Expr *Input) { 3727 UnaryOperatorKind Opc; 3728 switch (Kind) { 3729 default: llvm_unreachable("Unknown unary op!"); 3730 case tok::plusplus: Opc = UO_PostInc; break; 3731 case tok::minusminus: Opc = UO_PostDec; break; 3732 } 3733 3734 // Since this might is a postfix expression, get rid of ParenListExprs. 3735 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3736 if (Result.isInvalid()) return ExprError(); 3737 Input = Result.get(); 3738 3739 return BuildUnaryOp(S, OpLoc, Opc, Input); 3740 } 3741 3742 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 3743 /// 3744 /// \return true on error 3745 static bool checkArithmeticOnObjCPointer(Sema &S, 3746 SourceLocation opLoc, 3747 Expr *op) { 3748 assert(op->getType()->isObjCObjectPointerType()); 3749 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 3750 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 3751 return false; 3752 3753 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 3754 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 3755 << op->getSourceRange(); 3756 return true; 3757 } 3758 3759 ExprResult 3760 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 3761 Expr *idx, SourceLocation rbLoc) { 3762 // Since this might be a postfix expression, get rid of ParenListExprs. 3763 if (isa<ParenListExpr>(base)) { 3764 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 3765 if (result.isInvalid()) return ExprError(); 3766 base = result.get(); 3767 } 3768 3769 // Handle any non-overload placeholder types in the base and index 3770 // expressions. We can't handle overloads here because the other 3771 // operand might be an overloadable type, in which case the overload 3772 // resolution for the operator overload should get the first crack 3773 // at the overload. 3774 if (base->getType()->isNonOverloadPlaceholderType()) { 3775 ExprResult result = CheckPlaceholderExpr(base); 3776 if (result.isInvalid()) return ExprError(); 3777 base = result.get(); 3778 } 3779 if (idx->getType()->isNonOverloadPlaceholderType()) { 3780 ExprResult result = CheckPlaceholderExpr(idx); 3781 if (result.isInvalid()) return ExprError(); 3782 idx = result.get(); 3783 } 3784 3785 // Build an unanalyzed expression if either operand is type-dependent. 3786 if (getLangOpts().CPlusPlus && 3787 (base->isTypeDependent() || idx->isTypeDependent())) { 3788 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 3789 VK_LValue, OK_Ordinary, rbLoc); 3790 } 3791 3792 // Use C++ overloaded-operator rules if either operand has record 3793 // type. The spec says to do this if either type is *overloadable*, 3794 // but enum types can't declare subscript operators or conversion 3795 // operators, so there's nothing interesting for overload resolution 3796 // to do if there aren't any record types involved. 3797 // 3798 // ObjC pointers have their own subscripting logic that is not tied 3799 // to overload resolution and so should not take this path. 3800 if (getLangOpts().CPlusPlus && 3801 (base->getType()->isRecordType() || 3802 (!base->getType()->isObjCObjectPointerType() && 3803 idx->getType()->isRecordType()))) { 3804 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 3805 } 3806 3807 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 3808 } 3809 3810 ExprResult 3811 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 3812 Expr *Idx, SourceLocation RLoc) { 3813 Expr *LHSExp = Base; 3814 Expr *RHSExp = Idx; 3815 3816 // Perform default conversions. 3817 if (!LHSExp->getType()->getAs<VectorType>()) { 3818 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 3819 if (Result.isInvalid()) 3820 return ExprError(); 3821 LHSExp = Result.get(); 3822 } 3823 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 3824 if (Result.isInvalid()) 3825 return ExprError(); 3826 RHSExp = Result.get(); 3827 3828 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 3829 ExprValueKind VK = VK_LValue; 3830 ExprObjectKind OK = OK_Ordinary; 3831 3832 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 3833 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 3834 // in the subscript position. As a result, we need to derive the array base 3835 // and index from the expression types. 3836 Expr *BaseExpr, *IndexExpr; 3837 QualType ResultType; 3838 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 3839 BaseExpr = LHSExp; 3840 IndexExpr = RHSExp; 3841 ResultType = Context.DependentTy; 3842 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 3843 BaseExpr = LHSExp; 3844 IndexExpr = RHSExp; 3845 ResultType = PTy->getPointeeType(); 3846 } else if (const ObjCObjectPointerType *PTy = 3847 LHSTy->getAs<ObjCObjectPointerType>()) { 3848 BaseExpr = LHSExp; 3849 IndexExpr = RHSExp; 3850 3851 // Use custom logic if this should be the pseudo-object subscript 3852 // expression. 3853 if (!LangOpts.isSubscriptPointerArithmetic()) 3854 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 3855 nullptr); 3856 3857 ResultType = PTy->getPointeeType(); 3858 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 3859 // Handle the uncommon case of "123[Ptr]". 3860 BaseExpr = RHSExp; 3861 IndexExpr = LHSExp; 3862 ResultType = PTy->getPointeeType(); 3863 } else if (const ObjCObjectPointerType *PTy = 3864 RHSTy->getAs<ObjCObjectPointerType>()) { 3865 // Handle the uncommon case of "123[Ptr]". 3866 BaseExpr = RHSExp; 3867 IndexExpr = LHSExp; 3868 ResultType = PTy->getPointeeType(); 3869 if (!LangOpts.isSubscriptPointerArithmetic()) { 3870 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3871 << ResultType << BaseExpr->getSourceRange(); 3872 return ExprError(); 3873 } 3874 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 3875 BaseExpr = LHSExp; // vectors: V[123] 3876 IndexExpr = RHSExp; 3877 VK = LHSExp->getValueKind(); 3878 if (VK != VK_RValue) 3879 OK = OK_VectorComponent; 3880 3881 // FIXME: need to deal with const... 3882 ResultType = VTy->getElementType(); 3883 } else if (LHSTy->isArrayType()) { 3884 // If we see an array that wasn't promoted by 3885 // DefaultFunctionArrayLvalueConversion, it must be an array that 3886 // wasn't promoted because of the C90 rule that doesn't 3887 // allow promoting non-lvalue arrays. Warn, then 3888 // force the promotion here. 3889 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3890 LHSExp->getSourceRange(); 3891 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 3892 CK_ArrayToPointerDecay).get(); 3893 LHSTy = LHSExp->getType(); 3894 3895 BaseExpr = LHSExp; 3896 IndexExpr = RHSExp; 3897 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 3898 } else if (RHSTy->isArrayType()) { 3899 // Same as previous, except for 123[f().a] case 3900 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3901 RHSExp->getSourceRange(); 3902 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 3903 CK_ArrayToPointerDecay).get(); 3904 RHSTy = RHSExp->getType(); 3905 3906 BaseExpr = RHSExp; 3907 IndexExpr = LHSExp; 3908 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 3909 } else { 3910 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 3911 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 3912 } 3913 // C99 6.5.2.1p1 3914 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 3915 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 3916 << IndexExpr->getSourceRange()); 3917 3918 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 3919 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 3920 && !IndexExpr->isTypeDependent()) 3921 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 3922 3923 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 3924 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 3925 // type. Note that Functions are not objects, and that (in C99 parlance) 3926 // incomplete types are not object types. 3927 if (ResultType->isFunctionType()) { 3928 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 3929 << ResultType << BaseExpr->getSourceRange(); 3930 return ExprError(); 3931 } 3932 3933 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 3934 // GNU extension: subscripting on pointer to void 3935 Diag(LLoc, diag::ext_gnu_subscript_void_type) 3936 << BaseExpr->getSourceRange(); 3937 3938 // C forbids expressions of unqualified void type from being l-values. 3939 // See IsCForbiddenLValueType. 3940 if (!ResultType.hasQualifiers()) VK = VK_RValue; 3941 } else if (!ResultType->isDependentType() && 3942 RequireCompleteType(LLoc, ResultType, 3943 diag::err_subscript_incomplete_type, BaseExpr)) 3944 return ExprError(); 3945 3946 assert(VK == VK_RValue || LangOpts.CPlusPlus || 3947 !ResultType.isCForbiddenLValueType()); 3948 3949 return new (Context) 3950 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 3951 } 3952 3953 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3954 FunctionDecl *FD, 3955 ParmVarDecl *Param) { 3956 if (Param->hasUnparsedDefaultArg()) { 3957 Diag(CallLoc, 3958 diag::err_use_of_default_argument_to_function_declared_later) << 3959 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 3960 Diag(UnparsedDefaultArgLocs[Param], 3961 diag::note_default_argument_declared_here); 3962 return ExprError(); 3963 } 3964 3965 if (Param->hasUninstantiatedDefaultArg()) { 3966 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 3967 3968 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 3969 Param); 3970 3971 // Instantiate the expression. 3972 MultiLevelTemplateArgumentList MutiLevelArgList 3973 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 3974 3975 InstantiatingTemplate Inst(*this, CallLoc, Param, 3976 MutiLevelArgList.getInnermost()); 3977 if (Inst.isInvalid()) 3978 return ExprError(); 3979 3980 ExprResult Result; 3981 { 3982 // C++ [dcl.fct.default]p5: 3983 // The names in the [default argument] expression are bound, and 3984 // the semantic constraints are checked, at the point where the 3985 // default argument expression appears. 3986 ContextRAII SavedContext(*this, FD); 3987 LocalInstantiationScope Local(*this); 3988 Result = SubstExpr(UninstExpr, MutiLevelArgList); 3989 } 3990 if (Result.isInvalid()) 3991 return ExprError(); 3992 3993 // Check the expression as an initializer for the parameter. 3994 InitializedEntity Entity 3995 = InitializedEntity::InitializeParameter(Context, Param); 3996 InitializationKind Kind 3997 = InitializationKind::CreateCopy(Param->getLocation(), 3998 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 3999 Expr *ResultE = Result.getAs<Expr>(); 4000 4001 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4002 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4003 if (Result.isInvalid()) 4004 return ExprError(); 4005 4006 Expr *Arg = Result.getAs<Expr>(); 4007 CheckCompletedExpr(Arg, Param->getOuterLocStart()); 4008 // Build the default argument expression. 4009 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg); 4010 } 4011 4012 // If the default expression creates temporaries, we need to 4013 // push them to the current stack of expression temporaries so they'll 4014 // be properly destroyed. 4015 // FIXME: We should really be rebuilding the default argument with new 4016 // bound temporaries; see the comment in PR5810. 4017 // We don't need to do that with block decls, though, because 4018 // blocks in default argument expression can never capture anything. 4019 if (isa<ExprWithCleanups>(Param->getInit())) { 4020 // Set the "needs cleanups" bit regardless of whether there are 4021 // any explicit objects. 4022 ExprNeedsCleanups = true; 4023 4024 // Append all the objects to the cleanup list. Right now, this 4025 // should always be a no-op, because blocks in default argument 4026 // expressions should never be able to capture anything. 4027 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 4028 "default argument expression has capturing blocks?"); 4029 } 4030 4031 // We already type-checked the argument, so we know it works. 4032 // Just mark all of the declarations in this potentially-evaluated expression 4033 // as being "referenced". 4034 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4035 /*SkipLocalVariables=*/true); 4036 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4037 } 4038 4039 4040 Sema::VariadicCallType 4041 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4042 Expr *Fn) { 4043 if (Proto && Proto->isVariadic()) { 4044 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4045 return VariadicConstructor; 4046 else if (Fn && Fn->getType()->isBlockPointerType()) 4047 return VariadicBlock; 4048 else if (FDecl) { 4049 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4050 if (Method->isInstance()) 4051 return VariadicMethod; 4052 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4053 return VariadicMethod; 4054 return VariadicFunction; 4055 } 4056 return VariadicDoesNotApply; 4057 } 4058 4059 namespace { 4060 class FunctionCallCCC : public FunctionCallFilterCCC { 4061 public: 4062 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4063 unsigned NumArgs, MemberExpr *ME) 4064 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4065 FunctionName(FuncName) {} 4066 4067 bool ValidateCandidate(const TypoCorrection &candidate) override { 4068 if (!candidate.getCorrectionSpecifier() || 4069 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4070 return false; 4071 } 4072 4073 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4074 } 4075 4076 private: 4077 const IdentifierInfo *const FunctionName; 4078 }; 4079 } 4080 4081 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4082 FunctionDecl *FDecl, 4083 ArrayRef<Expr *> Args) { 4084 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4085 DeclarationName FuncName = FDecl->getDeclName(); 4086 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4087 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 4088 4089 if (TypoCorrection Corrected = S.CorrectTypo( 4090 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4091 S.getScopeForContext(S.CurContext), nullptr, CCC, 4092 Sema::CTK_ErrorRecovery)) { 4093 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 4094 if (Corrected.isOverloaded()) { 4095 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4096 OverloadCandidateSet::iterator Best; 4097 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 4098 CDEnd = Corrected.end(); 4099 CD != CDEnd; ++CD) { 4100 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 4101 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4102 OCS); 4103 } 4104 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4105 case OR_Success: 4106 ND = Best->Function; 4107 Corrected.setCorrectionDecl(ND); 4108 break; 4109 default: 4110 break; 4111 } 4112 } 4113 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 4114 return Corrected; 4115 } 4116 } 4117 } 4118 return TypoCorrection(); 4119 } 4120 4121 /// ConvertArgumentsForCall - Converts the arguments specified in 4122 /// Args/NumArgs to the parameter types of the function FDecl with 4123 /// function prototype Proto. Call is the call expression itself, and 4124 /// Fn is the function expression. For a C++ member function, this 4125 /// routine does not attempt to convert the object argument. Returns 4126 /// true if the call is ill-formed. 4127 bool 4128 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4129 FunctionDecl *FDecl, 4130 const FunctionProtoType *Proto, 4131 ArrayRef<Expr *> Args, 4132 SourceLocation RParenLoc, 4133 bool IsExecConfig) { 4134 // Bail out early if calling a builtin with custom typechecking. 4135 // We don't need to do this in the 4136 if (FDecl) 4137 if (unsigned ID = FDecl->getBuiltinID()) 4138 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4139 return false; 4140 4141 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4142 // assignment, to the types of the corresponding parameter, ... 4143 unsigned NumParams = Proto->getNumParams(); 4144 bool Invalid = false; 4145 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4146 unsigned FnKind = Fn->getType()->isBlockPointerType() 4147 ? 1 /* block */ 4148 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4149 : 0 /* function */); 4150 4151 // If too few arguments are available (and we don't have default 4152 // arguments for the remaining parameters), don't make the call. 4153 if (Args.size() < NumParams) { 4154 if (Args.size() < MinArgs) { 4155 TypoCorrection TC; 4156 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4157 unsigned diag_id = 4158 MinArgs == NumParams && !Proto->isVariadic() 4159 ? diag::err_typecheck_call_too_few_args_suggest 4160 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4161 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4162 << static_cast<unsigned>(Args.size()) 4163 << TC.getCorrectionRange()); 4164 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4165 Diag(RParenLoc, 4166 MinArgs == NumParams && !Proto->isVariadic() 4167 ? diag::err_typecheck_call_too_few_args_one 4168 : diag::err_typecheck_call_too_few_args_at_least_one) 4169 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4170 else 4171 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4172 ? diag::err_typecheck_call_too_few_args 4173 : diag::err_typecheck_call_too_few_args_at_least) 4174 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4175 << Fn->getSourceRange(); 4176 4177 // Emit the location of the prototype. 4178 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4179 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4180 << FDecl; 4181 4182 return true; 4183 } 4184 Call->setNumArgs(Context, NumParams); 4185 } 4186 4187 // If too many are passed and not variadic, error on the extras and drop 4188 // them. 4189 if (Args.size() > NumParams) { 4190 if (!Proto->isVariadic()) { 4191 TypoCorrection TC; 4192 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4193 unsigned diag_id = 4194 MinArgs == NumParams && !Proto->isVariadic() 4195 ? diag::err_typecheck_call_too_many_args_suggest 4196 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4197 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4198 << static_cast<unsigned>(Args.size()) 4199 << TC.getCorrectionRange()); 4200 } else if (NumParams == 1 && FDecl && 4201 FDecl->getParamDecl(0)->getDeclName()) 4202 Diag(Args[NumParams]->getLocStart(), 4203 MinArgs == NumParams 4204 ? diag::err_typecheck_call_too_many_args_one 4205 : diag::err_typecheck_call_too_many_args_at_most_one) 4206 << FnKind << FDecl->getParamDecl(0) 4207 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4208 << SourceRange(Args[NumParams]->getLocStart(), 4209 Args.back()->getLocEnd()); 4210 else 4211 Diag(Args[NumParams]->getLocStart(), 4212 MinArgs == NumParams 4213 ? diag::err_typecheck_call_too_many_args 4214 : diag::err_typecheck_call_too_many_args_at_most) 4215 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4216 << Fn->getSourceRange() 4217 << SourceRange(Args[NumParams]->getLocStart(), 4218 Args.back()->getLocEnd()); 4219 4220 // Emit the location of the prototype. 4221 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4222 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4223 << FDecl; 4224 4225 // This deletes the extra arguments. 4226 Call->setNumArgs(Context, NumParams); 4227 return true; 4228 } 4229 } 4230 SmallVector<Expr *, 8> AllArgs; 4231 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4232 4233 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4234 Proto, 0, Args, AllArgs, CallType); 4235 if (Invalid) 4236 return true; 4237 unsigned TotalNumArgs = AllArgs.size(); 4238 for (unsigned i = 0; i < TotalNumArgs; ++i) 4239 Call->setArg(i, AllArgs[i]); 4240 4241 return false; 4242 } 4243 4244 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4245 const FunctionProtoType *Proto, 4246 unsigned FirstParam, ArrayRef<Expr *> Args, 4247 SmallVectorImpl<Expr *> &AllArgs, 4248 VariadicCallType CallType, bool AllowExplicit, 4249 bool IsListInitialization) { 4250 unsigned NumParams = Proto->getNumParams(); 4251 bool Invalid = false; 4252 unsigned ArgIx = 0; 4253 // Continue to check argument types (even if we have too few/many args). 4254 for (unsigned i = FirstParam; i < NumParams; i++) { 4255 QualType ProtoArgType = Proto->getParamType(i); 4256 4257 Expr *Arg; 4258 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4259 if (ArgIx < Args.size()) { 4260 Arg = Args[ArgIx++]; 4261 4262 if (RequireCompleteType(Arg->getLocStart(), 4263 ProtoArgType, 4264 diag::err_call_incomplete_argument, Arg)) 4265 return true; 4266 4267 // Strip the unbridged-cast placeholder expression off, if applicable. 4268 bool CFAudited = false; 4269 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4270 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4271 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4272 Arg = stripARCUnbridgedCast(Arg); 4273 else if (getLangOpts().ObjCAutoRefCount && 4274 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4275 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4276 CFAudited = true; 4277 4278 InitializedEntity Entity = 4279 Param ? InitializedEntity::InitializeParameter(Context, Param, 4280 ProtoArgType) 4281 : InitializedEntity::InitializeParameter( 4282 Context, ProtoArgType, Proto->isParamConsumed(i)); 4283 4284 // Remember that parameter belongs to a CF audited API. 4285 if (CFAudited) 4286 Entity.setParameterCFAudited(); 4287 4288 ExprResult ArgE = PerformCopyInitialization( 4289 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4290 if (ArgE.isInvalid()) 4291 return true; 4292 4293 Arg = ArgE.getAs<Expr>(); 4294 } else { 4295 assert(Param && "can't use default arguments without a known callee"); 4296 4297 ExprResult ArgExpr = 4298 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4299 if (ArgExpr.isInvalid()) 4300 return true; 4301 4302 Arg = ArgExpr.getAs<Expr>(); 4303 } 4304 4305 // Check for array bounds violations for each argument to the call. This 4306 // check only triggers warnings when the argument isn't a more complex Expr 4307 // with its own checking, such as a BinaryOperator. 4308 CheckArrayAccess(Arg); 4309 4310 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4311 CheckStaticArrayArgument(CallLoc, Param, Arg); 4312 4313 AllArgs.push_back(Arg); 4314 } 4315 4316 // If this is a variadic call, handle args passed through "...". 4317 if (CallType != VariadicDoesNotApply) { 4318 // Assume that extern "C" functions with variadic arguments that 4319 // return __unknown_anytype aren't *really* variadic. 4320 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4321 FDecl->isExternC()) { 4322 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4323 QualType paramType; // ignored 4324 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType); 4325 Invalid |= arg.isInvalid(); 4326 AllArgs.push_back(arg.get()); 4327 } 4328 4329 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4330 } else { 4331 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4332 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 4333 FDecl); 4334 Invalid |= Arg.isInvalid(); 4335 AllArgs.push_back(Arg.get()); 4336 } 4337 } 4338 4339 // Check for array bounds violations. 4340 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) 4341 CheckArrayAccess(Args[i]); 4342 } 4343 return Invalid; 4344 } 4345 4346 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4347 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4348 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4349 TL = DTL.getOriginalLoc(); 4350 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4351 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4352 << ATL.getLocalSourceRange(); 4353 } 4354 4355 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4356 /// array parameter, check that it is non-null, and that if it is formed by 4357 /// array-to-pointer decay, the underlying array is sufficiently large. 4358 /// 4359 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4360 /// array type derivation, then for each call to the function, the value of the 4361 /// corresponding actual argument shall provide access to the first element of 4362 /// an array with at least as many elements as specified by the size expression. 4363 void 4364 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4365 ParmVarDecl *Param, 4366 const Expr *ArgExpr) { 4367 // Static array parameters are not supported in C++. 4368 if (!Param || getLangOpts().CPlusPlus) 4369 return; 4370 4371 QualType OrigTy = Param->getOriginalType(); 4372 4373 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4374 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4375 return; 4376 4377 if (ArgExpr->isNullPointerConstant(Context, 4378 Expr::NPC_NeverValueDependent)) { 4379 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4380 DiagnoseCalleeStaticArrayParam(*this, Param); 4381 return; 4382 } 4383 4384 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4385 if (!CAT) 4386 return; 4387 4388 const ConstantArrayType *ArgCAT = 4389 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4390 if (!ArgCAT) 4391 return; 4392 4393 if (ArgCAT->getSize().ult(CAT->getSize())) { 4394 Diag(CallLoc, diag::warn_static_array_too_small) 4395 << ArgExpr->getSourceRange() 4396 << (unsigned) ArgCAT->getSize().getZExtValue() 4397 << (unsigned) CAT->getSize().getZExtValue(); 4398 DiagnoseCalleeStaticArrayParam(*this, Param); 4399 } 4400 } 4401 4402 /// Given a function expression of unknown-any type, try to rebuild it 4403 /// to have a function type. 4404 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4405 4406 /// Is the given type a placeholder that we need to lower out 4407 /// immediately during argument processing? 4408 static bool isPlaceholderToRemoveAsArg(QualType type) { 4409 // Placeholders are never sugared. 4410 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4411 if (!placeholder) return false; 4412 4413 switch (placeholder->getKind()) { 4414 // Ignore all the non-placeholder types. 4415 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4416 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4417 #include "clang/AST/BuiltinTypes.def" 4418 return false; 4419 4420 // We cannot lower out overload sets; they might validly be resolved 4421 // by the call machinery. 4422 case BuiltinType::Overload: 4423 return false; 4424 4425 // Unbridged casts in ARC can be handled in some call positions and 4426 // should be left in place. 4427 case BuiltinType::ARCUnbridgedCast: 4428 return false; 4429 4430 // Pseudo-objects should be converted as soon as possible. 4431 case BuiltinType::PseudoObject: 4432 return true; 4433 4434 // The debugger mode could theoretically but currently does not try 4435 // to resolve unknown-typed arguments based on known parameter types. 4436 case BuiltinType::UnknownAny: 4437 return true; 4438 4439 // These are always invalid as call arguments and should be reported. 4440 case BuiltinType::BoundMember: 4441 case BuiltinType::BuiltinFn: 4442 return true; 4443 } 4444 llvm_unreachable("bad builtin type kind"); 4445 } 4446 4447 /// Check an argument list for placeholders that we won't try to 4448 /// handle later. 4449 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 4450 // Apply this processing to all the arguments at once instead of 4451 // dying at the first failure. 4452 bool hasInvalid = false; 4453 for (size_t i = 0, e = args.size(); i != e; i++) { 4454 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 4455 ExprResult result = S.CheckPlaceholderExpr(args[i]); 4456 if (result.isInvalid()) hasInvalid = true; 4457 else args[i] = result.get(); 4458 } 4459 } 4460 return hasInvalid; 4461 } 4462 4463 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 4464 /// This provides the location of the left/right parens and a list of comma 4465 /// locations. 4466 ExprResult 4467 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 4468 MultiExprArg ArgExprs, SourceLocation RParenLoc, 4469 Expr *ExecConfig, bool IsExecConfig) { 4470 // Since this might be a postfix expression, get rid of ParenListExprs. 4471 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 4472 if (Result.isInvalid()) return ExprError(); 4473 Fn = Result.get(); 4474 4475 if (checkArgsForPlaceholders(*this, ArgExprs)) 4476 return ExprError(); 4477 4478 if (getLangOpts().CPlusPlus) { 4479 // If this is a pseudo-destructor expression, build the call immediately. 4480 if (isa<CXXPseudoDestructorExpr>(Fn)) { 4481 if (!ArgExprs.empty()) { 4482 // Pseudo-destructor calls should not have any arguments. 4483 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 4484 << FixItHint::CreateRemoval( 4485 SourceRange(ArgExprs[0]->getLocStart(), 4486 ArgExprs.back()->getLocEnd())); 4487 } 4488 4489 return new (Context) 4490 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 4491 } 4492 if (Fn->getType() == Context.PseudoObjectTy) { 4493 ExprResult result = CheckPlaceholderExpr(Fn); 4494 if (result.isInvalid()) return ExprError(); 4495 Fn = result.get(); 4496 } 4497 4498 // Determine whether this is a dependent call inside a C++ template, 4499 // in which case we won't do any semantic analysis now. 4500 // FIXME: Will need to cache the results of name lookup (including ADL) in 4501 // Fn. 4502 bool Dependent = false; 4503 if (Fn->isTypeDependent()) 4504 Dependent = true; 4505 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 4506 Dependent = true; 4507 4508 if (Dependent) { 4509 if (ExecConfig) { 4510 return new (Context) CUDAKernelCallExpr( 4511 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 4512 Context.DependentTy, VK_RValue, RParenLoc); 4513 } else { 4514 return new (Context) CallExpr( 4515 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 4516 } 4517 } 4518 4519 // Determine whether this is a call to an object (C++ [over.call.object]). 4520 if (Fn->getType()->isRecordType()) 4521 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs, 4522 RParenLoc); 4523 4524 if (Fn->getType() == Context.UnknownAnyTy) { 4525 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4526 if (result.isInvalid()) return ExprError(); 4527 Fn = result.get(); 4528 } 4529 4530 if (Fn->getType() == Context.BoundMemberTy) { 4531 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 4532 } 4533 } 4534 4535 // Check for overloaded calls. This can happen even in C due to extensions. 4536 if (Fn->getType() == Context.OverloadTy) { 4537 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 4538 4539 // We aren't supposed to apply this logic for if there's an '&' involved. 4540 if (!find.HasFormOfMemberPointer) { 4541 OverloadExpr *ovl = find.Expression; 4542 if (isa<UnresolvedLookupExpr>(ovl)) { 4543 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 4544 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 4545 RParenLoc, ExecConfig); 4546 } else { 4547 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, 4548 RParenLoc); 4549 } 4550 } 4551 } 4552 4553 // If we're directly calling a function, get the appropriate declaration. 4554 if (Fn->getType() == Context.UnknownAnyTy) { 4555 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4556 if (result.isInvalid()) return ExprError(); 4557 Fn = result.get(); 4558 } 4559 4560 Expr *NakedFn = Fn->IgnoreParens(); 4561 4562 NamedDecl *NDecl = nullptr; 4563 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 4564 if (UnOp->getOpcode() == UO_AddrOf) 4565 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 4566 4567 if (isa<DeclRefExpr>(NakedFn)) 4568 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 4569 else if (isa<MemberExpr>(NakedFn)) 4570 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 4571 4572 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 4573 if (FD->hasAttr<EnableIfAttr>()) { 4574 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 4575 Diag(Fn->getLocStart(), 4576 isa<CXXMethodDecl>(FD) ? 4577 diag::err_ovl_no_viable_member_function_in_call : 4578 diag::err_ovl_no_viable_function_in_call) 4579 << FD << FD->getSourceRange(); 4580 Diag(FD->getLocation(), 4581 diag::note_ovl_candidate_disabled_by_enable_if_attr) 4582 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 4583 } 4584 } 4585 } 4586 4587 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 4588 ExecConfig, IsExecConfig); 4589 } 4590 4591 ExprResult 4592 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 4593 MultiExprArg ExecConfig, SourceLocation GGGLoc) { 4594 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl(); 4595 if (!ConfigDecl) 4596 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use) 4597 << "cudaConfigureCall"); 4598 QualType ConfigQTy = ConfigDecl->getType(); 4599 4600 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr( 4601 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc); 4602 MarkFunctionReferenced(LLLLoc, ConfigDecl); 4603 4604 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, nullptr, 4605 /*IsExecConfig=*/true); 4606 } 4607 4608 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 4609 /// 4610 /// __builtin_astype( value, dst type ) 4611 /// 4612 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 4613 SourceLocation BuiltinLoc, 4614 SourceLocation RParenLoc) { 4615 ExprValueKind VK = VK_RValue; 4616 ExprObjectKind OK = OK_Ordinary; 4617 QualType DstTy = GetTypeFromParser(ParsedDestTy); 4618 QualType SrcTy = E->getType(); 4619 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 4620 return ExprError(Diag(BuiltinLoc, 4621 diag::err_invalid_astype_of_different_size) 4622 << DstTy 4623 << SrcTy 4624 << E->getSourceRange()); 4625 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 4626 } 4627 4628 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 4629 /// provided arguments. 4630 /// 4631 /// __builtin_convertvector( value, dst type ) 4632 /// 4633 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 4634 SourceLocation BuiltinLoc, 4635 SourceLocation RParenLoc) { 4636 TypeSourceInfo *TInfo; 4637 GetTypeFromParser(ParsedDestTy, &TInfo); 4638 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 4639 } 4640 4641 /// BuildResolvedCallExpr - Build a call to a resolved expression, 4642 /// i.e. an expression not of \p OverloadTy. The expression should 4643 /// unary-convert to an expression of function-pointer or 4644 /// block-pointer type. 4645 /// 4646 /// \param NDecl the declaration being called, if available 4647 ExprResult 4648 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 4649 SourceLocation LParenLoc, 4650 ArrayRef<Expr *> Args, 4651 SourceLocation RParenLoc, 4652 Expr *Config, bool IsExecConfig) { 4653 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 4654 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 4655 4656 // Promote the function operand. 4657 // We special-case function promotion here because we only allow promoting 4658 // builtin functions to function pointers in the callee of a call. 4659 ExprResult Result; 4660 if (BuiltinID && 4661 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 4662 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 4663 CK_BuiltinFnToFnPtr).get(); 4664 } else { 4665 Result = CallExprUnaryConversions(Fn); 4666 } 4667 if (Result.isInvalid()) 4668 return ExprError(); 4669 Fn = Result.get(); 4670 4671 // Make the call expr early, before semantic checks. This guarantees cleanup 4672 // of arguments and function on error. 4673 CallExpr *TheCall; 4674 if (Config) 4675 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 4676 cast<CallExpr>(Config), Args, 4677 Context.BoolTy, VK_RValue, 4678 RParenLoc); 4679 else 4680 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 4681 VK_RValue, RParenLoc); 4682 4683 // Bail out early if calling a builtin with custom typechecking. 4684 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 4685 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4686 4687 retry: 4688 const FunctionType *FuncT; 4689 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 4690 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 4691 // have type pointer to function". 4692 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 4693 if (!FuncT) 4694 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4695 << Fn->getType() << Fn->getSourceRange()); 4696 } else if (const BlockPointerType *BPT = 4697 Fn->getType()->getAs<BlockPointerType>()) { 4698 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 4699 } else { 4700 // Handle calls to expressions of unknown-any type. 4701 if (Fn->getType() == Context.UnknownAnyTy) { 4702 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 4703 if (rewrite.isInvalid()) return ExprError(); 4704 Fn = rewrite.get(); 4705 TheCall->setCallee(Fn); 4706 goto retry; 4707 } 4708 4709 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4710 << Fn->getType() << Fn->getSourceRange()); 4711 } 4712 4713 if (getLangOpts().CUDA) { 4714 if (Config) { 4715 // CUDA: Kernel calls must be to global functions 4716 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 4717 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 4718 << FDecl->getName() << Fn->getSourceRange()); 4719 4720 // CUDA: Kernel function must have 'void' return type 4721 if (!FuncT->getReturnType()->isVoidType()) 4722 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 4723 << Fn->getType() << Fn->getSourceRange()); 4724 } else { 4725 // CUDA: Calls to global functions must be configured 4726 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 4727 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 4728 << FDecl->getName() << Fn->getSourceRange()); 4729 } 4730 } 4731 4732 // Check for a valid return type 4733 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 4734 FDecl)) 4735 return ExprError(); 4736 4737 // We know the result type of the call, set it. 4738 TheCall->setType(FuncT->getCallResultType(Context)); 4739 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 4740 4741 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 4742 if (Proto) { 4743 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 4744 IsExecConfig)) 4745 return ExprError(); 4746 } else { 4747 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 4748 4749 if (FDecl) { 4750 // Check if we have too few/too many template arguments, based 4751 // on our knowledge of the function definition. 4752 const FunctionDecl *Def = nullptr; 4753 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 4754 Proto = Def->getType()->getAs<FunctionProtoType>(); 4755 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 4756 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 4757 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 4758 } 4759 4760 // If the function we're calling isn't a function prototype, but we have 4761 // a function prototype from a prior declaratiom, use that prototype. 4762 if (!FDecl->hasPrototype()) 4763 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 4764 } 4765 4766 // Promote the arguments (C99 6.5.2.2p6). 4767 for (unsigned i = 0, e = Args.size(); i != e; i++) { 4768 Expr *Arg = Args[i]; 4769 4770 if (Proto && i < Proto->getNumParams()) { 4771 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4772 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 4773 ExprResult ArgE = 4774 PerformCopyInitialization(Entity, SourceLocation(), Arg); 4775 if (ArgE.isInvalid()) 4776 return true; 4777 4778 Arg = ArgE.getAs<Expr>(); 4779 4780 } else { 4781 ExprResult ArgE = DefaultArgumentPromotion(Arg); 4782 4783 if (ArgE.isInvalid()) 4784 return true; 4785 4786 Arg = ArgE.getAs<Expr>(); 4787 } 4788 4789 if (RequireCompleteType(Arg->getLocStart(), 4790 Arg->getType(), 4791 diag::err_call_incomplete_argument, Arg)) 4792 return ExprError(); 4793 4794 TheCall->setArg(i, Arg); 4795 } 4796 } 4797 4798 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4799 if (!Method->isStatic()) 4800 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 4801 << Fn->getSourceRange()); 4802 4803 // Check for sentinels 4804 if (NDecl) 4805 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 4806 4807 // Do special checking on direct calls to functions. 4808 if (FDecl) { 4809 if (CheckFunctionCall(FDecl, TheCall, Proto)) 4810 return ExprError(); 4811 4812 if (BuiltinID) 4813 return CheckBuiltinFunctionCall(BuiltinID, TheCall); 4814 } else if (NDecl) { 4815 if (CheckPointerCall(NDecl, TheCall, Proto)) 4816 return ExprError(); 4817 } else { 4818 if (CheckOtherCall(TheCall, Proto)) 4819 return ExprError(); 4820 } 4821 4822 return MaybeBindToTemporary(TheCall); 4823 } 4824 4825 ExprResult 4826 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 4827 SourceLocation RParenLoc, Expr *InitExpr) { 4828 assert(Ty && "ActOnCompoundLiteral(): missing type"); 4829 // FIXME: put back this assert when initializers are worked out. 4830 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 4831 4832 TypeSourceInfo *TInfo; 4833 QualType literalType = GetTypeFromParser(Ty, &TInfo); 4834 if (!TInfo) 4835 TInfo = Context.getTrivialTypeSourceInfo(literalType); 4836 4837 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 4838 } 4839 4840 ExprResult 4841 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 4842 SourceLocation RParenLoc, Expr *LiteralExpr) { 4843 QualType literalType = TInfo->getType(); 4844 4845 if (literalType->isArrayType()) { 4846 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 4847 diag::err_illegal_decl_array_incomplete_type, 4848 SourceRange(LParenLoc, 4849 LiteralExpr->getSourceRange().getEnd()))) 4850 return ExprError(); 4851 if (literalType->isVariableArrayType()) 4852 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 4853 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 4854 } else if (!literalType->isDependentType() && 4855 RequireCompleteType(LParenLoc, literalType, 4856 diag::err_typecheck_decl_incomplete_type, 4857 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 4858 return ExprError(); 4859 4860 InitializedEntity Entity 4861 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 4862 InitializationKind Kind 4863 = InitializationKind::CreateCStyleCast(LParenLoc, 4864 SourceRange(LParenLoc, RParenLoc), 4865 /*InitList=*/true); 4866 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 4867 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 4868 &literalType); 4869 if (Result.isInvalid()) 4870 return ExprError(); 4871 LiteralExpr = Result.get(); 4872 4873 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr; 4874 if (isFileScope && 4875 !LiteralExpr->isTypeDependent() && 4876 !LiteralExpr->isValueDependent() && 4877 !literalType->isDependentType()) { // 6.5.2.5p3 4878 if (CheckForConstantInitializer(LiteralExpr, literalType)) 4879 return ExprError(); 4880 } 4881 4882 // In C, compound literals are l-values for some reason. 4883 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 4884 4885 return MaybeBindToTemporary( 4886 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 4887 VK, LiteralExpr, isFileScope)); 4888 } 4889 4890 ExprResult 4891 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 4892 SourceLocation RBraceLoc) { 4893 // Immediately handle non-overload placeholders. Overloads can be 4894 // resolved contextually, but everything else here can't. 4895 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 4896 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 4897 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 4898 4899 // Ignore failures; dropping the entire initializer list because 4900 // of one failure would be terrible for indexing/etc. 4901 if (result.isInvalid()) continue; 4902 4903 InitArgList[I] = result.get(); 4904 } 4905 } 4906 4907 // Semantic analysis for initializers is done by ActOnDeclarator() and 4908 // CheckInitializer() - it requires knowledge of the object being intialized. 4909 4910 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 4911 RBraceLoc); 4912 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 4913 return E; 4914 } 4915 4916 /// Do an explicit extend of the given block pointer if we're in ARC. 4917 static void maybeExtendBlockObject(Sema &S, ExprResult &E) { 4918 assert(E.get()->getType()->isBlockPointerType()); 4919 assert(E.get()->isRValue()); 4920 4921 // Only do this in an r-value context. 4922 if (!S.getLangOpts().ObjCAutoRefCount) return; 4923 4924 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), 4925 CK_ARCExtendBlockObject, E.get(), 4926 /*base path*/ nullptr, VK_RValue); 4927 S.ExprNeedsCleanups = true; 4928 } 4929 4930 /// Prepare a conversion of the given expression to an ObjC object 4931 /// pointer type. 4932 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 4933 QualType type = E.get()->getType(); 4934 if (type->isObjCObjectPointerType()) { 4935 return CK_BitCast; 4936 } else if (type->isBlockPointerType()) { 4937 maybeExtendBlockObject(*this, E); 4938 return CK_BlockPointerToObjCPointerCast; 4939 } else { 4940 assert(type->isPointerType()); 4941 return CK_CPointerToObjCPointerCast; 4942 } 4943 } 4944 4945 /// Prepares for a scalar cast, performing all the necessary stages 4946 /// except the final cast and returning the kind required. 4947 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 4948 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 4949 // Also, callers should have filtered out the invalid cases with 4950 // pointers. Everything else should be possible. 4951 4952 QualType SrcTy = Src.get()->getType(); 4953 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 4954 return CK_NoOp; 4955 4956 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 4957 case Type::STK_MemberPointer: 4958 llvm_unreachable("member pointer type in C"); 4959 4960 case Type::STK_CPointer: 4961 case Type::STK_BlockPointer: 4962 case Type::STK_ObjCObjectPointer: 4963 switch (DestTy->getScalarTypeKind()) { 4964 case Type::STK_CPointer: { 4965 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 4966 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 4967 if (SrcAS != DestAS) 4968 return CK_AddressSpaceConversion; 4969 return CK_BitCast; 4970 } 4971 case Type::STK_BlockPointer: 4972 return (SrcKind == Type::STK_BlockPointer 4973 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 4974 case Type::STK_ObjCObjectPointer: 4975 if (SrcKind == Type::STK_ObjCObjectPointer) 4976 return CK_BitCast; 4977 if (SrcKind == Type::STK_CPointer) 4978 return CK_CPointerToObjCPointerCast; 4979 maybeExtendBlockObject(*this, Src); 4980 return CK_BlockPointerToObjCPointerCast; 4981 case Type::STK_Bool: 4982 return CK_PointerToBoolean; 4983 case Type::STK_Integral: 4984 return CK_PointerToIntegral; 4985 case Type::STK_Floating: 4986 case Type::STK_FloatingComplex: 4987 case Type::STK_IntegralComplex: 4988 case Type::STK_MemberPointer: 4989 llvm_unreachable("illegal cast from pointer"); 4990 } 4991 llvm_unreachable("Should have returned before this"); 4992 4993 case Type::STK_Bool: // casting from bool is like casting from an integer 4994 case Type::STK_Integral: 4995 switch (DestTy->getScalarTypeKind()) { 4996 case Type::STK_CPointer: 4997 case Type::STK_ObjCObjectPointer: 4998 case Type::STK_BlockPointer: 4999 if (Src.get()->isNullPointerConstant(Context, 5000 Expr::NPC_ValueDependentIsNull)) 5001 return CK_NullToPointer; 5002 return CK_IntegralToPointer; 5003 case Type::STK_Bool: 5004 return CK_IntegralToBoolean; 5005 case Type::STK_Integral: 5006 return CK_IntegralCast; 5007 case Type::STK_Floating: 5008 return CK_IntegralToFloating; 5009 case Type::STK_IntegralComplex: 5010 Src = ImpCastExprToType(Src.get(), 5011 DestTy->castAs<ComplexType>()->getElementType(), 5012 CK_IntegralCast); 5013 return CK_IntegralRealToComplex; 5014 case Type::STK_FloatingComplex: 5015 Src = ImpCastExprToType(Src.get(), 5016 DestTy->castAs<ComplexType>()->getElementType(), 5017 CK_IntegralToFloating); 5018 return CK_FloatingRealToComplex; 5019 case Type::STK_MemberPointer: 5020 llvm_unreachable("member pointer type in C"); 5021 } 5022 llvm_unreachable("Should have returned before this"); 5023 5024 case Type::STK_Floating: 5025 switch (DestTy->getScalarTypeKind()) { 5026 case Type::STK_Floating: 5027 return CK_FloatingCast; 5028 case Type::STK_Bool: 5029 return CK_FloatingToBoolean; 5030 case Type::STK_Integral: 5031 return CK_FloatingToIntegral; 5032 case Type::STK_FloatingComplex: 5033 Src = ImpCastExprToType(Src.get(), 5034 DestTy->castAs<ComplexType>()->getElementType(), 5035 CK_FloatingCast); 5036 return CK_FloatingRealToComplex; 5037 case Type::STK_IntegralComplex: 5038 Src = ImpCastExprToType(Src.get(), 5039 DestTy->castAs<ComplexType>()->getElementType(), 5040 CK_FloatingToIntegral); 5041 return CK_IntegralRealToComplex; 5042 case Type::STK_CPointer: 5043 case Type::STK_ObjCObjectPointer: 5044 case Type::STK_BlockPointer: 5045 llvm_unreachable("valid float->pointer cast?"); 5046 case Type::STK_MemberPointer: 5047 llvm_unreachable("member pointer type in C"); 5048 } 5049 llvm_unreachable("Should have returned before this"); 5050 5051 case Type::STK_FloatingComplex: 5052 switch (DestTy->getScalarTypeKind()) { 5053 case Type::STK_FloatingComplex: 5054 return CK_FloatingComplexCast; 5055 case Type::STK_IntegralComplex: 5056 return CK_FloatingComplexToIntegralComplex; 5057 case Type::STK_Floating: { 5058 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5059 if (Context.hasSameType(ET, DestTy)) 5060 return CK_FloatingComplexToReal; 5061 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5062 return CK_FloatingCast; 5063 } 5064 case Type::STK_Bool: 5065 return CK_FloatingComplexToBoolean; 5066 case Type::STK_Integral: 5067 Src = ImpCastExprToType(Src.get(), 5068 SrcTy->castAs<ComplexType>()->getElementType(), 5069 CK_FloatingComplexToReal); 5070 return CK_FloatingToIntegral; 5071 case Type::STK_CPointer: 5072 case Type::STK_ObjCObjectPointer: 5073 case Type::STK_BlockPointer: 5074 llvm_unreachable("valid complex float->pointer cast?"); 5075 case Type::STK_MemberPointer: 5076 llvm_unreachable("member pointer type in C"); 5077 } 5078 llvm_unreachable("Should have returned before this"); 5079 5080 case Type::STK_IntegralComplex: 5081 switch (DestTy->getScalarTypeKind()) { 5082 case Type::STK_FloatingComplex: 5083 return CK_IntegralComplexToFloatingComplex; 5084 case Type::STK_IntegralComplex: 5085 return CK_IntegralComplexCast; 5086 case Type::STK_Integral: { 5087 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5088 if (Context.hasSameType(ET, DestTy)) 5089 return CK_IntegralComplexToReal; 5090 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5091 return CK_IntegralCast; 5092 } 5093 case Type::STK_Bool: 5094 return CK_IntegralComplexToBoolean; 5095 case Type::STK_Floating: 5096 Src = ImpCastExprToType(Src.get(), 5097 SrcTy->castAs<ComplexType>()->getElementType(), 5098 CK_IntegralComplexToReal); 5099 return CK_IntegralToFloating; 5100 case Type::STK_CPointer: 5101 case Type::STK_ObjCObjectPointer: 5102 case Type::STK_BlockPointer: 5103 llvm_unreachable("valid complex int->pointer cast?"); 5104 case Type::STK_MemberPointer: 5105 llvm_unreachable("member pointer type in C"); 5106 } 5107 llvm_unreachable("Should have returned before this"); 5108 } 5109 5110 llvm_unreachable("Unhandled scalar cast"); 5111 } 5112 5113 static bool breakDownVectorType(QualType type, uint64_t &len, 5114 QualType &eltType) { 5115 // Vectors are simple. 5116 if (const VectorType *vecType = type->getAs<VectorType>()) { 5117 len = vecType->getNumElements(); 5118 eltType = vecType->getElementType(); 5119 assert(eltType->isScalarType()); 5120 return true; 5121 } 5122 5123 // We allow lax conversion to and from non-vector types, but only if 5124 // they're real types (i.e. non-complex, non-pointer scalar types). 5125 if (!type->isRealType()) return false; 5126 5127 len = 1; 5128 eltType = type; 5129 return true; 5130 } 5131 5132 static bool VectorTypesMatch(Sema &S, QualType srcTy, QualType destTy) { 5133 uint64_t srcLen, destLen; 5134 QualType srcElt, destElt; 5135 if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false; 5136 if (!breakDownVectorType(destTy, destLen, destElt)) return false; 5137 5138 // ASTContext::getTypeSize will return the size rounded up to a 5139 // power of 2, so instead of using that, we need to use the raw 5140 // element size multiplied by the element count. 5141 uint64_t srcEltSize = S.Context.getTypeSize(srcElt); 5142 uint64_t destEltSize = S.Context.getTypeSize(destElt); 5143 5144 return (srcLen * srcEltSize == destLen * destEltSize); 5145 } 5146 5147 /// Is this a legal conversion between two known vector types? 5148 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5149 assert(destTy->isVectorType() || srcTy->isVectorType()); 5150 5151 if (!Context.getLangOpts().LaxVectorConversions) 5152 return false; 5153 return VectorTypesMatch(*this, srcTy, destTy); 5154 } 5155 5156 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5157 CastKind &Kind) { 5158 assert(VectorTy->isVectorType() && "Not a vector type!"); 5159 5160 if (Ty->isVectorType() || Ty->isIntegerType()) { 5161 if (!VectorTypesMatch(*this, Ty, VectorTy)) 5162 return Diag(R.getBegin(), 5163 Ty->isVectorType() ? 5164 diag::err_invalid_conversion_between_vectors : 5165 diag::err_invalid_conversion_between_vector_and_integer) 5166 << VectorTy << Ty << R; 5167 } else 5168 return Diag(R.getBegin(), 5169 diag::err_invalid_conversion_between_vector_and_scalar) 5170 << VectorTy << Ty << R; 5171 5172 Kind = CK_BitCast; 5173 return false; 5174 } 5175 5176 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5177 Expr *CastExpr, CastKind &Kind) { 5178 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5179 5180 QualType SrcTy = CastExpr->getType(); 5181 5182 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5183 // an ExtVectorType. 5184 // In OpenCL, casts between vectors of different types are not allowed. 5185 // (See OpenCL 6.2). 5186 if (SrcTy->isVectorType()) { 5187 if (!VectorTypesMatch(*this, SrcTy, DestTy) 5188 || (getLangOpts().OpenCL && 5189 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5190 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5191 << DestTy << SrcTy << R; 5192 return ExprError(); 5193 } 5194 Kind = CK_BitCast; 5195 return CastExpr; 5196 } 5197 5198 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5199 // conversion will take place first from scalar to elt type, and then 5200 // splat from elt type to vector. 5201 if (SrcTy->isPointerType()) 5202 return Diag(R.getBegin(), 5203 diag::err_invalid_conversion_between_vector_and_scalar) 5204 << DestTy << SrcTy << R; 5205 5206 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 5207 ExprResult CastExprRes = CastExpr; 5208 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 5209 if (CastExprRes.isInvalid()) 5210 return ExprError(); 5211 CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get(); 5212 5213 Kind = CK_VectorSplat; 5214 return CastExpr; 5215 } 5216 5217 ExprResult 5218 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5219 Declarator &D, ParsedType &Ty, 5220 SourceLocation RParenLoc, Expr *CastExpr) { 5221 assert(!D.isInvalidType() && (CastExpr != nullptr) && 5222 "ActOnCastExpr(): missing type or expr"); 5223 5224 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5225 if (D.isInvalidType()) 5226 return ExprError(); 5227 5228 if (getLangOpts().CPlusPlus) { 5229 // Check that there are no default arguments (C++ only). 5230 CheckExtraCXXDefaultArguments(D); 5231 } 5232 5233 checkUnusedDeclAttributes(D); 5234 5235 QualType castType = castTInfo->getType(); 5236 Ty = CreateParsedType(castType, castTInfo); 5237 5238 bool isVectorLiteral = false; 5239 5240 // Check for an altivec or OpenCL literal, 5241 // i.e. all the elements are integer constants. 5242 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5243 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5244 if ((getLangOpts().AltiVec || getLangOpts().OpenCL) 5245 && castType->isVectorType() && (PE || PLE)) { 5246 if (PLE && PLE->getNumExprs() == 0) { 5247 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 5248 return ExprError(); 5249 } 5250 if (PE || PLE->getNumExprs() == 1) { 5251 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 5252 if (!E->getType()->isVectorType()) 5253 isVectorLiteral = true; 5254 } 5255 else 5256 isVectorLiteral = true; 5257 } 5258 5259 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 5260 // then handle it as such. 5261 if (isVectorLiteral) 5262 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 5263 5264 // If the Expr being casted is a ParenListExpr, handle it specially. 5265 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 5266 // sequence of BinOp comma operators. 5267 if (isa<ParenListExpr>(CastExpr)) { 5268 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 5269 if (Result.isInvalid()) return ExprError(); 5270 CastExpr = Result.get(); 5271 } 5272 5273 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 5274 !getSourceManager().isInSystemMacro(LParenLoc)) 5275 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 5276 5277 CheckTollFreeBridgeCast(castType, CastExpr); 5278 5279 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 5280 } 5281 5282 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 5283 SourceLocation RParenLoc, Expr *E, 5284 TypeSourceInfo *TInfo) { 5285 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 5286 "Expected paren or paren list expression"); 5287 5288 Expr **exprs; 5289 unsigned numExprs; 5290 Expr *subExpr; 5291 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 5292 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 5293 LiteralLParenLoc = PE->getLParenLoc(); 5294 LiteralRParenLoc = PE->getRParenLoc(); 5295 exprs = PE->getExprs(); 5296 numExprs = PE->getNumExprs(); 5297 } else { // isa<ParenExpr> by assertion at function entrance 5298 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 5299 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 5300 subExpr = cast<ParenExpr>(E)->getSubExpr(); 5301 exprs = &subExpr; 5302 numExprs = 1; 5303 } 5304 5305 QualType Ty = TInfo->getType(); 5306 assert(Ty->isVectorType() && "Expected vector type"); 5307 5308 SmallVector<Expr *, 8> initExprs; 5309 const VectorType *VTy = Ty->getAs<VectorType>(); 5310 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 5311 5312 // '(...)' form of vector initialization in AltiVec: the number of 5313 // initializers must be one or must match the size of the vector. 5314 // If a single value is specified in the initializer then it will be 5315 // replicated to all the components of the vector 5316 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 5317 // The number of initializers must be one or must match the size of the 5318 // vector. If a single value is specified in the initializer then it will 5319 // be replicated to all the components of the vector 5320 if (numExprs == 1) { 5321 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5322 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5323 if (Literal.isInvalid()) 5324 return ExprError(); 5325 Literal = ImpCastExprToType(Literal.get(), ElemTy, 5326 PrepareScalarCast(Literal, ElemTy)); 5327 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 5328 } 5329 else if (numExprs < numElems) { 5330 Diag(E->getExprLoc(), 5331 diag::err_incorrect_number_of_vector_initializers); 5332 return ExprError(); 5333 } 5334 else 5335 initExprs.append(exprs, exprs + numExprs); 5336 } 5337 else { 5338 // For OpenCL, when the number of initializers is a single value, 5339 // it will be replicated to all components of the vector. 5340 if (getLangOpts().OpenCL && 5341 VTy->getVectorKind() == VectorType::GenericVector && 5342 numExprs == 1) { 5343 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5344 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5345 if (Literal.isInvalid()) 5346 return ExprError(); 5347 Literal = ImpCastExprToType(Literal.get(), ElemTy, 5348 PrepareScalarCast(Literal, ElemTy)); 5349 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 5350 } 5351 5352 initExprs.append(exprs, exprs + numExprs); 5353 } 5354 // FIXME: This means that pretty-printing the final AST will produce curly 5355 // braces instead of the original commas. 5356 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 5357 initExprs, LiteralRParenLoc); 5358 initE->setType(Ty); 5359 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 5360 } 5361 5362 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 5363 /// the ParenListExpr into a sequence of comma binary operators. 5364 ExprResult 5365 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 5366 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 5367 if (!E) 5368 return OrigExpr; 5369 5370 ExprResult Result(E->getExpr(0)); 5371 5372 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 5373 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 5374 E->getExpr(i)); 5375 5376 if (Result.isInvalid()) return ExprError(); 5377 5378 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 5379 } 5380 5381 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 5382 SourceLocation R, 5383 MultiExprArg Val) { 5384 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 5385 return expr; 5386 } 5387 5388 /// \brief Emit a specialized diagnostic when one expression is a null pointer 5389 /// constant and the other is not a pointer. Returns true if a diagnostic is 5390 /// emitted. 5391 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 5392 SourceLocation QuestionLoc) { 5393 Expr *NullExpr = LHSExpr; 5394 Expr *NonPointerExpr = RHSExpr; 5395 Expr::NullPointerConstantKind NullKind = 5396 NullExpr->isNullPointerConstant(Context, 5397 Expr::NPC_ValueDependentIsNotNull); 5398 5399 if (NullKind == Expr::NPCK_NotNull) { 5400 NullExpr = RHSExpr; 5401 NonPointerExpr = LHSExpr; 5402 NullKind = 5403 NullExpr->isNullPointerConstant(Context, 5404 Expr::NPC_ValueDependentIsNotNull); 5405 } 5406 5407 if (NullKind == Expr::NPCK_NotNull) 5408 return false; 5409 5410 if (NullKind == Expr::NPCK_ZeroExpression) 5411 return false; 5412 5413 if (NullKind == Expr::NPCK_ZeroLiteral) { 5414 // In this case, check to make sure that we got here from a "NULL" 5415 // string in the source code. 5416 NullExpr = NullExpr->IgnoreParenImpCasts(); 5417 SourceLocation loc = NullExpr->getExprLoc(); 5418 if (!findMacroSpelling(loc, "NULL")) 5419 return false; 5420 } 5421 5422 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 5423 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 5424 << NonPointerExpr->getType() << DiagType 5425 << NonPointerExpr->getSourceRange(); 5426 return true; 5427 } 5428 5429 /// \brief Return false if the condition expression is valid, true otherwise. 5430 static bool checkCondition(Sema &S, Expr *Cond) { 5431 QualType CondTy = Cond->getType(); 5432 5433 // C99 6.5.15p2 5434 if (CondTy->isScalarType()) return false; 5435 5436 // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar. 5437 if (S.getLangOpts().OpenCL && CondTy->isVectorType()) 5438 return false; 5439 5440 // Emit the proper error message. 5441 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ? 5442 diag::err_typecheck_cond_expect_scalar : 5443 diag::err_typecheck_cond_expect_scalar_or_vector) 5444 << CondTy; 5445 return true; 5446 } 5447 5448 /// \brief Return false if the two expressions can be converted to a vector, 5449 /// true otherwise 5450 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS, 5451 ExprResult &RHS, 5452 QualType CondTy) { 5453 // Both operands should be of scalar type. 5454 if (!LHS.get()->getType()->isScalarType()) { 5455 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5456 << CondTy; 5457 return true; 5458 } 5459 if (!RHS.get()->getType()->isScalarType()) { 5460 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5461 << CondTy; 5462 return true; 5463 } 5464 5465 // Implicity convert these scalars to the type of the condition. 5466 LHS = S.ImpCastExprToType(LHS.get(), CondTy, CK_IntegralCast); 5467 RHS = S.ImpCastExprToType(RHS.get(), CondTy, CK_IntegralCast); 5468 return false; 5469 } 5470 5471 /// \brief Handle when one or both operands are void type. 5472 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 5473 ExprResult &RHS) { 5474 Expr *LHSExpr = LHS.get(); 5475 Expr *RHSExpr = RHS.get(); 5476 5477 if (!LHSExpr->getType()->isVoidType()) 5478 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5479 << RHSExpr->getSourceRange(); 5480 if (!RHSExpr->getType()->isVoidType()) 5481 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5482 << LHSExpr->getSourceRange(); 5483 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 5484 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 5485 return S.Context.VoidTy; 5486 } 5487 5488 /// \brief Return false if the NullExpr can be promoted to PointerTy, 5489 /// true otherwise. 5490 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 5491 QualType PointerTy) { 5492 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 5493 !NullExpr.get()->isNullPointerConstant(S.Context, 5494 Expr::NPC_ValueDependentIsNull)) 5495 return true; 5496 5497 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 5498 return false; 5499 } 5500 5501 /// \brief Checks compatibility between two pointers and return the resulting 5502 /// type. 5503 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 5504 ExprResult &RHS, 5505 SourceLocation Loc) { 5506 QualType LHSTy = LHS.get()->getType(); 5507 QualType RHSTy = RHS.get()->getType(); 5508 5509 if (S.Context.hasSameType(LHSTy, RHSTy)) { 5510 // Two identical pointers types are always compatible. 5511 return LHSTy; 5512 } 5513 5514 QualType lhptee, rhptee; 5515 5516 // Get the pointee types. 5517 bool IsBlockPointer = false; 5518 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 5519 lhptee = LHSBTy->getPointeeType(); 5520 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 5521 IsBlockPointer = true; 5522 } else { 5523 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 5524 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 5525 } 5526 5527 // C99 6.5.15p6: If both operands are pointers to compatible types or to 5528 // differently qualified versions of compatible types, the result type is 5529 // a pointer to an appropriately qualified version of the composite 5530 // type. 5531 5532 // Only CVR-qualifiers exist in the standard, and the differently-qualified 5533 // clause doesn't make sense for our extensions. E.g. address space 2 should 5534 // be incompatible with address space 3: they may live on different devices or 5535 // anything. 5536 Qualifiers lhQual = lhptee.getQualifiers(); 5537 Qualifiers rhQual = rhptee.getQualifiers(); 5538 5539 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 5540 lhQual.removeCVRQualifiers(); 5541 rhQual.removeCVRQualifiers(); 5542 5543 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 5544 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 5545 5546 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 5547 5548 if (CompositeTy.isNull()) { 5549 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers) 5550 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5551 << RHS.get()->getSourceRange(); 5552 // In this situation, we assume void* type. No especially good 5553 // reason, but this is what gcc does, and we do have to pick 5554 // to get a consistent AST. 5555 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 5556 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 5557 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 5558 return incompatTy; 5559 } 5560 5561 // The pointer types are compatible. 5562 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 5563 if (IsBlockPointer) 5564 ResultTy = S.Context.getBlockPointerType(ResultTy); 5565 else 5566 ResultTy = S.Context.getPointerType(ResultTy); 5567 5568 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast); 5569 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast); 5570 return ResultTy; 5571 } 5572 5573 /// \brief Returns true if QT is quelified-id and implements 'NSObject' and/or 5574 /// 'NSCopying' protocols (and nothing else); or QT is an NSObject and optionally 5575 /// implements 'NSObject' and/or NSCopying' protocols (and nothing else). 5576 static bool isObjCPtrBlockCompatible(Sema &S, ASTContext &C, QualType QT) { 5577 if (QT->isObjCIdType()) 5578 return true; 5579 5580 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>(); 5581 if (!OPT) 5582 return false; 5583 5584 if (ObjCInterfaceDecl *ID = OPT->getInterfaceDecl()) 5585 if (ID->getIdentifier() != &C.Idents.get("NSObject")) 5586 return false; 5587 5588 ObjCProtocolDecl* PNSCopying = 5589 S.LookupProtocol(&C.Idents.get("NSCopying"), SourceLocation()); 5590 ObjCProtocolDecl* PNSObject = 5591 S.LookupProtocol(&C.Idents.get("NSObject"), SourceLocation()); 5592 5593 for (auto *Proto : OPT->quals()) { 5594 if ((PNSCopying && declaresSameEntity(Proto, PNSCopying)) || 5595 (PNSObject && declaresSameEntity(Proto, PNSObject))) 5596 ; 5597 else 5598 return false; 5599 } 5600 return true; 5601 } 5602 5603 /// \brief Return the resulting type when the operands are both block pointers. 5604 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 5605 ExprResult &LHS, 5606 ExprResult &RHS, 5607 SourceLocation Loc) { 5608 QualType LHSTy = LHS.get()->getType(); 5609 QualType RHSTy = RHS.get()->getType(); 5610 5611 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 5612 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 5613 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 5614 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 5615 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 5616 return destType; 5617 } 5618 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 5619 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5620 << RHS.get()->getSourceRange(); 5621 return QualType(); 5622 } 5623 5624 // We have 2 block pointer types. 5625 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5626 } 5627 5628 /// \brief Return the resulting type when the operands are both pointers. 5629 static QualType 5630 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 5631 ExprResult &RHS, 5632 SourceLocation Loc) { 5633 // get the pointer types 5634 QualType LHSTy = LHS.get()->getType(); 5635 QualType RHSTy = RHS.get()->getType(); 5636 5637 // get the "pointed to" types 5638 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5639 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5640 5641 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 5642 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 5643 // Figure out necessary qualifiers (C99 6.5.15p6) 5644 QualType destPointee 5645 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5646 QualType destType = S.Context.getPointerType(destPointee); 5647 // Add qualifiers if necessary. 5648 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 5649 // Promote to void*. 5650 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 5651 return destType; 5652 } 5653 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 5654 QualType destPointee 5655 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5656 QualType destType = S.Context.getPointerType(destPointee); 5657 // Add qualifiers if necessary. 5658 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 5659 // Promote to void*. 5660 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 5661 return destType; 5662 } 5663 5664 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5665 } 5666 5667 /// \brief Return false if the first expression is not an integer and the second 5668 /// expression is not a pointer, true otherwise. 5669 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 5670 Expr* PointerExpr, SourceLocation Loc, 5671 bool IsIntFirstExpr) { 5672 if (!PointerExpr->getType()->isPointerType() || 5673 !Int.get()->getType()->isIntegerType()) 5674 return false; 5675 5676 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 5677 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 5678 5679 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch) 5680 << Expr1->getType() << Expr2->getType() 5681 << Expr1->getSourceRange() << Expr2->getSourceRange(); 5682 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 5683 CK_IntegralToPointer); 5684 return true; 5685 } 5686 5687 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 5688 /// In that case, LHS = cond. 5689 /// C99 6.5.15 5690 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 5691 ExprResult &RHS, ExprValueKind &VK, 5692 ExprObjectKind &OK, 5693 SourceLocation QuestionLoc) { 5694 5695 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 5696 if (!LHSResult.isUsable()) return QualType(); 5697 LHS = LHSResult; 5698 5699 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 5700 if (!RHSResult.isUsable()) return QualType(); 5701 RHS = RHSResult; 5702 5703 // C++ is sufficiently different to merit its own checker. 5704 if (getLangOpts().CPlusPlus) 5705 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 5706 5707 VK = VK_RValue; 5708 OK = OK_Ordinary; 5709 5710 // First, check the condition. 5711 Cond = UsualUnaryConversions(Cond.get()); 5712 if (Cond.isInvalid()) 5713 return QualType(); 5714 if (checkCondition(*this, Cond.get())) 5715 return QualType(); 5716 5717 // Now check the two expressions. 5718 if (LHS.get()->getType()->isVectorType() || 5719 RHS.get()->getType()->isVectorType()) 5720 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false); 5721 5722 UsualArithmeticConversions(LHS, RHS); 5723 if (LHS.isInvalid() || RHS.isInvalid()) 5724 return QualType(); 5725 5726 QualType CondTy = Cond.get()->getType(); 5727 QualType LHSTy = LHS.get()->getType(); 5728 QualType RHSTy = RHS.get()->getType(); 5729 5730 // If the condition is a vector, and both operands are scalar, 5731 // attempt to implicity convert them to the vector type to act like the 5732 // built in select. (OpenCL v1.1 s6.3.i) 5733 if (getLangOpts().OpenCL && CondTy->isVectorType()) 5734 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy)) 5735 return QualType(); 5736 5737 // If both operands have arithmetic type, do the usual arithmetic conversions 5738 // to find a common type: C99 6.5.15p3,5. 5739 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) 5740 return LHS.get()->getType(); 5741 5742 // If both operands are the same structure or union type, the result is that 5743 // type. 5744 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 5745 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 5746 if (LHSRT->getDecl() == RHSRT->getDecl()) 5747 // "If both the operands have structure or union type, the result has 5748 // that type." This implies that CV qualifiers are dropped. 5749 return LHSTy.getUnqualifiedType(); 5750 // FIXME: Type of conditional expression must be complete in C mode. 5751 } 5752 5753 // C99 6.5.15p5: "If both operands have void type, the result has void type." 5754 // The following || allows only one side to be void (a GCC-ism). 5755 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 5756 return checkConditionalVoidType(*this, LHS, RHS); 5757 } 5758 5759 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 5760 // the type of the other operand." 5761 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 5762 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 5763 5764 // All objective-c pointer type analysis is done here. 5765 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 5766 QuestionLoc); 5767 if (LHS.isInvalid() || RHS.isInvalid()) 5768 return QualType(); 5769 if (!compositeType.isNull()) 5770 return compositeType; 5771 5772 5773 // Handle block pointer types. 5774 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 5775 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 5776 QuestionLoc); 5777 5778 // Check constraints for C object pointers types (C99 6.5.15p3,6). 5779 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 5780 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 5781 QuestionLoc); 5782 5783 // GCC compatibility: soften pointer/integer mismatch. Note that 5784 // null pointers have been filtered out by this point. 5785 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 5786 /*isIntFirstExpr=*/true)) 5787 return RHSTy; 5788 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 5789 /*isIntFirstExpr=*/false)) 5790 return LHSTy; 5791 5792 // Emit a better diagnostic if one of the expressions is a null pointer 5793 // constant and the other is not a pointer type. In this case, the user most 5794 // likely forgot to take the address of the other expression. 5795 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 5796 return QualType(); 5797 5798 // Otherwise, the operands are not compatible. 5799 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 5800 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5801 << RHS.get()->getSourceRange(); 5802 return QualType(); 5803 } 5804 5805 /// FindCompositeObjCPointerType - Helper method to find composite type of 5806 /// two objective-c pointer types of the two input expressions. 5807 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 5808 SourceLocation QuestionLoc) { 5809 QualType LHSTy = LHS.get()->getType(); 5810 QualType RHSTy = RHS.get()->getType(); 5811 5812 // Handle things like Class and struct objc_class*. Here we case the result 5813 // to the pseudo-builtin, because that will be implicitly cast back to the 5814 // redefinition type if an attempt is made to access its fields. 5815 if (LHSTy->isObjCClassType() && 5816 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 5817 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 5818 return LHSTy; 5819 } 5820 if (RHSTy->isObjCClassType() && 5821 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 5822 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 5823 return RHSTy; 5824 } 5825 // And the same for struct objc_object* / id 5826 if (LHSTy->isObjCIdType() && 5827 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 5828 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 5829 return LHSTy; 5830 } 5831 if (RHSTy->isObjCIdType() && 5832 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 5833 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 5834 return RHSTy; 5835 } 5836 // And the same for struct objc_selector* / SEL 5837 if (Context.isObjCSelType(LHSTy) && 5838 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 5839 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 5840 return LHSTy; 5841 } 5842 if (Context.isObjCSelType(RHSTy) && 5843 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 5844 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 5845 return RHSTy; 5846 } 5847 // Check constraints for Objective-C object pointers types. 5848 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 5849 5850 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 5851 // Two identical object pointer types are always compatible. 5852 return LHSTy; 5853 } 5854 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 5855 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 5856 QualType compositeType = LHSTy; 5857 5858 // If both operands are interfaces and either operand can be 5859 // assigned to the other, use that type as the composite 5860 // type. This allows 5861 // xxx ? (A*) a : (B*) b 5862 // where B is a subclass of A. 5863 // 5864 // Additionally, as for assignment, if either type is 'id' 5865 // allow silent coercion. Finally, if the types are 5866 // incompatible then make sure to use 'id' as the composite 5867 // type so the result is acceptable for sending messages to. 5868 5869 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 5870 // It could return the composite type. 5871 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 5872 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 5873 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 5874 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 5875 } else if ((LHSTy->isObjCQualifiedIdType() || 5876 RHSTy->isObjCQualifiedIdType()) && 5877 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 5878 // Need to handle "id<xx>" explicitly. 5879 // GCC allows qualified id and any Objective-C type to devolve to 5880 // id. Currently localizing to here until clear this should be 5881 // part of ObjCQualifiedIdTypesAreCompatible. 5882 compositeType = Context.getObjCIdType(); 5883 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 5884 compositeType = Context.getObjCIdType(); 5885 } else if (!(compositeType = 5886 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 5887 ; 5888 else { 5889 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 5890 << LHSTy << RHSTy 5891 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5892 QualType incompatTy = Context.getObjCIdType(); 5893 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 5894 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 5895 return incompatTy; 5896 } 5897 // The object pointer types are compatible. 5898 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 5899 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 5900 return compositeType; 5901 } 5902 // Check Objective-C object pointer types and 'void *' 5903 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 5904 if (getLangOpts().ObjCAutoRefCount) { 5905 // ARC forbids the implicit conversion of object pointers to 'void *', 5906 // so these types are not compatible. 5907 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5908 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5909 LHS = RHS = true; 5910 return QualType(); 5911 } 5912 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5913 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5914 QualType destPointee 5915 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5916 QualType destType = Context.getPointerType(destPointee); 5917 // Add qualifiers if necessary. 5918 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 5919 // Promote to void*. 5920 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 5921 return destType; 5922 } 5923 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 5924 if (getLangOpts().ObjCAutoRefCount) { 5925 // ARC forbids the implicit conversion of object pointers to 'void *', 5926 // so these types are not compatible. 5927 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5928 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5929 LHS = RHS = true; 5930 return QualType(); 5931 } 5932 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5933 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5934 QualType destPointee 5935 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5936 QualType destType = Context.getPointerType(destPointee); 5937 // Add qualifiers if necessary. 5938 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 5939 // Promote to void*. 5940 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 5941 return destType; 5942 } 5943 return QualType(); 5944 } 5945 5946 /// SuggestParentheses - Emit a note with a fixit hint that wraps 5947 /// ParenRange in parentheses. 5948 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 5949 const PartialDiagnostic &Note, 5950 SourceRange ParenRange) { 5951 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 5952 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 5953 EndLoc.isValid()) { 5954 Self.Diag(Loc, Note) 5955 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 5956 << FixItHint::CreateInsertion(EndLoc, ")"); 5957 } else { 5958 // We can't display the parentheses, so just show the bare note. 5959 Self.Diag(Loc, Note) << ParenRange; 5960 } 5961 } 5962 5963 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 5964 return Opc >= BO_Mul && Opc <= BO_Shr; 5965 } 5966 5967 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 5968 /// expression, either using a built-in or overloaded operator, 5969 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 5970 /// expression. 5971 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 5972 Expr **RHSExprs) { 5973 // Don't strip parenthesis: we should not warn if E is in parenthesis. 5974 E = E->IgnoreImpCasts(); 5975 E = E->IgnoreConversionOperator(); 5976 E = E->IgnoreImpCasts(); 5977 5978 // Built-in binary operator. 5979 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 5980 if (IsArithmeticOp(OP->getOpcode())) { 5981 *Opcode = OP->getOpcode(); 5982 *RHSExprs = OP->getRHS(); 5983 return true; 5984 } 5985 } 5986 5987 // Overloaded operator. 5988 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 5989 if (Call->getNumArgs() != 2) 5990 return false; 5991 5992 // Make sure this is really a binary operator that is safe to pass into 5993 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 5994 OverloadedOperatorKind OO = Call->getOperator(); 5995 if (OO < OO_Plus || OO > OO_Arrow || 5996 OO == OO_PlusPlus || OO == OO_MinusMinus) 5997 return false; 5998 5999 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 6000 if (IsArithmeticOp(OpKind)) { 6001 *Opcode = OpKind; 6002 *RHSExprs = Call->getArg(1); 6003 return true; 6004 } 6005 } 6006 6007 return false; 6008 } 6009 6010 static bool IsLogicOp(BinaryOperatorKind Opc) { 6011 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 6012 } 6013 6014 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 6015 /// or is a logical expression such as (x==y) which has int type, but is 6016 /// commonly interpreted as boolean. 6017 static bool ExprLooksBoolean(Expr *E) { 6018 E = E->IgnoreParenImpCasts(); 6019 6020 if (E->getType()->isBooleanType()) 6021 return true; 6022 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 6023 return IsLogicOp(OP->getOpcode()); 6024 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 6025 return OP->getOpcode() == UO_LNot; 6026 6027 return false; 6028 } 6029 6030 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 6031 /// and binary operator are mixed in a way that suggests the programmer assumed 6032 /// the conditional operator has higher precedence, for example: 6033 /// "int x = a + someBinaryCondition ? 1 : 2". 6034 static void DiagnoseConditionalPrecedence(Sema &Self, 6035 SourceLocation OpLoc, 6036 Expr *Condition, 6037 Expr *LHSExpr, 6038 Expr *RHSExpr) { 6039 BinaryOperatorKind CondOpcode; 6040 Expr *CondRHS; 6041 6042 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 6043 return; 6044 if (!ExprLooksBoolean(CondRHS)) 6045 return; 6046 6047 // The condition is an arithmetic binary expression, with a right- 6048 // hand side that looks boolean, so warn. 6049 6050 Self.Diag(OpLoc, diag::warn_precedence_conditional) 6051 << Condition->getSourceRange() 6052 << BinaryOperator::getOpcodeStr(CondOpcode); 6053 6054 SuggestParentheses(Self, OpLoc, 6055 Self.PDiag(diag::note_precedence_silence) 6056 << BinaryOperator::getOpcodeStr(CondOpcode), 6057 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 6058 6059 SuggestParentheses(Self, OpLoc, 6060 Self.PDiag(diag::note_precedence_conditional_first), 6061 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 6062 } 6063 6064 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 6065 /// in the case of a the GNU conditional expr extension. 6066 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 6067 SourceLocation ColonLoc, 6068 Expr *CondExpr, Expr *LHSExpr, 6069 Expr *RHSExpr) { 6070 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 6071 // was the condition. 6072 OpaqueValueExpr *opaqueValue = nullptr; 6073 Expr *commonExpr = nullptr; 6074 if (!LHSExpr) { 6075 commonExpr = CondExpr; 6076 // Lower out placeholder types first. This is important so that we don't 6077 // try to capture a placeholder. This happens in few cases in C++; such 6078 // as Objective-C++'s dictionary subscripting syntax. 6079 if (commonExpr->hasPlaceholderType()) { 6080 ExprResult result = CheckPlaceholderExpr(commonExpr); 6081 if (!result.isUsable()) return ExprError(); 6082 commonExpr = result.get(); 6083 } 6084 // We usually want to apply unary conversions *before* saving, except 6085 // in the special case of a C++ l-value conditional. 6086 if (!(getLangOpts().CPlusPlus 6087 && !commonExpr->isTypeDependent() 6088 && commonExpr->getValueKind() == RHSExpr->getValueKind() 6089 && commonExpr->isGLValue() 6090 && commonExpr->isOrdinaryOrBitFieldObject() 6091 && RHSExpr->isOrdinaryOrBitFieldObject() 6092 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 6093 ExprResult commonRes = UsualUnaryConversions(commonExpr); 6094 if (commonRes.isInvalid()) 6095 return ExprError(); 6096 commonExpr = commonRes.get(); 6097 } 6098 6099 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 6100 commonExpr->getType(), 6101 commonExpr->getValueKind(), 6102 commonExpr->getObjectKind(), 6103 commonExpr); 6104 LHSExpr = CondExpr = opaqueValue; 6105 } 6106 6107 ExprValueKind VK = VK_RValue; 6108 ExprObjectKind OK = OK_Ordinary; 6109 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 6110 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 6111 VK, OK, QuestionLoc); 6112 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 6113 RHS.isInvalid()) 6114 return ExprError(); 6115 6116 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 6117 RHS.get()); 6118 6119 if (!commonExpr) 6120 return new (Context) 6121 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 6122 RHS.get(), result, VK, OK); 6123 6124 return new (Context) BinaryConditionalOperator( 6125 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 6126 ColonLoc, result, VK, OK); 6127 } 6128 6129 // checkPointerTypesForAssignment - This is a very tricky routine (despite 6130 // being closely modeled after the C99 spec:-). The odd characteristic of this 6131 // routine is it effectively iqnores the qualifiers on the top level pointee. 6132 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 6133 // FIXME: add a couple examples in this comment. 6134 static Sema::AssignConvertType 6135 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 6136 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6137 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6138 6139 // get the "pointed to" type (ignoring qualifiers at the top level) 6140 const Type *lhptee, *rhptee; 6141 Qualifiers lhq, rhq; 6142 std::tie(lhptee, lhq) = 6143 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 6144 std::tie(rhptee, rhq) = 6145 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 6146 6147 Sema::AssignConvertType ConvTy = Sema::Compatible; 6148 6149 // C99 6.5.16.1p1: This following citation is common to constraints 6150 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 6151 // qualifiers of the type *pointed to* by the right; 6152 6153 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 6154 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 6155 lhq.compatiblyIncludesObjCLifetime(rhq)) { 6156 // Ignore lifetime for further calculation. 6157 lhq.removeObjCLifetime(); 6158 rhq.removeObjCLifetime(); 6159 } 6160 6161 if (!lhq.compatiblyIncludes(rhq)) { 6162 // Treat address-space mismatches as fatal. TODO: address subspaces 6163 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 6164 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6165 6166 // It's okay to add or remove GC or lifetime qualifiers when converting to 6167 // and from void*. 6168 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 6169 .compatiblyIncludes( 6170 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 6171 && (lhptee->isVoidType() || rhptee->isVoidType())) 6172 ; // keep old 6173 6174 // Treat lifetime mismatches as fatal. 6175 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 6176 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6177 6178 // For GCC compatibility, other qualifier mismatches are treated 6179 // as still compatible in C. 6180 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6181 } 6182 6183 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 6184 // incomplete type and the other is a pointer to a qualified or unqualified 6185 // version of void... 6186 if (lhptee->isVoidType()) { 6187 if (rhptee->isIncompleteOrObjectType()) 6188 return ConvTy; 6189 6190 // As an extension, we allow cast to/from void* to function pointer. 6191 assert(rhptee->isFunctionType()); 6192 return Sema::FunctionVoidPointer; 6193 } 6194 6195 if (rhptee->isVoidType()) { 6196 if (lhptee->isIncompleteOrObjectType()) 6197 return ConvTy; 6198 6199 // As an extension, we allow cast to/from void* to function pointer. 6200 assert(lhptee->isFunctionType()); 6201 return Sema::FunctionVoidPointer; 6202 } 6203 6204 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 6205 // unqualified versions of compatible types, ... 6206 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 6207 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 6208 // Check if the pointee types are compatible ignoring the sign. 6209 // We explicitly check for char so that we catch "char" vs 6210 // "unsigned char" on systems where "char" is unsigned. 6211 if (lhptee->isCharType()) 6212 ltrans = S.Context.UnsignedCharTy; 6213 else if (lhptee->hasSignedIntegerRepresentation()) 6214 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 6215 6216 if (rhptee->isCharType()) 6217 rtrans = S.Context.UnsignedCharTy; 6218 else if (rhptee->hasSignedIntegerRepresentation()) 6219 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 6220 6221 if (ltrans == rtrans) { 6222 // Types are compatible ignoring the sign. Qualifier incompatibility 6223 // takes priority over sign incompatibility because the sign 6224 // warning can be disabled. 6225 if (ConvTy != Sema::Compatible) 6226 return ConvTy; 6227 6228 return Sema::IncompatiblePointerSign; 6229 } 6230 6231 // If we are a multi-level pointer, it's possible that our issue is simply 6232 // one of qualification - e.g. char ** -> const char ** is not allowed. If 6233 // the eventual target type is the same and the pointers have the same 6234 // level of indirection, this must be the issue. 6235 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 6236 do { 6237 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 6238 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 6239 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 6240 6241 if (lhptee == rhptee) 6242 return Sema::IncompatibleNestedPointerQualifiers; 6243 } 6244 6245 // General pointer incompatibility takes priority over qualifiers. 6246 return Sema::IncompatiblePointer; 6247 } 6248 if (!S.getLangOpts().CPlusPlus && 6249 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 6250 return Sema::IncompatiblePointer; 6251 return ConvTy; 6252 } 6253 6254 /// checkBlockPointerTypesForAssignment - This routine determines whether two 6255 /// block pointer types are compatible or whether a block and normal pointer 6256 /// are compatible. It is more restrict than comparing two function pointer 6257 // types. 6258 static Sema::AssignConvertType 6259 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 6260 QualType RHSType) { 6261 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6262 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6263 6264 QualType lhptee, rhptee; 6265 6266 // get the "pointed to" type (ignoring qualifiers at the top level) 6267 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 6268 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 6269 6270 // In C++, the types have to match exactly. 6271 if (S.getLangOpts().CPlusPlus) 6272 return Sema::IncompatibleBlockPointer; 6273 6274 Sema::AssignConvertType ConvTy = Sema::Compatible; 6275 6276 // For blocks we enforce that qualifiers are identical. 6277 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 6278 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6279 6280 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 6281 return Sema::IncompatibleBlockPointer; 6282 6283 return ConvTy; 6284 } 6285 6286 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 6287 /// for assignment compatibility. 6288 static Sema::AssignConvertType 6289 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 6290 QualType RHSType) { 6291 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 6292 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 6293 6294 if (LHSType->isObjCBuiltinType()) { 6295 // Class is not compatible with ObjC object pointers. 6296 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 6297 !RHSType->isObjCQualifiedClassType()) 6298 return Sema::IncompatiblePointer; 6299 return Sema::Compatible; 6300 } 6301 if (RHSType->isObjCBuiltinType()) { 6302 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 6303 !LHSType->isObjCQualifiedClassType()) 6304 return Sema::IncompatiblePointer; 6305 return Sema::Compatible; 6306 } 6307 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6308 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6309 6310 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 6311 // make an exception for id<P> 6312 !LHSType->isObjCQualifiedIdType()) 6313 return Sema::CompatiblePointerDiscardsQualifiers; 6314 6315 if (S.Context.typesAreCompatible(LHSType, RHSType)) 6316 return Sema::Compatible; 6317 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 6318 return Sema::IncompatibleObjCQualifiedId; 6319 return Sema::IncompatiblePointer; 6320 } 6321 6322 Sema::AssignConvertType 6323 Sema::CheckAssignmentConstraints(SourceLocation Loc, 6324 QualType LHSType, QualType RHSType) { 6325 // Fake up an opaque expression. We don't actually care about what 6326 // cast operations are required, so if CheckAssignmentConstraints 6327 // adds casts to this they'll be wasted, but fortunately that doesn't 6328 // usually happen on valid code. 6329 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 6330 ExprResult RHSPtr = &RHSExpr; 6331 CastKind K = CK_Invalid; 6332 6333 return CheckAssignmentConstraints(LHSType, RHSPtr, K); 6334 } 6335 6336 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 6337 /// has code to accommodate several GCC extensions when type checking 6338 /// pointers. Here are some objectionable examples that GCC considers warnings: 6339 /// 6340 /// int a, *pint; 6341 /// short *pshort; 6342 /// struct foo *pfoo; 6343 /// 6344 /// pint = pshort; // warning: assignment from incompatible pointer type 6345 /// a = pint; // warning: assignment makes integer from pointer without a cast 6346 /// pint = a; // warning: assignment makes pointer from integer without a cast 6347 /// pint = pfoo; // warning: assignment from incompatible pointer type 6348 /// 6349 /// As a result, the code for dealing with pointers is more complex than the 6350 /// C99 spec dictates. 6351 /// 6352 /// Sets 'Kind' for any result kind except Incompatible. 6353 Sema::AssignConvertType 6354 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6355 CastKind &Kind) { 6356 QualType RHSType = RHS.get()->getType(); 6357 QualType OrigLHSType = LHSType; 6358 6359 // Get canonical types. We're not formatting these types, just comparing 6360 // them. 6361 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 6362 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 6363 6364 // Common case: no conversion required. 6365 if (LHSType == RHSType) { 6366 Kind = CK_NoOp; 6367 return Compatible; 6368 } 6369 6370 // If we have an atomic type, try a non-atomic assignment, then just add an 6371 // atomic qualification step. 6372 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 6373 Sema::AssignConvertType result = 6374 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 6375 if (result != Compatible) 6376 return result; 6377 if (Kind != CK_NoOp) 6378 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 6379 Kind = CK_NonAtomicToAtomic; 6380 return Compatible; 6381 } 6382 6383 // If the left-hand side is a reference type, then we are in a 6384 // (rare!) case where we've allowed the use of references in C, 6385 // e.g., as a parameter type in a built-in function. In this case, 6386 // just make sure that the type referenced is compatible with the 6387 // right-hand side type. The caller is responsible for adjusting 6388 // LHSType so that the resulting expression does not have reference 6389 // type. 6390 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 6391 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 6392 Kind = CK_LValueBitCast; 6393 return Compatible; 6394 } 6395 return Incompatible; 6396 } 6397 6398 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 6399 // to the same ExtVector type. 6400 if (LHSType->isExtVectorType()) { 6401 if (RHSType->isExtVectorType()) 6402 return Incompatible; 6403 if (RHSType->isArithmeticType()) { 6404 // CK_VectorSplat does T -> vector T, so first cast to the 6405 // element type. 6406 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 6407 if (elType != RHSType) { 6408 Kind = PrepareScalarCast(RHS, elType); 6409 RHS = ImpCastExprToType(RHS.get(), elType, Kind); 6410 } 6411 Kind = CK_VectorSplat; 6412 return Compatible; 6413 } 6414 } 6415 6416 // Conversions to or from vector type. 6417 if (LHSType->isVectorType() || RHSType->isVectorType()) { 6418 if (LHSType->isVectorType() && RHSType->isVectorType()) { 6419 // Allow assignments of an AltiVec vector type to an equivalent GCC 6420 // vector type and vice versa 6421 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6422 Kind = CK_BitCast; 6423 return Compatible; 6424 } 6425 6426 // If we are allowing lax vector conversions, and LHS and RHS are both 6427 // vectors, the total size only needs to be the same. This is a bitcast; 6428 // no bits are changed but the result type is different. 6429 if (isLaxVectorConversion(RHSType, LHSType)) { 6430 Kind = CK_BitCast; 6431 return IncompatibleVectors; 6432 } 6433 } 6434 return Incompatible; 6435 } 6436 6437 // Arithmetic conversions. 6438 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 6439 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 6440 Kind = PrepareScalarCast(RHS, LHSType); 6441 return Compatible; 6442 } 6443 6444 // Conversions to normal pointers. 6445 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 6446 // U* -> T* 6447 if (isa<PointerType>(RHSType)) { 6448 Kind = CK_BitCast; 6449 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 6450 } 6451 6452 // int -> T* 6453 if (RHSType->isIntegerType()) { 6454 Kind = CK_IntegralToPointer; // FIXME: null? 6455 return IntToPointer; 6456 } 6457 6458 // C pointers are not compatible with ObjC object pointers, 6459 // with two exceptions: 6460 if (isa<ObjCObjectPointerType>(RHSType)) { 6461 // - conversions to void* 6462 if (LHSPointer->getPointeeType()->isVoidType()) { 6463 Kind = CK_BitCast; 6464 return Compatible; 6465 } 6466 6467 // - conversions from 'Class' to the redefinition type 6468 if (RHSType->isObjCClassType() && 6469 Context.hasSameType(LHSType, 6470 Context.getObjCClassRedefinitionType())) { 6471 Kind = CK_BitCast; 6472 return Compatible; 6473 } 6474 6475 Kind = CK_BitCast; 6476 return IncompatiblePointer; 6477 } 6478 6479 // U^ -> void* 6480 if (RHSType->getAs<BlockPointerType>()) { 6481 if (LHSPointer->getPointeeType()->isVoidType()) { 6482 Kind = CK_BitCast; 6483 return Compatible; 6484 } 6485 } 6486 6487 return Incompatible; 6488 } 6489 6490 // Conversions to block pointers. 6491 if (isa<BlockPointerType>(LHSType)) { 6492 // U^ -> T^ 6493 if (RHSType->isBlockPointerType()) { 6494 Kind = CK_BitCast; 6495 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 6496 } 6497 6498 // int or null -> T^ 6499 if (RHSType->isIntegerType()) { 6500 Kind = CK_IntegralToPointer; // FIXME: null 6501 return IntToBlockPointer; 6502 } 6503 6504 // id -> T^ 6505 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 6506 Kind = CK_AnyPointerToBlockPointerCast; 6507 return Compatible; 6508 } 6509 6510 // void* -> T^ 6511 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 6512 if (RHSPT->getPointeeType()->isVoidType()) { 6513 Kind = CK_AnyPointerToBlockPointerCast; 6514 return Compatible; 6515 } 6516 6517 return Incompatible; 6518 } 6519 6520 // Conversions to Objective-C pointers. 6521 if (isa<ObjCObjectPointerType>(LHSType)) { 6522 // A* -> B* 6523 if (RHSType->isObjCObjectPointerType()) { 6524 Kind = CK_BitCast; 6525 Sema::AssignConvertType result = 6526 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 6527 if (getLangOpts().ObjCAutoRefCount && 6528 result == Compatible && 6529 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 6530 result = IncompatibleObjCWeakRef; 6531 return result; 6532 } 6533 6534 // int or null -> A* 6535 if (RHSType->isIntegerType()) { 6536 Kind = CK_IntegralToPointer; // FIXME: null 6537 return IntToPointer; 6538 } 6539 6540 // In general, C pointers are not compatible with ObjC object pointers, 6541 // with two exceptions: 6542 if (isa<PointerType>(RHSType)) { 6543 Kind = CK_CPointerToObjCPointerCast; 6544 6545 // - conversions from 'void*' 6546 if (RHSType->isVoidPointerType()) { 6547 return Compatible; 6548 } 6549 6550 // - conversions to 'Class' from its redefinition type 6551 if (LHSType->isObjCClassType() && 6552 Context.hasSameType(RHSType, 6553 Context.getObjCClassRedefinitionType())) { 6554 return Compatible; 6555 } 6556 6557 return IncompatiblePointer; 6558 } 6559 6560 // Only under strict condition T^ is compatible with an Objective-C pointer. 6561 if (RHSType->isBlockPointerType() && 6562 isObjCPtrBlockCompatible(*this, Context, LHSType)) { 6563 maybeExtendBlockObject(*this, RHS); 6564 Kind = CK_BlockPointerToObjCPointerCast; 6565 return Compatible; 6566 } 6567 6568 return Incompatible; 6569 } 6570 6571 // Conversions from pointers that are not covered by the above. 6572 if (isa<PointerType>(RHSType)) { 6573 // T* -> _Bool 6574 if (LHSType == Context.BoolTy) { 6575 Kind = CK_PointerToBoolean; 6576 return Compatible; 6577 } 6578 6579 // T* -> int 6580 if (LHSType->isIntegerType()) { 6581 Kind = CK_PointerToIntegral; 6582 return PointerToInt; 6583 } 6584 6585 return Incompatible; 6586 } 6587 6588 // Conversions from Objective-C pointers that are not covered by the above. 6589 if (isa<ObjCObjectPointerType>(RHSType)) { 6590 // T* -> _Bool 6591 if (LHSType == Context.BoolTy) { 6592 Kind = CK_PointerToBoolean; 6593 return Compatible; 6594 } 6595 6596 // T* -> int 6597 if (LHSType->isIntegerType()) { 6598 Kind = CK_PointerToIntegral; 6599 return PointerToInt; 6600 } 6601 6602 return Incompatible; 6603 } 6604 6605 // struct A -> struct B 6606 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 6607 if (Context.typesAreCompatible(LHSType, RHSType)) { 6608 Kind = CK_NoOp; 6609 return Compatible; 6610 } 6611 } 6612 6613 return Incompatible; 6614 } 6615 6616 /// \brief Constructs a transparent union from an expression that is 6617 /// used to initialize the transparent union. 6618 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 6619 ExprResult &EResult, QualType UnionType, 6620 FieldDecl *Field) { 6621 // Build an initializer list that designates the appropriate member 6622 // of the transparent union. 6623 Expr *E = EResult.get(); 6624 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 6625 E, SourceLocation()); 6626 Initializer->setType(UnionType); 6627 Initializer->setInitializedFieldInUnion(Field); 6628 6629 // Build a compound literal constructing a value of the transparent 6630 // union type from this initializer list. 6631 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 6632 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 6633 VK_RValue, Initializer, false); 6634 } 6635 6636 Sema::AssignConvertType 6637 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 6638 ExprResult &RHS) { 6639 QualType RHSType = RHS.get()->getType(); 6640 6641 // If the ArgType is a Union type, we want to handle a potential 6642 // transparent_union GCC extension. 6643 const RecordType *UT = ArgType->getAsUnionType(); 6644 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 6645 return Incompatible; 6646 6647 // The field to initialize within the transparent union. 6648 RecordDecl *UD = UT->getDecl(); 6649 FieldDecl *InitField = nullptr; 6650 // It's compatible if the expression matches any of the fields. 6651 for (auto *it : UD->fields()) { 6652 if (it->getType()->isPointerType()) { 6653 // If the transparent union contains a pointer type, we allow: 6654 // 1) void pointer 6655 // 2) null pointer constant 6656 if (RHSType->isPointerType()) 6657 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 6658 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 6659 InitField = it; 6660 break; 6661 } 6662 6663 if (RHS.get()->isNullPointerConstant(Context, 6664 Expr::NPC_ValueDependentIsNull)) { 6665 RHS = ImpCastExprToType(RHS.get(), it->getType(), 6666 CK_NullToPointer); 6667 InitField = it; 6668 break; 6669 } 6670 } 6671 6672 CastKind Kind = CK_Invalid; 6673 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 6674 == Compatible) { 6675 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 6676 InitField = it; 6677 break; 6678 } 6679 } 6680 6681 if (!InitField) 6682 return Incompatible; 6683 6684 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 6685 return Compatible; 6686 } 6687 6688 Sema::AssignConvertType 6689 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6690 bool Diagnose, 6691 bool DiagnoseCFAudited) { 6692 if (getLangOpts().CPlusPlus) { 6693 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 6694 // C++ 5.17p3: If the left operand is not of class type, the 6695 // expression is implicitly converted (C++ 4) to the 6696 // cv-unqualified type of the left operand. 6697 ExprResult Res; 6698 if (Diagnose) { 6699 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6700 AA_Assigning); 6701 } else { 6702 ImplicitConversionSequence ICS = 6703 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6704 /*SuppressUserConversions=*/false, 6705 /*AllowExplicit=*/false, 6706 /*InOverloadResolution=*/false, 6707 /*CStyle=*/false, 6708 /*AllowObjCWritebackConversion=*/false); 6709 if (ICS.isFailure()) 6710 return Incompatible; 6711 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6712 ICS, AA_Assigning); 6713 } 6714 if (Res.isInvalid()) 6715 return Incompatible; 6716 Sema::AssignConvertType result = Compatible; 6717 if (getLangOpts().ObjCAutoRefCount && 6718 !CheckObjCARCUnavailableWeakConversion(LHSType, 6719 RHS.get()->getType())) 6720 result = IncompatibleObjCWeakRef; 6721 RHS = Res; 6722 return result; 6723 } 6724 6725 // FIXME: Currently, we fall through and treat C++ classes like C 6726 // structures. 6727 // FIXME: We also fall through for atomics; not sure what should 6728 // happen there, though. 6729 } 6730 6731 // C99 6.5.16.1p1: the left operand is a pointer and the right is 6732 // a null pointer constant. 6733 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 6734 LHSType->isBlockPointerType()) && 6735 RHS.get()->isNullPointerConstant(Context, 6736 Expr::NPC_ValueDependentIsNull)) { 6737 CastKind Kind; 6738 CXXCastPath Path; 6739 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false); 6740 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 6741 return Compatible; 6742 } 6743 6744 // This check seems unnatural, however it is necessary to ensure the proper 6745 // conversion of functions/arrays. If the conversion were done for all 6746 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 6747 // expressions that suppress this implicit conversion (&, sizeof). 6748 // 6749 // Suppress this for references: C++ 8.5.3p5. 6750 if (!LHSType->isReferenceType()) { 6751 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 6752 if (RHS.isInvalid()) 6753 return Incompatible; 6754 } 6755 6756 CastKind Kind = CK_Invalid; 6757 Sema::AssignConvertType result = 6758 CheckAssignmentConstraints(LHSType, RHS, Kind); 6759 6760 // C99 6.5.16.1p2: The value of the right operand is converted to the 6761 // type of the assignment expression. 6762 // CheckAssignmentConstraints allows the left-hand side to be a reference, 6763 // so that we can use references in built-in functions even in C. 6764 // The getNonReferenceType() call makes sure that the resulting expression 6765 // does not have reference type. 6766 if (result != Incompatible && RHS.get()->getType() != LHSType) { 6767 QualType Ty = LHSType.getNonLValueExprType(Context); 6768 Expr *E = RHS.get(); 6769 if (getLangOpts().ObjCAutoRefCount) 6770 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 6771 DiagnoseCFAudited); 6772 if (getLangOpts().ObjC1 && 6773 (CheckObjCBridgeRelatedConversions(E->getLocStart(), 6774 LHSType, E->getType(), E) || 6775 ConversionToObjCStringLiteralCheck(LHSType, E))) { 6776 RHS = E; 6777 return Compatible; 6778 } 6779 6780 RHS = ImpCastExprToType(E, Ty, Kind); 6781 } 6782 return result; 6783 } 6784 6785 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 6786 ExprResult &RHS) { 6787 Diag(Loc, diag::err_typecheck_invalid_operands) 6788 << LHS.get()->getType() << RHS.get()->getType() 6789 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6790 return QualType(); 6791 } 6792 6793 /// Try to convert a value of non-vector type to a vector type by converting 6794 /// the type to the element type of the vector and then performing a splat. 6795 /// If the language is OpenCL, we only use conversions that promote scalar 6796 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 6797 /// for float->int. 6798 /// 6799 /// \param scalar - if non-null, actually perform the conversions 6800 /// \return true if the operation fails (but without diagnosing the failure) 6801 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 6802 QualType scalarTy, 6803 QualType vectorEltTy, 6804 QualType vectorTy) { 6805 // The conversion to apply to the scalar before splatting it, 6806 // if necessary. 6807 CastKind scalarCast = CK_Invalid; 6808 6809 if (vectorEltTy->isIntegralType(S.Context)) { 6810 if (!scalarTy->isIntegralType(S.Context)) 6811 return true; 6812 if (S.getLangOpts().OpenCL && 6813 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 6814 return true; 6815 scalarCast = CK_IntegralCast; 6816 } else if (vectorEltTy->isRealFloatingType()) { 6817 if (scalarTy->isRealFloatingType()) { 6818 if (S.getLangOpts().OpenCL && 6819 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 6820 return true; 6821 scalarCast = CK_FloatingCast; 6822 } 6823 else if (scalarTy->isIntegralType(S.Context)) 6824 scalarCast = CK_IntegralToFloating; 6825 else 6826 return true; 6827 } else { 6828 return true; 6829 } 6830 6831 // Adjust scalar if desired. 6832 if (scalar) { 6833 if (scalarCast != CK_Invalid) 6834 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 6835 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 6836 } 6837 return false; 6838 } 6839 6840 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 6841 SourceLocation Loc, bool IsCompAssign) { 6842 if (!IsCompAssign) { 6843 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 6844 if (LHS.isInvalid()) 6845 return QualType(); 6846 } 6847 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 6848 if (RHS.isInvalid()) 6849 return QualType(); 6850 6851 // For conversion purposes, we ignore any qualifiers. 6852 // For example, "const float" and "float" are equivalent. 6853 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 6854 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 6855 6856 // If the vector types are identical, return. 6857 if (Context.hasSameType(LHSType, RHSType)) 6858 return LHSType; 6859 6860 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 6861 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 6862 assert(LHSVecType || RHSVecType); 6863 6864 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 6865 if (LHSVecType && RHSVecType && 6866 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6867 if (isa<ExtVectorType>(LHSVecType)) { 6868 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 6869 return LHSType; 6870 } 6871 6872 if (!IsCompAssign) 6873 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 6874 return RHSType; 6875 } 6876 6877 // If there's an ext-vector type and a scalar, try to convert the scalar to 6878 // the vector element type and splat. 6879 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 6880 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 6881 LHSVecType->getElementType(), LHSType)) 6882 return LHSType; 6883 } 6884 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 6885 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 6886 LHSType, RHSVecType->getElementType(), 6887 RHSType)) 6888 return RHSType; 6889 } 6890 6891 // If we're allowing lax vector conversions, only the total (data) size 6892 // needs to be the same. 6893 // FIXME: Should we really be allowing this? 6894 // FIXME: We really just pick the LHS type arbitrarily? 6895 if (isLaxVectorConversion(RHSType, LHSType)) { 6896 QualType resultType = LHSType; 6897 RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast); 6898 return resultType; 6899 } 6900 6901 // Okay, the expression is invalid. 6902 6903 // If there's a non-vector, non-real operand, diagnose that. 6904 if ((!RHSVecType && !RHSType->isRealType()) || 6905 (!LHSVecType && !LHSType->isRealType())) { 6906 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 6907 << LHSType << RHSType 6908 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6909 return QualType(); 6910 } 6911 6912 // Otherwise, use the generic diagnostic. 6913 Diag(Loc, diag::err_typecheck_vector_not_convertable) 6914 << LHSType << RHSType 6915 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6916 return QualType(); 6917 } 6918 6919 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 6920 // expression. These are mainly cases where the null pointer is used as an 6921 // integer instead of a pointer. 6922 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 6923 SourceLocation Loc, bool IsCompare) { 6924 // The canonical way to check for a GNU null is with isNullPointerConstant, 6925 // but we use a bit of a hack here for speed; this is a relatively 6926 // hot path, and isNullPointerConstant is slow. 6927 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 6928 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 6929 6930 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 6931 6932 // Avoid analyzing cases where the result will either be invalid (and 6933 // diagnosed as such) or entirely valid and not something to warn about. 6934 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 6935 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 6936 return; 6937 6938 // Comparison operations would not make sense with a null pointer no matter 6939 // what the other expression is. 6940 if (!IsCompare) { 6941 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 6942 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 6943 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 6944 return; 6945 } 6946 6947 // The rest of the operations only make sense with a null pointer 6948 // if the other expression is a pointer. 6949 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 6950 NonNullType->canDecayToPointerType()) 6951 return; 6952 6953 S.Diag(Loc, diag::warn_null_in_comparison_operation) 6954 << LHSNull /* LHS is NULL */ << NonNullType 6955 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6956 } 6957 6958 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 6959 SourceLocation Loc, 6960 bool IsCompAssign, bool IsDiv) { 6961 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6962 6963 if (LHS.get()->getType()->isVectorType() || 6964 RHS.get()->getType()->isVectorType()) 6965 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6966 6967 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6968 if (LHS.isInvalid() || RHS.isInvalid()) 6969 return QualType(); 6970 6971 6972 if (compType.isNull() || !compType->isArithmeticType()) 6973 return InvalidOperands(Loc, LHS, RHS); 6974 6975 // Check for division by zero. 6976 llvm::APSInt RHSValue; 6977 if (IsDiv && !RHS.get()->isValueDependent() && 6978 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0) 6979 DiagRuntimeBehavior(Loc, RHS.get(), 6980 PDiag(diag::warn_division_by_zero) 6981 << RHS.get()->getSourceRange()); 6982 6983 return compType; 6984 } 6985 6986 QualType Sema::CheckRemainderOperands( 6987 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 6988 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6989 6990 if (LHS.get()->getType()->isVectorType() || 6991 RHS.get()->getType()->isVectorType()) { 6992 if (LHS.get()->getType()->hasIntegerRepresentation() && 6993 RHS.get()->getType()->hasIntegerRepresentation()) 6994 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6995 return InvalidOperands(Loc, LHS, RHS); 6996 } 6997 6998 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6999 if (LHS.isInvalid() || RHS.isInvalid()) 7000 return QualType(); 7001 7002 if (compType.isNull() || !compType->isIntegerType()) 7003 return InvalidOperands(Loc, LHS, RHS); 7004 7005 // Check for remainder by zero. 7006 llvm::APSInt RHSValue; 7007 if (!RHS.get()->isValueDependent() && 7008 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0) 7009 DiagRuntimeBehavior(Loc, RHS.get(), 7010 PDiag(diag::warn_remainder_by_zero) 7011 << RHS.get()->getSourceRange()); 7012 7013 return compType; 7014 } 7015 7016 /// \brief Diagnose invalid arithmetic on two void pointers. 7017 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 7018 Expr *LHSExpr, Expr *RHSExpr) { 7019 S.Diag(Loc, S.getLangOpts().CPlusPlus 7020 ? diag::err_typecheck_pointer_arith_void_type 7021 : diag::ext_gnu_void_ptr) 7022 << 1 /* two pointers */ << LHSExpr->getSourceRange() 7023 << RHSExpr->getSourceRange(); 7024 } 7025 7026 /// \brief Diagnose invalid arithmetic on a void pointer. 7027 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 7028 Expr *Pointer) { 7029 S.Diag(Loc, S.getLangOpts().CPlusPlus 7030 ? diag::err_typecheck_pointer_arith_void_type 7031 : diag::ext_gnu_void_ptr) 7032 << 0 /* one pointer */ << Pointer->getSourceRange(); 7033 } 7034 7035 /// \brief Diagnose invalid arithmetic on two function pointers. 7036 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 7037 Expr *LHS, Expr *RHS) { 7038 assert(LHS->getType()->isAnyPointerType()); 7039 assert(RHS->getType()->isAnyPointerType()); 7040 S.Diag(Loc, S.getLangOpts().CPlusPlus 7041 ? diag::err_typecheck_pointer_arith_function_type 7042 : diag::ext_gnu_ptr_func_arith) 7043 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 7044 // We only show the second type if it differs from the first. 7045 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 7046 RHS->getType()) 7047 << RHS->getType()->getPointeeType() 7048 << LHS->getSourceRange() << RHS->getSourceRange(); 7049 } 7050 7051 /// \brief Diagnose invalid arithmetic on a function pointer. 7052 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 7053 Expr *Pointer) { 7054 assert(Pointer->getType()->isAnyPointerType()); 7055 S.Diag(Loc, S.getLangOpts().CPlusPlus 7056 ? diag::err_typecheck_pointer_arith_function_type 7057 : diag::ext_gnu_ptr_func_arith) 7058 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 7059 << 0 /* one pointer, so only one type */ 7060 << Pointer->getSourceRange(); 7061 } 7062 7063 /// \brief Emit error if Operand is incomplete pointer type 7064 /// 7065 /// \returns True if pointer has incomplete type 7066 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 7067 Expr *Operand) { 7068 assert(Operand->getType()->isAnyPointerType() && 7069 !Operand->getType()->isDependentType()); 7070 QualType PointeeTy = Operand->getType()->getPointeeType(); 7071 return S.RequireCompleteType(Loc, PointeeTy, 7072 diag::err_typecheck_arithmetic_incomplete_type, 7073 PointeeTy, Operand->getSourceRange()); 7074 } 7075 7076 /// \brief Check the validity of an arithmetic pointer operand. 7077 /// 7078 /// If the operand has pointer type, this code will check for pointer types 7079 /// which are invalid in arithmetic operations. These will be diagnosed 7080 /// appropriately, including whether or not the use is supported as an 7081 /// extension. 7082 /// 7083 /// \returns True when the operand is valid to use (even if as an extension). 7084 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 7085 Expr *Operand) { 7086 if (!Operand->getType()->isAnyPointerType()) return true; 7087 7088 QualType PointeeTy = Operand->getType()->getPointeeType(); 7089 if (PointeeTy->isVoidType()) { 7090 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 7091 return !S.getLangOpts().CPlusPlus; 7092 } 7093 if (PointeeTy->isFunctionType()) { 7094 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 7095 return !S.getLangOpts().CPlusPlus; 7096 } 7097 7098 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 7099 7100 return true; 7101 } 7102 7103 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 7104 /// operands. 7105 /// 7106 /// This routine will diagnose any invalid arithmetic on pointer operands much 7107 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 7108 /// for emitting a single diagnostic even for operations where both LHS and RHS 7109 /// are (potentially problematic) pointers. 7110 /// 7111 /// \returns True when the operand is valid to use (even if as an extension). 7112 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 7113 Expr *LHSExpr, Expr *RHSExpr) { 7114 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 7115 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 7116 if (!isLHSPointer && !isRHSPointer) return true; 7117 7118 QualType LHSPointeeTy, RHSPointeeTy; 7119 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 7120 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 7121 7122 // Check for arithmetic on pointers to incomplete types. 7123 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 7124 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 7125 if (isLHSVoidPtr || isRHSVoidPtr) { 7126 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 7127 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 7128 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 7129 7130 return !S.getLangOpts().CPlusPlus; 7131 } 7132 7133 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 7134 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 7135 if (isLHSFuncPtr || isRHSFuncPtr) { 7136 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 7137 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 7138 RHSExpr); 7139 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 7140 7141 return !S.getLangOpts().CPlusPlus; 7142 } 7143 7144 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 7145 return false; 7146 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 7147 return false; 7148 7149 return true; 7150 } 7151 7152 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 7153 /// literal. 7154 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 7155 Expr *LHSExpr, Expr *RHSExpr) { 7156 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 7157 Expr* IndexExpr = RHSExpr; 7158 if (!StrExpr) { 7159 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 7160 IndexExpr = LHSExpr; 7161 } 7162 7163 bool IsStringPlusInt = StrExpr && 7164 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 7165 if (!IsStringPlusInt) 7166 return; 7167 7168 llvm::APSInt index; 7169 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 7170 unsigned StrLenWithNull = StrExpr->getLength() + 1; 7171 if (index.isNonNegative() && 7172 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 7173 index.isUnsigned())) 7174 return; 7175 } 7176 7177 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7178 Self.Diag(OpLoc, diag::warn_string_plus_int) 7179 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 7180 7181 // Only print a fixit for "str" + int, not for int + "str". 7182 if (IndexExpr == RHSExpr) { 7183 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 7184 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7185 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7186 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7187 << FixItHint::CreateInsertion(EndLoc, "]"); 7188 } else 7189 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7190 } 7191 7192 /// \brief Emit a warning when adding a char literal to a string. 7193 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 7194 Expr *LHSExpr, Expr *RHSExpr) { 7195 const DeclRefExpr *StringRefExpr = 7196 dyn_cast<DeclRefExpr>(LHSExpr->IgnoreImpCasts()); 7197 const CharacterLiteral *CharExpr = 7198 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 7199 if (!StringRefExpr) { 7200 StringRefExpr = dyn_cast<DeclRefExpr>(RHSExpr->IgnoreImpCasts()); 7201 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 7202 } 7203 7204 if (!CharExpr || !StringRefExpr) 7205 return; 7206 7207 const QualType StringType = StringRefExpr->getType(); 7208 7209 // Return if not a PointerType. 7210 if (!StringType->isAnyPointerType()) 7211 return; 7212 7213 // Return if not a CharacterType. 7214 if (!StringType->getPointeeType()->isAnyCharacterType()) 7215 return; 7216 7217 ASTContext &Ctx = Self.getASTContext(); 7218 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7219 7220 const QualType CharType = CharExpr->getType(); 7221 if (!CharType->isAnyCharacterType() && 7222 CharType->isIntegerType() && 7223 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 7224 Self.Diag(OpLoc, diag::warn_string_plus_char) 7225 << DiagRange << Ctx.CharTy; 7226 } else { 7227 Self.Diag(OpLoc, diag::warn_string_plus_char) 7228 << DiagRange << CharExpr->getType(); 7229 } 7230 7231 // Only print a fixit for str + char, not for char + str. 7232 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 7233 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 7234 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7235 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7236 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7237 << FixItHint::CreateInsertion(EndLoc, "]"); 7238 } else { 7239 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7240 } 7241 } 7242 7243 /// \brief Emit error when two pointers are incompatible. 7244 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 7245 Expr *LHSExpr, Expr *RHSExpr) { 7246 assert(LHSExpr->getType()->isAnyPointerType()); 7247 assert(RHSExpr->getType()->isAnyPointerType()); 7248 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 7249 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 7250 << RHSExpr->getSourceRange(); 7251 } 7252 7253 QualType Sema::CheckAdditionOperands( // C99 6.5.6 7254 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 7255 QualType* CompLHSTy) { 7256 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7257 7258 if (LHS.get()->getType()->isVectorType() || 7259 RHS.get()->getType()->isVectorType()) { 7260 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 7261 if (CompLHSTy) *CompLHSTy = compType; 7262 return compType; 7263 } 7264 7265 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7266 if (LHS.isInvalid() || RHS.isInvalid()) 7267 return QualType(); 7268 7269 // Diagnose "string literal" '+' int and string '+' "char literal". 7270 if (Opc == BO_Add) { 7271 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 7272 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 7273 } 7274 7275 // handle the common case first (both operands are arithmetic). 7276 if (!compType.isNull() && compType->isArithmeticType()) { 7277 if (CompLHSTy) *CompLHSTy = compType; 7278 return compType; 7279 } 7280 7281 // Type-checking. Ultimately the pointer's going to be in PExp; 7282 // note that we bias towards the LHS being the pointer. 7283 Expr *PExp = LHS.get(), *IExp = RHS.get(); 7284 7285 bool isObjCPointer; 7286 if (PExp->getType()->isPointerType()) { 7287 isObjCPointer = false; 7288 } else if (PExp->getType()->isObjCObjectPointerType()) { 7289 isObjCPointer = true; 7290 } else { 7291 std::swap(PExp, IExp); 7292 if (PExp->getType()->isPointerType()) { 7293 isObjCPointer = false; 7294 } else if (PExp->getType()->isObjCObjectPointerType()) { 7295 isObjCPointer = true; 7296 } else { 7297 return InvalidOperands(Loc, LHS, RHS); 7298 } 7299 } 7300 assert(PExp->getType()->isAnyPointerType()); 7301 7302 if (!IExp->getType()->isIntegerType()) 7303 return InvalidOperands(Loc, LHS, RHS); 7304 7305 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 7306 return QualType(); 7307 7308 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 7309 return QualType(); 7310 7311 // Check array bounds for pointer arithemtic 7312 CheckArrayAccess(PExp, IExp); 7313 7314 if (CompLHSTy) { 7315 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 7316 if (LHSTy.isNull()) { 7317 LHSTy = LHS.get()->getType(); 7318 if (LHSTy->isPromotableIntegerType()) 7319 LHSTy = Context.getPromotedIntegerType(LHSTy); 7320 } 7321 *CompLHSTy = LHSTy; 7322 } 7323 7324 return PExp->getType(); 7325 } 7326 7327 // C99 6.5.6 7328 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 7329 SourceLocation Loc, 7330 QualType* CompLHSTy) { 7331 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7332 7333 if (LHS.get()->getType()->isVectorType() || 7334 RHS.get()->getType()->isVectorType()) { 7335 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 7336 if (CompLHSTy) *CompLHSTy = compType; 7337 return compType; 7338 } 7339 7340 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7341 if (LHS.isInvalid() || RHS.isInvalid()) 7342 return QualType(); 7343 7344 // Enforce type constraints: C99 6.5.6p3. 7345 7346 // Handle the common case first (both operands are arithmetic). 7347 if (!compType.isNull() && compType->isArithmeticType()) { 7348 if (CompLHSTy) *CompLHSTy = compType; 7349 return compType; 7350 } 7351 7352 // Either ptr - int or ptr - ptr. 7353 if (LHS.get()->getType()->isAnyPointerType()) { 7354 QualType lpointee = LHS.get()->getType()->getPointeeType(); 7355 7356 // Diagnose bad cases where we step over interface counts. 7357 if (LHS.get()->getType()->isObjCObjectPointerType() && 7358 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 7359 return QualType(); 7360 7361 // The result type of a pointer-int computation is the pointer type. 7362 if (RHS.get()->getType()->isIntegerType()) { 7363 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 7364 return QualType(); 7365 7366 // Check array bounds for pointer arithemtic 7367 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 7368 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 7369 7370 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 7371 return LHS.get()->getType(); 7372 } 7373 7374 // Handle pointer-pointer subtractions. 7375 if (const PointerType *RHSPTy 7376 = RHS.get()->getType()->getAs<PointerType>()) { 7377 QualType rpointee = RHSPTy->getPointeeType(); 7378 7379 if (getLangOpts().CPlusPlus) { 7380 // Pointee types must be the same: C++ [expr.add] 7381 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 7382 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 7383 } 7384 } else { 7385 // Pointee types must be compatible C99 6.5.6p3 7386 if (!Context.typesAreCompatible( 7387 Context.getCanonicalType(lpointee).getUnqualifiedType(), 7388 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 7389 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 7390 return QualType(); 7391 } 7392 } 7393 7394 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 7395 LHS.get(), RHS.get())) 7396 return QualType(); 7397 7398 // The pointee type may have zero size. As an extension, a structure or 7399 // union may have zero size or an array may have zero length. In this 7400 // case subtraction does not make sense. 7401 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 7402 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 7403 if (ElementSize.isZero()) { 7404 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 7405 << rpointee.getUnqualifiedType() 7406 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7407 } 7408 } 7409 7410 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 7411 return Context.getPointerDiffType(); 7412 } 7413 } 7414 7415 return InvalidOperands(Loc, LHS, RHS); 7416 } 7417 7418 static bool isScopedEnumerationType(QualType T) { 7419 if (const EnumType *ET = dyn_cast<EnumType>(T)) 7420 return ET->getDecl()->isScoped(); 7421 return false; 7422 } 7423 7424 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 7425 SourceLocation Loc, unsigned Opc, 7426 QualType LHSType) { 7427 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 7428 // so skip remaining warnings as we don't want to modify values within Sema. 7429 if (S.getLangOpts().OpenCL) 7430 return; 7431 7432 llvm::APSInt Right; 7433 // Check right/shifter operand 7434 if (RHS.get()->isValueDependent() || 7435 !RHS.get()->isIntegerConstantExpr(Right, S.Context)) 7436 return; 7437 7438 if (Right.isNegative()) { 7439 S.DiagRuntimeBehavior(Loc, RHS.get(), 7440 S.PDiag(diag::warn_shift_negative) 7441 << RHS.get()->getSourceRange()); 7442 return; 7443 } 7444 llvm::APInt LeftBits(Right.getBitWidth(), 7445 S.Context.getTypeSize(LHS.get()->getType())); 7446 if (Right.uge(LeftBits)) { 7447 S.DiagRuntimeBehavior(Loc, RHS.get(), 7448 S.PDiag(diag::warn_shift_gt_typewidth) 7449 << RHS.get()->getSourceRange()); 7450 return; 7451 } 7452 if (Opc != BO_Shl) 7453 return; 7454 7455 // When left shifting an ICE which is signed, we can check for overflow which 7456 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 7457 // integers have defined behavior modulo one more than the maximum value 7458 // representable in the result type, so never warn for those. 7459 llvm::APSInt Left; 7460 if (LHS.get()->isValueDependent() || 7461 !LHS.get()->isIntegerConstantExpr(Left, S.Context) || 7462 LHSType->hasUnsignedIntegerRepresentation()) 7463 return; 7464 llvm::APInt ResultBits = 7465 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 7466 if (LeftBits.uge(ResultBits)) 7467 return; 7468 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 7469 Result = Result.shl(Right); 7470 7471 // Print the bit representation of the signed integer as an unsigned 7472 // hexadecimal number. 7473 SmallString<40> HexResult; 7474 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 7475 7476 // If we are only missing a sign bit, this is less likely to result in actual 7477 // bugs -- if the result is cast back to an unsigned type, it will have the 7478 // expected value. Thus we place this behind a different warning that can be 7479 // turned off separately if needed. 7480 if (LeftBits == ResultBits - 1) { 7481 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 7482 << HexResult.str() << LHSType 7483 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7484 return; 7485 } 7486 7487 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 7488 << HexResult.str() << Result.getMinSignedBits() << LHSType 7489 << Left.getBitWidth() << LHS.get()->getSourceRange() 7490 << RHS.get()->getSourceRange(); 7491 } 7492 7493 // C99 6.5.7 7494 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 7495 SourceLocation Loc, unsigned Opc, 7496 bool IsCompAssign) { 7497 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7498 7499 // Vector shifts promote their scalar inputs to vector type. 7500 if (LHS.get()->getType()->isVectorType() || 7501 RHS.get()->getType()->isVectorType()) 7502 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 7503 7504 // Shifts don't perform usual arithmetic conversions, they just do integer 7505 // promotions on each operand. C99 6.5.7p3 7506 7507 // For the LHS, do usual unary conversions, but then reset them away 7508 // if this is a compound assignment. 7509 ExprResult OldLHS = LHS; 7510 LHS = UsualUnaryConversions(LHS.get()); 7511 if (LHS.isInvalid()) 7512 return QualType(); 7513 QualType LHSType = LHS.get()->getType(); 7514 if (IsCompAssign) LHS = OldLHS; 7515 7516 // The RHS is simpler. 7517 RHS = UsualUnaryConversions(RHS.get()); 7518 if (RHS.isInvalid()) 7519 return QualType(); 7520 QualType RHSType = RHS.get()->getType(); 7521 7522 // C99 6.5.7p2: Each of the operands shall have integer type. 7523 if (!LHSType->hasIntegerRepresentation() || 7524 !RHSType->hasIntegerRepresentation()) 7525 return InvalidOperands(Loc, LHS, RHS); 7526 7527 // C++0x: Don't allow scoped enums. FIXME: Use something better than 7528 // hasIntegerRepresentation() above instead of this. 7529 if (isScopedEnumerationType(LHSType) || 7530 isScopedEnumerationType(RHSType)) { 7531 return InvalidOperands(Loc, LHS, RHS); 7532 } 7533 // Sanity-check shift operands 7534 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 7535 7536 // "The type of the result is that of the promoted left operand." 7537 return LHSType; 7538 } 7539 7540 static bool IsWithinTemplateSpecialization(Decl *D) { 7541 if (DeclContext *DC = D->getDeclContext()) { 7542 if (isa<ClassTemplateSpecializationDecl>(DC)) 7543 return true; 7544 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 7545 return FD->isFunctionTemplateSpecialization(); 7546 } 7547 return false; 7548 } 7549 7550 /// If two different enums are compared, raise a warning. 7551 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 7552 Expr *RHS) { 7553 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 7554 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 7555 7556 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 7557 if (!LHSEnumType) 7558 return; 7559 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 7560 if (!RHSEnumType) 7561 return; 7562 7563 // Ignore anonymous enums. 7564 if (!LHSEnumType->getDecl()->getIdentifier()) 7565 return; 7566 if (!RHSEnumType->getDecl()->getIdentifier()) 7567 return; 7568 7569 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 7570 return; 7571 7572 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 7573 << LHSStrippedType << RHSStrippedType 7574 << LHS->getSourceRange() << RHS->getSourceRange(); 7575 } 7576 7577 /// \brief Diagnose bad pointer comparisons. 7578 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 7579 ExprResult &LHS, ExprResult &RHS, 7580 bool IsError) { 7581 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 7582 : diag::ext_typecheck_comparison_of_distinct_pointers) 7583 << LHS.get()->getType() << RHS.get()->getType() 7584 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7585 } 7586 7587 /// \brief Returns false if the pointers are converted to a composite type, 7588 /// true otherwise. 7589 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 7590 ExprResult &LHS, ExprResult &RHS) { 7591 // C++ [expr.rel]p2: 7592 // [...] Pointer conversions (4.10) and qualification 7593 // conversions (4.4) are performed on pointer operands (or on 7594 // a pointer operand and a null pointer constant) to bring 7595 // them to their composite pointer type. [...] 7596 // 7597 // C++ [expr.eq]p1 uses the same notion for (in)equality 7598 // comparisons of pointers. 7599 7600 // C++ [expr.eq]p2: 7601 // In addition, pointers to members can be compared, or a pointer to 7602 // member and a null pointer constant. Pointer to member conversions 7603 // (4.11) and qualification conversions (4.4) are performed to bring 7604 // them to a common type. If one operand is a null pointer constant, 7605 // the common type is the type of the other operand. Otherwise, the 7606 // common type is a pointer to member type similar (4.4) to the type 7607 // of one of the operands, with a cv-qualification signature (4.4) 7608 // that is the union of the cv-qualification signatures of the operand 7609 // types. 7610 7611 QualType LHSType = LHS.get()->getType(); 7612 QualType RHSType = RHS.get()->getType(); 7613 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 7614 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 7615 7616 bool NonStandardCompositeType = false; 7617 bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType; 7618 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 7619 if (T.isNull()) { 7620 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 7621 return true; 7622 } 7623 7624 if (NonStandardCompositeType) 7625 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 7626 << LHSType << RHSType << T << LHS.get()->getSourceRange() 7627 << RHS.get()->getSourceRange(); 7628 7629 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 7630 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 7631 return false; 7632 } 7633 7634 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 7635 ExprResult &LHS, 7636 ExprResult &RHS, 7637 bool IsError) { 7638 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 7639 : diag::ext_typecheck_comparison_of_fptr_to_void) 7640 << LHS.get()->getType() << RHS.get()->getType() 7641 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7642 } 7643 7644 static bool isObjCObjectLiteral(ExprResult &E) { 7645 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 7646 case Stmt::ObjCArrayLiteralClass: 7647 case Stmt::ObjCDictionaryLiteralClass: 7648 case Stmt::ObjCStringLiteralClass: 7649 case Stmt::ObjCBoxedExprClass: 7650 return true; 7651 default: 7652 // Note that ObjCBoolLiteral is NOT an object literal! 7653 return false; 7654 } 7655 } 7656 7657 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 7658 const ObjCObjectPointerType *Type = 7659 LHS->getType()->getAs<ObjCObjectPointerType>(); 7660 7661 // If this is not actually an Objective-C object, bail out. 7662 if (!Type) 7663 return false; 7664 7665 // Get the LHS object's interface type. 7666 QualType InterfaceType = Type->getPointeeType(); 7667 if (const ObjCObjectType *iQFaceTy = 7668 InterfaceType->getAsObjCQualifiedInterfaceType()) 7669 InterfaceType = iQFaceTy->getBaseType(); 7670 7671 // If the RHS isn't an Objective-C object, bail out. 7672 if (!RHS->getType()->isObjCObjectPointerType()) 7673 return false; 7674 7675 // Try to find the -isEqual: method. 7676 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 7677 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 7678 InterfaceType, 7679 /*instance=*/true); 7680 if (!Method) { 7681 if (Type->isObjCIdType()) { 7682 // For 'id', just check the global pool. 7683 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 7684 /*receiverId=*/true, 7685 /*warn=*/false); 7686 } else { 7687 // Check protocols. 7688 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 7689 /*instance=*/true); 7690 } 7691 } 7692 7693 if (!Method) 7694 return false; 7695 7696 QualType T = Method->param_begin()[0]->getType(); 7697 if (!T->isObjCObjectPointerType()) 7698 return false; 7699 7700 QualType R = Method->getReturnType(); 7701 if (!R->isScalarType()) 7702 return false; 7703 7704 return true; 7705 } 7706 7707 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 7708 FromE = FromE->IgnoreParenImpCasts(); 7709 switch (FromE->getStmtClass()) { 7710 default: 7711 break; 7712 case Stmt::ObjCStringLiteralClass: 7713 // "string literal" 7714 return LK_String; 7715 case Stmt::ObjCArrayLiteralClass: 7716 // "array literal" 7717 return LK_Array; 7718 case Stmt::ObjCDictionaryLiteralClass: 7719 // "dictionary literal" 7720 return LK_Dictionary; 7721 case Stmt::BlockExprClass: 7722 return LK_Block; 7723 case Stmt::ObjCBoxedExprClass: { 7724 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 7725 switch (Inner->getStmtClass()) { 7726 case Stmt::IntegerLiteralClass: 7727 case Stmt::FloatingLiteralClass: 7728 case Stmt::CharacterLiteralClass: 7729 case Stmt::ObjCBoolLiteralExprClass: 7730 case Stmt::CXXBoolLiteralExprClass: 7731 // "numeric literal" 7732 return LK_Numeric; 7733 case Stmt::ImplicitCastExprClass: { 7734 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 7735 // Boolean literals can be represented by implicit casts. 7736 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 7737 return LK_Numeric; 7738 break; 7739 } 7740 default: 7741 break; 7742 } 7743 return LK_Boxed; 7744 } 7745 } 7746 return LK_None; 7747 } 7748 7749 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 7750 ExprResult &LHS, ExprResult &RHS, 7751 BinaryOperator::Opcode Opc){ 7752 Expr *Literal; 7753 Expr *Other; 7754 if (isObjCObjectLiteral(LHS)) { 7755 Literal = LHS.get(); 7756 Other = RHS.get(); 7757 } else { 7758 Literal = RHS.get(); 7759 Other = LHS.get(); 7760 } 7761 7762 // Don't warn on comparisons against nil. 7763 Other = Other->IgnoreParenCasts(); 7764 if (Other->isNullPointerConstant(S.getASTContext(), 7765 Expr::NPC_ValueDependentIsNotNull)) 7766 return; 7767 7768 // This should be kept in sync with warn_objc_literal_comparison. 7769 // LK_String should always be after the other literals, since it has its own 7770 // warning flag. 7771 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 7772 assert(LiteralKind != Sema::LK_Block); 7773 if (LiteralKind == Sema::LK_None) { 7774 llvm_unreachable("Unknown Objective-C object literal kind"); 7775 } 7776 7777 if (LiteralKind == Sema::LK_String) 7778 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 7779 << Literal->getSourceRange(); 7780 else 7781 S.Diag(Loc, diag::warn_objc_literal_comparison) 7782 << LiteralKind << Literal->getSourceRange(); 7783 7784 if (BinaryOperator::isEqualityOp(Opc) && 7785 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 7786 SourceLocation Start = LHS.get()->getLocStart(); 7787 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 7788 CharSourceRange OpRange = 7789 CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc)); 7790 7791 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 7792 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 7793 << FixItHint::CreateReplacement(OpRange, " isEqual:") 7794 << FixItHint::CreateInsertion(End, "]"); 7795 } 7796 } 7797 7798 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 7799 ExprResult &RHS, 7800 SourceLocation Loc, 7801 unsigned OpaqueOpc) { 7802 // This checking requires bools. 7803 if (!S.getLangOpts().Bool) return; 7804 7805 // Check that left hand side is !something. 7806 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 7807 if (!UO || UO->getOpcode() != UO_LNot) return; 7808 7809 // Only check if the right hand side is non-bool arithmetic type. 7810 if (RHS.get()->getType()->isBooleanType()) return; 7811 7812 // Make sure that the something in !something is not bool. 7813 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 7814 if (SubExpr->getType()->isBooleanType()) return; 7815 7816 // Emit warning. 7817 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 7818 << Loc; 7819 7820 // First note suggest !(x < y) 7821 SourceLocation FirstOpen = SubExpr->getLocStart(); 7822 SourceLocation FirstClose = RHS.get()->getLocEnd(); 7823 FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose); 7824 if (FirstClose.isInvalid()) 7825 FirstOpen = SourceLocation(); 7826 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 7827 << FixItHint::CreateInsertion(FirstOpen, "(") 7828 << FixItHint::CreateInsertion(FirstClose, ")"); 7829 7830 // Second note suggests (!x) < y 7831 SourceLocation SecondOpen = LHS.get()->getLocStart(); 7832 SourceLocation SecondClose = LHS.get()->getLocEnd(); 7833 SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose); 7834 if (SecondClose.isInvalid()) 7835 SecondOpen = SourceLocation(); 7836 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 7837 << FixItHint::CreateInsertion(SecondOpen, "(") 7838 << FixItHint::CreateInsertion(SecondClose, ")"); 7839 } 7840 7841 // Get the decl for a simple expression: a reference to a variable, 7842 // an implicit C++ field reference, or an implicit ObjC ivar reference. 7843 static ValueDecl *getCompareDecl(Expr *E) { 7844 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 7845 return DR->getDecl(); 7846 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 7847 if (Ivar->isFreeIvar()) 7848 return Ivar->getDecl(); 7849 } 7850 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 7851 if (Mem->isImplicitAccess()) 7852 return Mem->getMemberDecl(); 7853 } 7854 return nullptr; 7855 } 7856 7857 // C99 6.5.8, C++ [expr.rel] 7858 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 7859 SourceLocation Loc, unsigned OpaqueOpc, 7860 bool IsRelational) { 7861 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 7862 7863 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 7864 7865 // Handle vector comparisons separately. 7866 if (LHS.get()->getType()->isVectorType() || 7867 RHS.get()->getType()->isVectorType()) 7868 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 7869 7870 QualType LHSType = LHS.get()->getType(); 7871 QualType RHSType = RHS.get()->getType(); 7872 7873 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 7874 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 7875 7876 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 7877 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc); 7878 7879 if (!LHSType->hasFloatingRepresentation() && 7880 !(LHSType->isBlockPointerType() && IsRelational) && 7881 !LHS.get()->getLocStart().isMacroID() && 7882 !RHS.get()->getLocStart().isMacroID() && 7883 ActiveTemplateInstantiations.empty()) { 7884 // For non-floating point types, check for self-comparisons of the form 7885 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 7886 // often indicate logic errors in the program. 7887 // 7888 // NOTE: Don't warn about comparison expressions resulting from macro 7889 // expansion. Also don't warn about comparisons which are only self 7890 // comparisons within a template specialization. The warnings should catch 7891 // obvious cases in the definition of the template anyways. The idea is to 7892 // warn when the typed comparison operator will always evaluate to the same 7893 // result. 7894 ValueDecl *DL = getCompareDecl(LHSStripped); 7895 ValueDecl *DR = getCompareDecl(RHSStripped); 7896 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 7897 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 7898 << 0 // self- 7899 << (Opc == BO_EQ 7900 || Opc == BO_LE 7901 || Opc == BO_GE)); 7902 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 7903 !DL->getType()->isReferenceType() && 7904 !DR->getType()->isReferenceType()) { 7905 // what is it always going to eval to? 7906 char always_evals_to; 7907 switch(Opc) { 7908 case BO_EQ: // e.g. array1 == array2 7909 always_evals_to = 0; // false 7910 break; 7911 case BO_NE: // e.g. array1 != array2 7912 always_evals_to = 1; // true 7913 break; 7914 default: 7915 // best we can say is 'a constant' 7916 always_evals_to = 2; // e.g. array1 <= array2 7917 break; 7918 } 7919 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 7920 << 1 // array 7921 << always_evals_to); 7922 } 7923 7924 if (isa<CastExpr>(LHSStripped)) 7925 LHSStripped = LHSStripped->IgnoreParenCasts(); 7926 if (isa<CastExpr>(RHSStripped)) 7927 RHSStripped = RHSStripped->IgnoreParenCasts(); 7928 7929 // Warn about comparisons against a string constant (unless the other 7930 // operand is null), the user probably wants strcmp. 7931 Expr *literalString = nullptr; 7932 Expr *literalStringStripped = nullptr; 7933 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 7934 !RHSStripped->isNullPointerConstant(Context, 7935 Expr::NPC_ValueDependentIsNull)) { 7936 literalString = LHS.get(); 7937 literalStringStripped = LHSStripped; 7938 } else if ((isa<StringLiteral>(RHSStripped) || 7939 isa<ObjCEncodeExpr>(RHSStripped)) && 7940 !LHSStripped->isNullPointerConstant(Context, 7941 Expr::NPC_ValueDependentIsNull)) { 7942 literalString = RHS.get(); 7943 literalStringStripped = RHSStripped; 7944 } 7945 7946 if (literalString) { 7947 DiagRuntimeBehavior(Loc, nullptr, 7948 PDiag(diag::warn_stringcompare) 7949 << isa<ObjCEncodeExpr>(literalStringStripped) 7950 << literalString->getSourceRange()); 7951 } 7952 } 7953 7954 // C99 6.5.8p3 / C99 6.5.9p4 7955 UsualArithmeticConversions(LHS, RHS); 7956 if (LHS.isInvalid() || RHS.isInvalid()) 7957 return QualType(); 7958 7959 LHSType = LHS.get()->getType(); 7960 RHSType = RHS.get()->getType(); 7961 7962 // The result of comparisons is 'bool' in C++, 'int' in C. 7963 QualType ResultTy = Context.getLogicalOperationType(); 7964 7965 if (IsRelational) { 7966 if (LHSType->isRealType() && RHSType->isRealType()) 7967 return ResultTy; 7968 } else { 7969 // Check for comparisons of floating point operands using != and ==. 7970 if (LHSType->hasFloatingRepresentation()) 7971 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 7972 7973 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 7974 return ResultTy; 7975 } 7976 7977 const Expr::NullPointerConstantKind LHSNullKind = 7978 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 7979 const Expr::NullPointerConstantKind RHSNullKind = 7980 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 7981 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 7982 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 7983 7984 if (!IsRelational && LHSIsNull != RHSIsNull) { 7985 bool IsEquality = Opc == BO_EQ; 7986 if (RHSIsNull) 7987 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 7988 RHS.get()->getSourceRange()); 7989 else 7990 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 7991 LHS.get()->getSourceRange()); 7992 } 7993 7994 // All of the following pointer-related warnings are GCC extensions, except 7995 // when handling null pointer constants. 7996 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 7997 QualType LCanPointeeTy = 7998 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7999 QualType RCanPointeeTy = 8000 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 8001 8002 if (getLangOpts().CPlusPlus) { 8003 if (LCanPointeeTy == RCanPointeeTy) 8004 return ResultTy; 8005 if (!IsRelational && 8006 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 8007 // Valid unless comparison between non-null pointer and function pointer 8008 // This is a gcc extension compatibility comparison. 8009 // In a SFINAE context, we treat this as a hard error to maintain 8010 // conformance with the C++ standard. 8011 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 8012 && !LHSIsNull && !RHSIsNull) { 8013 diagnoseFunctionPointerToVoidComparison( 8014 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 8015 8016 if (isSFINAEContext()) 8017 return QualType(); 8018 8019 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8020 return ResultTy; 8021 } 8022 } 8023 8024 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 8025 return QualType(); 8026 else 8027 return ResultTy; 8028 } 8029 // C99 6.5.9p2 and C99 6.5.8p2 8030 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 8031 RCanPointeeTy.getUnqualifiedType())) { 8032 // Valid unless a relational comparison of function pointers 8033 if (IsRelational && LCanPointeeTy->isFunctionType()) { 8034 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 8035 << LHSType << RHSType << LHS.get()->getSourceRange() 8036 << RHS.get()->getSourceRange(); 8037 } 8038 } else if (!IsRelational && 8039 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 8040 // Valid unless comparison between non-null pointer and function pointer 8041 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 8042 && !LHSIsNull && !RHSIsNull) 8043 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 8044 /*isError*/false); 8045 } else { 8046 // Invalid 8047 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 8048 } 8049 if (LCanPointeeTy != RCanPointeeTy) { 8050 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 8051 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 8052 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 8053 : CK_BitCast; 8054 if (LHSIsNull && !RHSIsNull) 8055 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 8056 else 8057 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 8058 } 8059 return ResultTy; 8060 } 8061 8062 if (getLangOpts().CPlusPlus) { 8063 // Comparison of nullptr_t with itself. 8064 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 8065 return ResultTy; 8066 8067 // Comparison of pointers with null pointer constants and equality 8068 // comparisons of member pointers to null pointer constants. 8069 if (RHSIsNull && 8070 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 8071 (!IsRelational && 8072 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 8073 RHS = ImpCastExprToType(RHS.get(), LHSType, 8074 LHSType->isMemberPointerType() 8075 ? CK_NullToMemberPointer 8076 : CK_NullToPointer); 8077 return ResultTy; 8078 } 8079 if (LHSIsNull && 8080 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 8081 (!IsRelational && 8082 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 8083 LHS = ImpCastExprToType(LHS.get(), RHSType, 8084 RHSType->isMemberPointerType() 8085 ? CK_NullToMemberPointer 8086 : CK_NullToPointer); 8087 return ResultTy; 8088 } 8089 8090 // Comparison of member pointers. 8091 if (!IsRelational && 8092 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 8093 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 8094 return QualType(); 8095 else 8096 return ResultTy; 8097 } 8098 8099 // Handle scoped enumeration types specifically, since they don't promote 8100 // to integers. 8101 if (LHS.get()->getType()->isEnumeralType() && 8102 Context.hasSameUnqualifiedType(LHS.get()->getType(), 8103 RHS.get()->getType())) 8104 return ResultTy; 8105 } 8106 8107 // Handle block pointer types. 8108 if (!IsRelational && LHSType->isBlockPointerType() && 8109 RHSType->isBlockPointerType()) { 8110 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 8111 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 8112 8113 if (!LHSIsNull && !RHSIsNull && 8114 !Context.typesAreCompatible(lpointee, rpointee)) { 8115 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 8116 << LHSType << RHSType << LHS.get()->getSourceRange() 8117 << RHS.get()->getSourceRange(); 8118 } 8119 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8120 return ResultTy; 8121 } 8122 8123 // Allow block pointers to be compared with null pointer constants. 8124 if (!IsRelational 8125 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 8126 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 8127 if (!LHSIsNull && !RHSIsNull) { 8128 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 8129 ->getPointeeType()->isVoidType()) 8130 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 8131 ->getPointeeType()->isVoidType()))) 8132 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 8133 << LHSType << RHSType << LHS.get()->getSourceRange() 8134 << RHS.get()->getSourceRange(); 8135 } 8136 if (LHSIsNull && !RHSIsNull) 8137 LHS = ImpCastExprToType(LHS.get(), RHSType, 8138 RHSType->isPointerType() ? CK_BitCast 8139 : CK_AnyPointerToBlockPointerCast); 8140 else 8141 RHS = ImpCastExprToType(RHS.get(), LHSType, 8142 LHSType->isPointerType() ? CK_BitCast 8143 : CK_AnyPointerToBlockPointerCast); 8144 return ResultTy; 8145 } 8146 8147 if (LHSType->isObjCObjectPointerType() || 8148 RHSType->isObjCObjectPointerType()) { 8149 const PointerType *LPT = LHSType->getAs<PointerType>(); 8150 const PointerType *RPT = RHSType->getAs<PointerType>(); 8151 if (LPT || RPT) { 8152 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 8153 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 8154 8155 if (!LPtrToVoid && !RPtrToVoid && 8156 !Context.typesAreCompatible(LHSType, RHSType)) { 8157 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8158 /*isError*/false); 8159 } 8160 if (LHSIsNull && !RHSIsNull) { 8161 Expr *E = LHS.get(); 8162 if (getLangOpts().ObjCAutoRefCount) 8163 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 8164 LHS = ImpCastExprToType(E, RHSType, 8165 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8166 } 8167 else { 8168 Expr *E = RHS.get(); 8169 if (getLangOpts().ObjCAutoRefCount) 8170 CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false, 8171 Opc); 8172 RHS = ImpCastExprToType(E, LHSType, 8173 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8174 } 8175 return ResultTy; 8176 } 8177 if (LHSType->isObjCObjectPointerType() && 8178 RHSType->isObjCObjectPointerType()) { 8179 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 8180 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8181 /*isError*/false); 8182 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 8183 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 8184 8185 if (LHSIsNull && !RHSIsNull) 8186 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8187 else 8188 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8189 return ResultTy; 8190 } 8191 } 8192 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 8193 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 8194 unsigned DiagID = 0; 8195 bool isError = false; 8196 if (LangOpts.DebuggerSupport) { 8197 // Under a debugger, allow the comparison of pointers to integers, 8198 // since users tend to want to compare addresses. 8199 } else if ((LHSIsNull && LHSType->isIntegerType()) || 8200 (RHSIsNull && RHSType->isIntegerType())) { 8201 if (IsRelational && !getLangOpts().CPlusPlus) 8202 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 8203 } else if (IsRelational && !getLangOpts().CPlusPlus) 8204 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 8205 else if (getLangOpts().CPlusPlus) { 8206 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 8207 isError = true; 8208 } else 8209 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 8210 8211 if (DiagID) { 8212 Diag(Loc, DiagID) 8213 << LHSType << RHSType << LHS.get()->getSourceRange() 8214 << RHS.get()->getSourceRange(); 8215 if (isError) 8216 return QualType(); 8217 } 8218 8219 if (LHSType->isIntegerType()) 8220 LHS = ImpCastExprToType(LHS.get(), RHSType, 8221 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8222 else 8223 RHS = ImpCastExprToType(RHS.get(), LHSType, 8224 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8225 return ResultTy; 8226 } 8227 8228 // Handle block pointers. 8229 if (!IsRelational && RHSIsNull 8230 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 8231 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8232 return ResultTy; 8233 } 8234 if (!IsRelational && LHSIsNull 8235 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 8236 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 8237 return ResultTy; 8238 } 8239 8240 return InvalidOperands(Loc, LHS, RHS); 8241 } 8242 8243 8244 // Return a signed type that is of identical size and number of elements. 8245 // For floating point vectors, return an integer type of identical size 8246 // and number of elements. 8247 QualType Sema::GetSignedVectorType(QualType V) { 8248 const VectorType *VTy = V->getAs<VectorType>(); 8249 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 8250 if (TypeSize == Context.getTypeSize(Context.CharTy)) 8251 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 8252 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 8253 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 8254 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 8255 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 8256 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 8257 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 8258 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 8259 "Unhandled vector element size in vector compare"); 8260 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 8261 } 8262 8263 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 8264 /// operates on extended vector types. Instead of producing an IntTy result, 8265 /// like a scalar comparison, a vector comparison produces a vector of integer 8266 /// types. 8267 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 8268 SourceLocation Loc, 8269 bool IsRelational) { 8270 // Check to make sure we're operating on vectors of the same type and width, 8271 // Allowing one side to be a scalar of element type. 8272 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false); 8273 if (vType.isNull()) 8274 return vType; 8275 8276 QualType LHSType = LHS.get()->getType(); 8277 8278 // If AltiVec, the comparison results in a numeric type, i.e. 8279 // bool for C++, int for C 8280 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 8281 return Context.getLogicalOperationType(); 8282 8283 // For non-floating point types, check for self-comparisons of the form 8284 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 8285 // often indicate logic errors in the program. 8286 if (!LHSType->hasFloatingRepresentation() && 8287 ActiveTemplateInstantiations.empty()) { 8288 if (DeclRefExpr* DRL 8289 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 8290 if (DeclRefExpr* DRR 8291 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 8292 if (DRL->getDecl() == DRR->getDecl()) 8293 DiagRuntimeBehavior(Loc, nullptr, 8294 PDiag(diag::warn_comparison_always) 8295 << 0 // self- 8296 << 2 // "a constant" 8297 ); 8298 } 8299 8300 // Check for comparisons of floating point operands using != and ==. 8301 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 8302 assert (RHS.get()->getType()->hasFloatingRepresentation()); 8303 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 8304 } 8305 8306 // Return a signed type for the vector. 8307 return GetSignedVectorType(LHSType); 8308 } 8309 8310 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 8311 SourceLocation Loc) { 8312 // Ensure that either both operands are of the same vector type, or 8313 // one operand is of a vector type and the other is of its element type. 8314 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false); 8315 if (vType.isNull()) 8316 return InvalidOperands(Loc, LHS, RHS); 8317 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 8318 vType->hasFloatingRepresentation()) 8319 return InvalidOperands(Loc, LHS, RHS); 8320 8321 return GetSignedVectorType(LHS.get()->getType()); 8322 } 8323 8324 inline QualType Sema::CheckBitwiseOperands( 8325 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8326 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8327 8328 if (LHS.get()->getType()->isVectorType() || 8329 RHS.get()->getType()->isVectorType()) { 8330 if (LHS.get()->getType()->hasIntegerRepresentation() && 8331 RHS.get()->getType()->hasIntegerRepresentation()) 8332 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 8333 8334 return InvalidOperands(Loc, LHS, RHS); 8335 } 8336 8337 ExprResult LHSResult = LHS, RHSResult = RHS; 8338 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 8339 IsCompAssign); 8340 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 8341 return QualType(); 8342 LHS = LHSResult.get(); 8343 RHS = RHSResult.get(); 8344 8345 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 8346 return compType; 8347 return InvalidOperands(Loc, LHS, RHS); 8348 } 8349 8350 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 8351 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) { 8352 8353 // Check vector operands differently. 8354 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 8355 return CheckVectorLogicalOperands(LHS, RHS, Loc); 8356 8357 // Diagnose cases where the user write a logical and/or but probably meant a 8358 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 8359 // is a constant. 8360 if (LHS.get()->getType()->isIntegerType() && 8361 !LHS.get()->getType()->isBooleanType() && 8362 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 8363 // Don't warn in macros or template instantiations. 8364 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 8365 // If the RHS can be constant folded, and if it constant folds to something 8366 // that isn't 0 or 1 (which indicate a potential logical operation that 8367 // happened to fold to true/false) then warn. 8368 // Parens on the RHS are ignored. 8369 llvm::APSInt Result; 8370 if (RHS.get()->EvaluateAsInt(Result, Context)) 8371 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 8372 !RHS.get()->getExprLoc().isMacroID()) || 8373 (Result != 0 && Result != 1)) { 8374 Diag(Loc, diag::warn_logical_instead_of_bitwise) 8375 << RHS.get()->getSourceRange() 8376 << (Opc == BO_LAnd ? "&&" : "||"); 8377 // Suggest replacing the logical operator with the bitwise version 8378 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 8379 << (Opc == BO_LAnd ? "&" : "|") 8380 << FixItHint::CreateReplacement(SourceRange( 8381 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(), 8382 getLangOpts())), 8383 Opc == BO_LAnd ? "&" : "|"); 8384 if (Opc == BO_LAnd) 8385 // Suggest replacing "Foo() && kNonZero" with "Foo()" 8386 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 8387 << FixItHint::CreateRemoval( 8388 SourceRange( 8389 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(), 8390 0, getSourceManager(), 8391 getLangOpts()), 8392 RHS.get()->getLocEnd())); 8393 } 8394 } 8395 8396 if (!Context.getLangOpts().CPlusPlus) { 8397 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 8398 // not operate on the built-in scalar and vector float types. 8399 if (Context.getLangOpts().OpenCL && 8400 Context.getLangOpts().OpenCLVersion < 120) { 8401 if (LHS.get()->getType()->isFloatingType() || 8402 RHS.get()->getType()->isFloatingType()) 8403 return InvalidOperands(Loc, LHS, RHS); 8404 } 8405 8406 LHS = UsualUnaryConversions(LHS.get()); 8407 if (LHS.isInvalid()) 8408 return QualType(); 8409 8410 RHS = UsualUnaryConversions(RHS.get()); 8411 if (RHS.isInvalid()) 8412 return QualType(); 8413 8414 if (!LHS.get()->getType()->isScalarType() || 8415 !RHS.get()->getType()->isScalarType()) 8416 return InvalidOperands(Loc, LHS, RHS); 8417 8418 return Context.IntTy; 8419 } 8420 8421 // The following is safe because we only use this method for 8422 // non-overloadable operands. 8423 8424 // C++ [expr.log.and]p1 8425 // C++ [expr.log.or]p1 8426 // The operands are both contextually converted to type bool. 8427 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 8428 if (LHSRes.isInvalid()) 8429 return InvalidOperands(Loc, LHS, RHS); 8430 LHS = LHSRes; 8431 8432 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 8433 if (RHSRes.isInvalid()) 8434 return InvalidOperands(Loc, LHS, RHS); 8435 RHS = RHSRes; 8436 8437 // C++ [expr.log.and]p2 8438 // C++ [expr.log.or]p2 8439 // The result is a bool. 8440 return Context.BoolTy; 8441 } 8442 8443 static bool IsReadonlyMessage(Expr *E, Sema &S) { 8444 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 8445 if (!ME) return false; 8446 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 8447 ObjCMessageExpr *Base = 8448 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 8449 if (!Base) return false; 8450 return Base->getMethodDecl() != nullptr; 8451 } 8452 8453 /// Is the given expression (which must be 'const') a reference to a 8454 /// variable which was originally non-const, but which has become 8455 /// 'const' due to being captured within a block? 8456 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 8457 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 8458 assert(E->isLValue() && E->getType().isConstQualified()); 8459 E = E->IgnoreParens(); 8460 8461 // Must be a reference to a declaration from an enclosing scope. 8462 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 8463 if (!DRE) return NCCK_None; 8464 if (!DRE->refersToEnclosingLocal()) return NCCK_None; 8465 8466 // The declaration must be a variable which is not declared 'const'. 8467 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 8468 if (!var) return NCCK_None; 8469 if (var->getType().isConstQualified()) return NCCK_None; 8470 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 8471 8472 // Decide whether the first capture was for a block or a lambda. 8473 DeclContext *DC = S.CurContext, *Prev = nullptr; 8474 while (DC != var->getDeclContext()) { 8475 Prev = DC; 8476 DC = DC->getParent(); 8477 } 8478 // Unless we have an init-capture, we've gone one step too far. 8479 if (!var->isInitCapture()) 8480 DC = Prev; 8481 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 8482 } 8483 8484 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 8485 /// emit an error and return true. If so, return false. 8486 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 8487 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 8488 SourceLocation OrigLoc = Loc; 8489 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 8490 &Loc); 8491 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 8492 IsLV = Expr::MLV_InvalidMessageExpression; 8493 if (IsLV == Expr::MLV_Valid) 8494 return false; 8495 8496 unsigned Diag = 0; 8497 bool NeedType = false; 8498 switch (IsLV) { // C99 6.5.16p2 8499 case Expr::MLV_ConstQualified: 8500 Diag = diag::err_typecheck_assign_const; 8501 8502 // Use a specialized diagnostic when we're assigning to an object 8503 // from an enclosing function or block. 8504 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 8505 if (NCCK == NCCK_Block) 8506 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 8507 else 8508 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue; 8509 break; 8510 } 8511 8512 // In ARC, use some specialized diagnostics for occasions where we 8513 // infer 'const'. These are always pseudo-strong variables. 8514 if (S.getLangOpts().ObjCAutoRefCount) { 8515 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 8516 if (declRef && isa<VarDecl>(declRef->getDecl())) { 8517 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 8518 8519 // Use the normal diagnostic if it's pseudo-__strong but the 8520 // user actually wrote 'const'. 8521 if (var->isARCPseudoStrong() && 8522 (!var->getTypeSourceInfo() || 8523 !var->getTypeSourceInfo()->getType().isConstQualified())) { 8524 // There are two pseudo-strong cases: 8525 // - self 8526 ObjCMethodDecl *method = S.getCurMethodDecl(); 8527 if (method && var == method->getSelfDecl()) 8528 Diag = method->isClassMethod() 8529 ? diag::err_typecheck_arc_assign_self_class_method 8530 : diag::err_typecheck_arc_assign_self; 8531 8532 // - fast enumeration variables 8533 else 8534 Diag = diag::err_typecheck_arr_assign_enumeration; 8535 8536 SourceRange Assign; 8537 if (Loc != OrigLoc) 8538 Assign = SourceRange(OrigLoc, OrigLoc); 8539 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 8540 // We need to preserve the AST regardless, so migration tool 8541 // can do its job. 8542 return false; 8543 } 8544 } 8545 } 8546 8547 break; 8548 case Expr::MLV_ArrayType: 8549 case Expr::MLV_ArrayTemporary: 8550 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 8551 NeedType = true; 8552 break; 8553 case Expr::MLV_NotObjectType: 8554 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 8555 NeedType = true; 8556 break; 8557 case Expr::MLV_LValueCast: 8558 Diag = diag::err_typecheck_lvalue_casts_not_supported; 8559 break; 8560 case Expr::MLV_Valid: 8561 llvm_unreachable("did not take early return for MLV_Valid"); 8562 case Expr::MLV_InvalidExpression: 8563 case Expr::MLV_MemberFunction: 8564 case Expr::MLV_ClassTemporary: 8565 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 8566 break; 8567 case Expr::MLV_IncompleteType: 8568 case Expr::MLV_IncompleteVoidType: 8569 return S.RequireCompleteType(Loc, E->getType(), 8570 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 8571 case Expr::MLV_DuplicateVectorComponents: 8572 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 8573 break; 8574 case Expr::MLV_NoSetterProperty: 8575 llvm_unreachable("readonly properties should be processed differently"); 8576 case Expr::MLV_InvalidMessageExpression: 8577 Diag = diag::error_readonly_message_assignment; 8578 break; 8579 case Expr::MLV_SubObjCPropertySetting: 8580 Diag = diag::error_no_subobject_property_setting; 8581 break; 8582 } 8583 8584 SourceRange Assign; 8585 if (Loc != OrigLoc) 8586 Assign = SourceRange(OrigLoc, OrigLoc); 8587 if (NeedType) 8588 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 8589 else 8590 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 8591 return true; 8592 } 8593 8594 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 8595 SourceLocation Loc, 8596 Sema &Sema) { 8597 // C / C++ fields 8598 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 8599 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 8600 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 8601 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 8602 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 8603 } 8604 8605 // Objective-C instance variables 8606 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 8607 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 8608 if (OL && OR && OL->getDecl() == OR->getDecl()) { 8609 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 8610 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 8611 if (RL && RR && RL->getDecl() == RR->getDecl()) 8612 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 8613 } 8614 } 8615 8616 // C99 6.5.16.1 8617 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 8618 SourceLocation Loc, 8619 QualType CompoundType) { 8620 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 8621 8622 // Verify that LHS is a modifiable lvalue, and emit error if not. 8623 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 8624 return QualType(); 8625 8626 QualType LHSType = LHSExpr->getType(); 8627 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 8628 CompoundType; 8629 AssignConvertType ConvTy; 8630 if (CompoundType.isNull()) { 8631 Expr *RHSCheck = RHS.get(); 8632 8633 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 8634 8635 QualType LHSTy(LHSType); 8636 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 8637 if (RHS.isInvalid()) 8638 return QualType(); 8639 // Special case of NSObject attributes on c-style pointer types. 8640 if (ConvTy == IncompatiblePointer && 8641 ((Context.isObjCNSObjectType(LHSType) && 8642 RHSType->isObjCObjectPointerType()) || 8643 (Context.isObjCNSObjectType(RHSType) && 8644 LHSType->isObjCObjectPointerType()))) 8645 ConvTy = Compatible; 8646 8647 if (ConvTy == Compatible && 8648 LHSType->isObjCObjectType()) 8649 Diag(Loc, diag::err_objc_object_assignment) 8650 << LHSType; 8651 8652 // If the RHS is a unary plus or minus, check to see if they = and + are 8653 // right next to each other. If so, the user may have typo'd "x =+ 4" 8654 // instead of "x += 4". 8655 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 8656 RHSCheck = ICE->getSubExpr(); 8657 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 8658 if ((UO->getOpcode() == UO_Plus || 8659 UO->getOpcode() == UO_Minus) && 8660 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 8661 // Only if the two operators are exactly adjacent. 8662 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 8663 // And there is a space or other character before the subexpr of the 8664 // unary +/-. We don't want to warn on "x=-1". 8665 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 8666 UO->getSubExpr()->getLocStart().isFileID()) { 8667 Diag(Loc, diag::warn_not_compound_assign) 8668 << (UO->getOpcode() == UO_Plus ? "+" : "-") 8669 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 8670 } 8671 } 8672 8673 if (ConvTy == Compatible) { 8674 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 8675 // Warn about retain cycles where a block captures the LHS, but 8676 // not if the LHS is a simple variable into which the block is 8677 // being stored...unless that variable can be captured by reference! 8678 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 8679 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 8680 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 8681 checkRetainCycles(LHSExpr, RHS.get()); 8682 8683 // It is safe to assign a weak reference into a strong variable. 8684 // Although this code can still have problems: 8685 // id x = self.weakProp; 8686 // id y = self.weakProp; 8687 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8688 // paths through the function. This should be revisited if 8689 // -Wrepeated-use-of-weak is made flow-sensitive. 8690 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 8691 RHS.get()->getLocStart())) 8692 getCurFunction()->markSafeWeakUse(RHS.get()); 8693 8694 } else if (getLangOpts().ObjCAutoRefCount) { 8695 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 8696 } 8697 } 8698 } else { 8699 // Compound assignment "x += y" 8700 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 8701 } 8702 8703 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 8704 RHS.get(), AA_Assigning)) 8705 return QualType(); 8706 8707 CheckForNullPointerDereference(*this, LHSExpr); 8708 8709 // C99 6.5.16p3: The type of an assignment expression is the type of the 8710 // left operand unless the left operand has qualified type, in which case 8711 // it is the unqualified version of the type of the left operand. 8712 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 8713 // is converted to the type of the assignment expression (above). 8714 // C++ 5.17p1: the type of the assignment expression is that of its left 8715 // operand. 8716 return (getLangOpts().CPlusPlus 8717 ? LHSType : LHSType.getUnqualifiedType()); 8718 } 8719 8720 // C99 6.5.17 8721 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 8722 SourceLocation Loc) { 8723 LHS = S.CheckPlaceholderExpr(LHS.get()); 8724 RHS = S.CheckPlaceholderExpr(RHS.get()); 8725 if (LHS.isInvalid() || RHS.isInvalid()) 8726 return QualType(); 8727 8728 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 8729 // operands, but not unary promotions. 8730 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 8731 8732 // So we treat the LHS as a ignored value, and in C++ we allow the 8733 // containing site to determine what should be done with the RHS. 8734 LHS = S.IgnoredValueConversions(LHS.get()); 8735 if (LHS.isInvalid()) 8736 return QualType(); 8737 8738 S.DiagnoseUnusedExprResult(LHS.get()); 8739 8740 if (!S.getLangOpts().CPlusPlus) { 8741 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8742 if (RHS.isInvalid()) 8743 return QualType(); 8744 if (!RHS.get()->getType()->isVoidType()) 8745 S.RequireCompleteType(Loc, RHS.get()->getType(), 8746 diag::err_incomplete_type); 8747 } 8748 8749 return RHS.get()->getType(); 8750 } 8751 8752 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 8753 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 8754 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 8755 ExprValueKind &VK, 8756 SourceLocation OpLoc, 8757 bool IsInc, bool IsPrefix) { 8758 if (Op->isTypeDependent()) 8759 return S.Context.DependentTy; 8760 8761 QualType ResType = Op->getType(); 8762 // Atomic types can be used for increment / decrement where the non-atomic 8763 // versions can, so ignore the _Atomic() specifier for the purpose of 8764 // checking. 8765 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8766 ResType = ResAtomicType->getValueType(); 8767 8768 assert(!ResType.isNull() && "no type for increment/decrement expression"); 8769 8770 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 8771 // Decrement of bool is not allowed. 8772 if (!IsInc) { 8773 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 8774 return QualType(); 8775 } 8776 // Increment of bool sets it to true, but is deprecated. 8777 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 8778 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 8779 // Error on enum increments and decrements in C++ mode 8780 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 8781 return QualType(); 8782 } else if (ResType->isRealType()) { 8783 // OK! 8784 } else if (ResType->isPointerType()) { 8785 // C99 6.5.2.4p2, 6.5.6p2 8786 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 8787 return QualType(); 8788 } else if (ResType->isObjCObjectPointerType()) { 8789 // On modern runtimes, ObjC pointer arithmetic is forbidden. 8790 // Otherwise, we just need a complete type. 8791 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 8792 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 8793 return QualType(); 8794 } else if (ResType->isAnyComplexType()) { 8795 // C99 does not support ++/-- on complex types, we allow as an extension. 8796 S.Diag(OpLoc, diag::ext_integer_increment_complex) 8797 << ResType << Op->getSourceRange(); 8798 } else if (ResType->isPlaceholderType()) { 8799 ExprResult PR = S.CheckPlaceholderExpr(Op); 8800 if (PR.isInvalid()) return QualType(); 8801 return CheckIncrementDecrementOperand(S, PR.get(), VK, OpLoc, 8802 IsInc, IsPrefix); 8803 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 8804 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 8805 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 8806 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 8807 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 8808 } else { 8809 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 8810 << ResType << int(IsInc) << Op->getSourceRange(); 8811 return QualType(); 8812 } 8813 // At this point, we know we have a real, complex or pointer type. 8814 // Now make sure the operand is a modifiable lvalue. 8815 if (CheckForModifiableLvalue(Op, OpLoc, S)) 8816 return QualType(); 8817 // In C++, a prefix increment is the same type as the operand. Otherwise 8818 // (in C or with postfix), the increment is the unqualified type of the 8819 // operand. 8820 if (IsPrefix && S.getLangOpts().CPlusPlus) { 8821 VK = VK_LValue; 8822 return ResType; 8823 } else { 8824 VK = VK_RValue; 8825 return ResType.getUnqualifiedType(); 8826 } 8827 } 8828 8829 8830 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 8831 /// This routine allows us to typecheck complex/recursive expressions 8832 /// where the declaration is needed for type checking. We only need to 8833 /// handle cases when the expression references a function designator 8834 /// or is an lvalue. Here are some examples: 8835 /// - &(x) => x 8836 /// - &*****f => f for f a function designator. 8837 /// - &s.xx => s 8838 /// - &s.zz[1].yy -> s, if zz is an array 8839 /// - *(x + 1) -> x, if x is an array 8840 /// - &"123"[2] -> 0 8841 /// - & __real__ x -> x 8842 static ValueDecl *getPrimaryDecl(Expr *E) { 8843 switch (E->getStmtClass()) { 8844 case Stmt::DeclRefExprClass: 8845 return cast<DeclRefExpr>(E)->getDecl(); 8846 case Stmt::MemberExprClass: 8847 // If this is an arrow operator, the address is an offset from 8848 // the base's value, so the object the base refers to is 8849 // irrelevant. 8850 if (cast<MemberExpr>(E)->isArrow()) 8851 return nullptr; 8852 // Otherwise, the expression refers to a part of the base 8853 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 8854 case Stmt::ArraySubscriptExprClass: { 8855 // FIXME: This code shouldn't be necessary! We should catch the implicit 8856 // promotion of register arrays earlier. 8857 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 8858 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 8859 if (ICE->getSubExpr()->getType()->isArrayType()) 8860 return getPrimaryDecl(ICE->getSubExpr()); 8861 } 8862 return nullptr; 8863 } 8864 case Stmt::UnaryOperatorClass: { 8865 UnaryOperator *UO = cast<UnaryOperator>(E); 8866 8867 switch(UO->getOpcode()) { 8868 case UO_Real: 8869 case UO_Imag: 8870 case UO_Extension: 8871 return getPrimaryDecl(UO->getSubExpr()); 8872 default: 8873 return nullptr; 8874 } 8875 } 8876 case Stmt::ParenExprClass: 8877 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 8878 case Stmt::ImplicitCastExprClass: 8879 // If the result of an implicit cast is an l-value, we care about 8880 // the sub-expression; otherwise, the result here doesn't matter. 8881 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 8882 default: 8883 return nullptr; 8884 } 8885 } 8886 8887 namespace { 8888 enum { 8889 AO_Bit_Field = 0, 8890 AO_Vector_Element = 1, 8891 AO_Property_Expansion = 2, 8892 AO_Register_Variable = 3, 8893 AO_No_Error = 4 8894 }; 8895 } 8896 /// \brief Diagnose invalid operand for address of operations. 8897 /// 8898 /// \param Type The type of operand which cannot have its address taken. 8899 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 8900 Expr *E, unsigned Type) { 8901 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 8902 } 8903 8904 /// CheckAddressOfOperand - The operand of & must be either a function 8905 /// designator or an lvalue designating an object. If it is an lvalue, the 8906 /// object cannot be declared with storage class register or be a bit field. 8907 /// Note: The usual conversions are *not* applied to the operand of the & 8908 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 8909 /// In C++, the operand might be an overloaded function name, in which case 8910 /// we allow the '&' but retain the overloaded-function type. 8911 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 8912 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 8913 if (PTy->getKind() == BuiltinType::Overload) { 8914 Expr *E = OrigOp.get()->IgnoreParens(); 8915 if (!isa<OverloadExpr>(E)) { 8916 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 8917 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 8918 << OrigOp.get()->getSourceRange(); 8919 return QualType(); 8920 } 8921 8922 OverloadExpr *Ovl = cast<OverloadExpr>(E); 8923 if (isa<UnresolvedMemberExpr>(Ovl)) 8924 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 8925 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8926 << OrigOp.get()->getSourceRange(); 8927 return QualType(); 8928 } 8929 8930 return Context.OverloadTy; 8931 } 8932 8933 if (PTy->getKind() == BuiltinType::UnknownAny) 8934 return Context.UnknownAnyTy; 8935 8936 if (PTy->getKind() == BuiltinType::BoundMember) { 8937 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8938 << OrigOp.get()->getSourceRange(); 8939 return QualType(); 8940 } 8941 8942 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 8943 if (OrigOp.isInvalid()) return QualType(); 8944 } 8945 8946 if (OrigOp.get()->isTypeDependent()) 8947 return Context.DependentTy; 8948 8949 assert(!OrigOp.get()->getType()->isPlaceholderType()); 8950 8951 // Make sure to ignore parentheses in subsequent checks 8952 Expr *op = OrigOp.get()->IgnoreParens(); 8953 8954 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 8955 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 8956 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 8957 return QualType(); 8958 } 8959 8960 if (getLangOpts().C99) { 8961 // Implement C99-only parts of addressof rules. 8962 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 8963 if (uOp->getOpcode() == UO_Deref) 8964 // Per C99 6.5.3.2, the address of a deref always returns a valid result 8965 // (assuming the deref expression is valid). 8966 return uOp->getSubExpr()->getType(); 8967 } 8968 // Technically, there should be a check for array subscript 8969 // expressions here, but the result of one is always an lvalue anyway. 8970 } 8971 ValueDecl *dcl = getPrimaryDecl(op); 8972 Expr::LValueClassification lval = op->ClassifyLValue(Context); 8973 unsigned AddressOfError = AO_No_Error; 8974 8975 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 8976 bool sfinae = (bool)isSFINAEContext(); 8977 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 8978 : diag::ext_typecheck_addrof_temporary) 8979 << op->getType() << op->getSourceRange(); 8980 if (sfinae) 8981 return QualType(); 8982 // Materialize the temporary as an lvalue so that we can take its address. 8983 OrigOp = op = new (Context) 8984 MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 8985 } else if (isa<ObjCSelectorExpr>(op)) { 8986 return Context.getPointerType(op->getType()); 8987 } else if (lval == Expr::LV_MemberFunction) { 8988 // If it's an instance method, make a member pointer. 8989 // The expression must have exactly the form &A::foo. 8990 8991 // If the underlying expression isn't a decl ref, give up. 8992 if (!isa<DeclRefExpr>(op)) { 8993 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8994 << OrigOp.get()->getSourceRange(); 8995 return QualType(); 8996 } 8997 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 8998 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 8999 9000 // The id-expression was parenthesized. 9001 if (OrigOp.get() != DRE) { 9002 Diag(OpLoc, diag::err_parens_pointer_member_function) 9003 << OrigOp.get()->getSourceRange(); 9004 9005 // The method was named without a qualifier. 9006 } else if (!DRE->getQualifier()) { 9007 if (MD->getParent()->getName().empty()) 9008 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 9009 << op->getSourceRange(); 9010 else { 9011 SmallString<32> Str; 9012 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 9013 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 9014 << op->getSourceRange() 9015 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 9016 } 9017 } 9018 9019 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 9020 if (isa<CXXDestructorDecl>(MD)) 9021 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 9022 9023 QualType MPTy = Context.getMemberPointerType( 9024 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 9025 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 9026 RequireCompleteType(OpLoc, MPTy, 0); 9027 return MPTy; 9028 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 9029 // C99 6.5.3.2p1 9030 // The operand must be either an l-value or a function designator 9031 if (!op->getType()->isFunctionType()) { 9032 // Use a special diagnostic for loads from property references. 9033 if (isa<PseudoObjectExpr>(op)) { 9034 AddressOfError = AO_Property_Expansion; 9035 } else { 9036 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 9037 << op->getType() << op->getSourceRange(); 9038 return QualType(); 9039 } 9040 } 9041 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 9042 // The operand cannot be a bit-field 9043 AddressOfError = AO_Bit_Field; 9044 } else if (op->getObjectKind() == OK_VectorComponent) { 9045 // The operand cannot be an element of a vector 9046 AddressOfError = AO_Vector_Element; 9047 } else if (dcl) { // C99 6.5.3.2p1 9048 // We have an lvalue with a decl. Make sure the decl is not declared 9049 // with the register storage-class specifier. 9050 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 9051 // in C++ it is not error to take address of a register 9052 // variable (c++03 7.1.1P3) 9053 if (vd->getStorageClass() == SC_Register && 9054 !getLangOpts().CPlusPlus) { 9055 AddressOfError = AO_Register_Variable; 9056 } 9057 } else if (isa<FunctionTemplateDecl>(dcl)) { 9058 return Context.OverloadTy; 9059 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 9060 // Okay: we can take the address of a field. 9061 // Could be a pointer to member, though, if there is an explicit 9062 // scope qualifier for the class. 9063 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 9064 DeclContext *Ctx = dcl->getDeclContext(); 9065 if (Ctx && Ctx->isRecord()) { 9066 if (dcl->getType()->isReferenceType()) { 9067 Diag(OpLoc, 9068 diag::err_cannot_form_pointer_to_member_of_reference_type) 9069 << dcl->getDeclName() << dcl->getType(); 9070 return QualType(); 9071 } 9072 9073 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 9074 Ctx = Ctx->getParent(); 9075 9076 QualType MPTy = Context.getMemberPointerType( 9077 op->getType(), 9078 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 9079 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 9080 RequireCompleteType(OpLoc, MPTy, 0); 9081 return MPTy; 9082 } 9083 } 9084 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 9085 llvm_unreachable("Unknown/unexpected decl type"); 9086 } 9087 9088 if (AddressOfError != AO_No_Error) { 9089 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 9090 return QualType(); 9091 } 9092 9093 if (lval == Expr::LV_IncompleteVoidType) { 9094 // Taking the address of a void variable is technically illegal, but we 9095 // allow it in cases which are otherwise valid. 9096 // Example: "extern void x; void* y = &x;". 9097 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 9098 } 9099 9100 // If the operand has type "type", the result has type "pointer to type". 9101 if (op->getType()->isObjCObjectType()) 9102 return Context.getObjCObjectPointerType(op->getType()); 9103 return Context.getPointerType(op->getType()); 9104 } 9105 9106 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 9107 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 9108 SourceLocation OpLoc) { 9109 if (Op->isTypeDependent()) 9110 return S.Context.DependentTy; 9111 9112 ExprResult ConvResult = S.UsualUnaryConversions(Op); 9113 if (ConvResult.isInvalid()) 9114 return QualType(); 9115 Op = ConvResult.get(); 9116 QualType OpTy = Op->getType(); 9117 QualType Result; 9118 9119 if (isa<CXXReinterpretCastExpr>(Op)) { 9120 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 9121 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 9122 Op->getSourceRange()); 9123 } 9124 9125 if (const PointerType *PT = OpTy->getAs<PointerType>()) 9126 Result = PT->getPointeeType(); 9127 else if (const ObjCObjectPointerType *OPT = 9128 OpTy->getAs<ObjCObjectPointerType>()) 9129 Result = OPT->getPointeeType(); 9130 else { 9131 ExprResult PR = S.CheckPlaceholderExpr(Op); 9132 if (PR.isInvalid()) return QualType(); 9133 if (PR.get() != Op) 9134 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 9135 } 9136 9137 if (Result.isNull()) { 9138 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 9139 << OpTy << Op->getSourceRange(); 9140 return QualType(); 9141 } 9142 9143 // Note that per both C89 and C99, indirection is always legal, even if Result 9144 // is an incomplete type or void. It would be possible to warn about 9145 // dereferencing a void pointer, but it's completely well-defined, and such a 9146 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 9147 // for pointers to 'void' but is fine for any other pointer type: 9148 // 9149 // C++ [expr.unary.op]p1: 9150 // [...] the expression to which [the unary * operator] is applied shall 9151 // be a pointer to an object type, or a pointer to a function type 9152 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 9153 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 9154 << OpTy << Op->getSourceRange(); 9155 9156 // Dereferences are usually l-values... 9157 VK = VK_LValue; 9158 9159 // ...except that certain expressions are never l-values in C. 9160 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 9161 VK = VK_RValue; 9162 9163 return Result; 9164 } 9165 9166 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode( 9167 tok::TokenKind Kind) { 9168 BinaryOperatorKind Opc; 9169 switch (Kind) { 9170 default: llvm_unreachable("Unknown binop!"); 9171 case tok::periodstar: Opc = BO_PtrMemD; break; 9172 case tok::arrowstar: Opc = BO_PtrMemI; break; 9173 case tok::star: Opc = BO_Mul; break; 9174 case tok::slash: Opc = BO_Div; break; 9175 case tok::percent: Opc = BO_Rem; break; 9176 case tok::plus: Opc = BO_Add; break; 9177 case tok::minus: Opc = BO_Sub; break; 9178 case tok::lessless: Opc = BO_Shl; break; 9179 case tok::greatergreater: Opc = BO_Shr; break; 9180 case tok::lessequal: Opc = BO_LE; break; 9181 case tok::less: Opc = BO_LT; break; 9182 case tok::greaterequal: Opc = BO_GE; break; 9183 case tok::greater: Opc = BO_GT; break; 9184 case tok::exclaimequal: Opc = BO_NE; break; 9185 case tok::equalequal: Opc = BO_EQ; break; 9186 case tok::amp: Opc = BO_And; break; 9187 case tok::caret: Opc = BO_Xor; break; 9188 case tok::pipe: Opc = BO_Or; break; 9189 case tok::ampamp: Opc = BO_LAnd; break; 9190 case tok::pipepipe: Opc = BO_LOr; break; 9191 case tok::equal: Opc = BO_Assign; break; 9192 case tok::starequal: Opc = BO_MulAssign; break; 9193 case tok::slashequal: Opc = BO_DivAssign; break; 9194 case tok::percentequal: Opc = BO_RemAssign; break; 9195 case tok::plusequal: Opc = BO_AddAssign; break; 9196 case tok::minusequal: Opc = BO_SubAssign; break; 9197 case tok::lesslessequal: Opc = BO_ShlAssign; break; 9198 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 9199 case tok::ampequal: Opc = BO_AndAssign; break; 9200 case tok::caretequal: Opc = BO_XorAssign; break; 9201 case tok::pipeequal: Opc = BO_OrAssign; break; 9202 case tok::comma: Opc = BO_Comma; break; 9203 } 9204 return Opc; 9205 } 9206 9207 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 9208 tok::TokenKind Kind) { 9209 UnaryOperatorKind Opc; 9210 switch (Kind) { 9211 default: llvm_unreachable("Unknown unary op!"); 9212 case tok::plusplus: Opc = UO_PreInc; break; 9213 case tok::minusminus: Opc = UO_PreDec; break; 9214 case tok::amp: Opc = UO_AddrOf; break; 9215 case tok::star: Opc = UO_Deref; break; 9216 case tok::plus: Opc = UO_Plus; break; 9217 case tok::minus: Opc = UO_Minus; break; 9218 case tok::tilde: Opc = UO_Not; break; 9219 case tok::exclaim: Opc = UO_LNot; break; 9220 case tok::kw___real: Opc = UO_Real; break; 9221 case tok::kw___imag: Opc = UO_Imag; break; 9222 case tok::kw___extension__: Opc = UO_Extension; break; 9223 } 9224 return Opc; 9225 } 9226 9227 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 9228 /// This warning is only emitted for builtin assignment operations. It is also 9229 /// suppressed in the event of macro expansions. 9230 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 9231 SourceLocation OpLoc) { 9232 if (!S.ActiveTemplateInstantiations.empty()) 9233 return; 9234 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 9235 return; 9236 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 9237 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 9238 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 9239 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 9240 if (!LHSDeclRef || !RHSDeclRef || 9241 LHSDeclRef->getLocation().isMacroID() || 9242 RHSDeclRef->getLocation().isMacroID()) 9243 return; 9244 const ValueDecl *LHSDecl = 9245 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 9246 const ValueDecl *RHSDecl = 9247 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 9248 if (LHSDecl != RHSDecl) 9249 return; 9250 if (LHSDecl->getType().isVolatileQualified()) 9251 return; 9252 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 9253 if (RefTy->getPointeeType().isVolatileQualified()) 9254 return; 9255 9256 S.Diag(OpLoc, diag::warn_self_assignment) 9257 << LHSDeclRef->getType() 9258 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9259 } 9260 9261 /// Check if a bitwise-& is performed on an Objective-C pointer. This 9262 /// is usually indicative of introspection within the Objective-C pointer. 9263 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 9264 SourceLocation OpLoc) { 9265 if (!S.getLangOpts().ObjC1) 9266 return; 9267 9268 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 9269 const Expr *LHS = L.get(); 9270 const Expr *RHS = R.get(); 9271 9272 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 9273 ObjCPointerExpr = LHS; 9274 OtherExpr = RHS; 9275 } 9276 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 9277 ObjCPointerExpr = RHS; 9278 OtherExpr = LHS; 9279 } 9280 9281 // This warning is deliberately made very specific to reduce false 9282 // positives with logic that uses '&' for hashing. This logic mainly 9283 // looks for code trying to introspect into tagged pointers, which 9284 // code should generally never do. 9285 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 9286 unsigned Diag = diag::warn_objc_pointer_masking; 9287 // Determine if we are introspecting the result of performSelectorXXX. 9288 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 9289 // Special case messages to -performSelector and friends, which 9290 // can return non-pointer values boxed in a pointer value. 9291 // Some clients may wish to silence warnings in this subcase. 9292 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 9293 Selector S = ME->getSelector(); 9294 StringRef SelArg0 = S.getNameForSlot(0); 9295 if (SelArg0.startswith("performSelector")) 9296 Diag = diag::warn_objc_pointer_masking_performSelector; 9297 } 9298 9299 S.Diag(OpLoc, Diag) 9300 << ObjCPointerExpr->getSourceRange(); 9301 } 9302 } 9303 9304 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 9305 /// operator @p Opc at location @c TokLoc. This routine only supports 9306 /// built-in operations; ActOnBinOp handles overloaded operators. 9307 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 9308 BinaryOperatorKind Opc, 9309 Expr *LHSExpr, Expr *RHSExpr) { 9310 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 9311 // The syntax only allows initializer lists on the RHS of assignment, 9312 // so we don't need to worry about accepting invalid code for 9313 // non-assignment operators. 9314 // C++11 5.17p9: 9315 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 9316 // of x = {} is x = T(). 9317 InitializationKind Kind = 9318 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 9319 InitializedEntity Entity = 9320 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 9321 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 9322 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 9323 if (Init.isInvalid()) 9324 return Init; 9325 RHSExpr = Init.get(); 9326 } 9327 9328 ExprResult LHS = LHSExpr, RHS = RHSExpr; 9329 QualType ResultTy; // Result type of the binary operator. 9330 // The following two variables are used for compound assignment operators 9331 QualType CompLHSTy; // Type of LHS after promotions for computation 9332 QualType CompResultTy; // Type of computation result 9333 ExprValueKind VK = VK_RValue; 9334 ExprObjectKind OK = OK_Ordinary; 9335 9336 switch (Opc) { 9337 case BO_Assign: 9338 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 9339 if (getLangOpts().CPlusPlus && 9340 LHS.get()->getObjectKind() != OK_ObjCProperty) { 9341 VK = LHS.get()->getValueKind(); 9342 OK = LHS.get()->getObjectKind(); 9343 } 9344 if (!ResultTy.isNull()) 9345 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 9346 break; 9347 case BO_PtrMemD: 9348 case BO_PtrMemI: 9349 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 9350 Opc == BO_PtrMemI); 9351 break; 9352 case BO_Mul: 9353 case BO_Div: 9354 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 9355 Opc == BO_Div); 9356 break; 9357 case BO_Rem: 9358 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 9359 break; 9360 case BO_Add: 9361 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 9362 break; 9363 case BO_Sub: 9364 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 9365 break; 9366 case BO_Shl: 9367 case BO_Shr: 9368 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 9369 break; 9370 case BO_LE: 9371 case BO_LT: 9372 case BO_GE: 9373 case BO_GT: 9374 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 9375 break; 9376 case BO_EQ: 9377 case BO_NE: 9378 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 9379 break; 9380 case BO_And: 9381 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 9382 case BO_Xor: 9383 case BO_Or: 9384 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 9385 break; 9386 case BO_LAnd: 9387 case BO_LOr: 9388 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 9389 break; 9390 case BO_MulAssign: 9391 case BO_DivAssign: 9392 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 9393 Opc == BO_DivAssign); 9394 CompLHSTy = CompResultTy; 9395 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9396 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9397 break; 9398 case BO_RemAssign: 9399 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 9400 CompLHSTy = CompResultTy; 9401 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9402 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9403 break; 9404 case BO_AddAssign: 9405 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 9406 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9407 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9408 break; 9409 case BO_SubAssign: 9410 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 9411 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9412 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9413 break; 9414 case BO_ShlAssign: 9415 case BO_ShrAssign: 9416 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 9417 CompLHSTy = CompResultTy; 9418 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9419 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9420 break; 9421 case BO_AndAssign: 9422 case BO_OrAssign: // fallthrough 9423 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 9424 case BO_XorAssign: 9425 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 9426 CompLHSTy = CompResultTy; 9427 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9428 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9429 break; 9430 case BO_Comma: 9431 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 9432 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 9433 VK = RHS.get()->getValueKind(); 9434 OK = RHS.get()->getObjectKind(); 9435 } 9436 break; 9437 } 9438 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 9439 return ExprError(); 9440 9441 // Check for array bounds violations for both sides of the BinaryOperator 9442 CheckArrayAccess(LHS.get()); 9443 CheckArrayAccess(RHS.get()); 9444 9445 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 9446 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 9447 &Context.Idents.get("object_setClass"), 9448 SourceLocation(), LookupOrdinaryName); 9449 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 9450 SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 9451 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 9452 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 9453 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 9454 FixItHint::CreateInsertion(RHSLocEnd, ")"); 9455 } 9456 else 9457 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 9458 } 9459 else if (const ObjCIvarRefExpr *OIRE = 9460 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 9461 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 9462 9463 if (CompResultTy.isNull()) 9464 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 9465 OK, OpLoc, FPFeatures.fp_contract); 9466 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 9467 OK_ObjCProperty) { 9468 VK = VK_LValue; 9469 OK = LHS.get()->getObjectKind(); 9470 } 9471 return new (Context) CompoundAssignOperator( 9472 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 9473 OpLoc, FPFeatures.fp_contract); 9474 } 9475 9476 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 9477 /// operators are mixed in a way that suggests that the programmer forgot that 9478 /// comparison operators have higher precedence. The most typical example of 9479 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 9480 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 9481 SourceLocation OpLoc, Expr *LHSExpr, 9482 Expr *RHSExpr) { 9483 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 9484 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 9485 9486 // Check that one of the sides is a comparison operator. 9487 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 9488 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 9489 if (!isLeftComp && !isRightComp) 9490 return; 9491 9492 // Bitwise operations are sometimes used as eager logical ops. 9493 // Don't diagnose this. 9494 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 9495 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 9496 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise)) 9497 return; 9498 9499 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 9500 OpLoc) 9501 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 9502 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 9503 SourceRange ParensRange = isLeftComp ? 9504 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 9505 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart()); 9506 9507 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 9508 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 9509 SuggestParentheses(Self, OpLoc, 9510 Self.PDiag(diag::note_precedence_silence) << OpStr, 9511 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 9512 SuggestParentheses(Self, OpLoc, 9513 Self.PDiag(diag::note_precedence_bitwise_first) 9514 << BinaryOperator::getOpcodeStr(Opc), 9515 ParensRange); 9516 } 9517 9518 /// \brief It accepts a '&' expr that is inside a '|' one. 9519 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression 9520 /// in parentheses. 9521 static void 9522 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 9523 BinaryOperator *Bop) { 9524 assert(Bop->getOpcode() == BO_And); 9525 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 9526 << Bop->getSourceRange() << OpLoc; 9527 SuggestParentheses(Self, Bop->getOperatorLoc(), 9528 Self.PDiag(diag::note_precedence_silence) 9529 << Bop->getOpcodeStr(), 9530 Bop->getSourceRange()); 9531 } 9532 9533 /// \brief It accepts a '&&' expr that is inside a '||' one. 9534 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 9535 /// in parentheses. 9536 static void 9537 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 9538 BinaryOperator *Bop) { 9539 assert(Bop->getOpcode() == BO_LAnd); 9540 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 9541 << Bop->getSourceRange() << OpLoc; 9542 SuggestParentheses(Self, Bop->getOperatorLoc(), 9543 Self.PDiag(diag::note_precedence_silence) 9544 << Bop->getOpcodeStr(), 9545 Bop->getSourceRange()); 9546 } 9547 9548 /// \brief Returns true if the given expression can be evaluated as a constant 9549 /// 'true'. 9550 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 9551 bool Res; 9552 return !E->isValueDependent() && 9553 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 9554 } 9555 9556 /// \brief Returns true if the given expression can be evaluated as a constant 9557 /// 'false'. 9558 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 9559 bool Res; 9560 return !E->isValueDependent() && 9561 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 9562 } 9563 9564 /// \brief Look for '&&' in the left hand of a '||' expr. 9565 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 9566 Expr *LHSExpr, Expr *RHSExpr) { 9567 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 9568 if (Bop->getOpcode() == BO_LAnd) { 9569 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 9570 if (EvaluatesAsFalse(S, RHSExpr)) 9571 return; 9572 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 9573 if (!EvaluatesAsTrue(S, Bop->getLHS())) 9574 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 9575 } else if (Bop->getOpcode() == BO_LOr) { 9576 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 9577 // If it's "a || b && 1 || c" we didn't warn earlier for 9578 // "a || b && 1", but warn now. 9579 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 9580 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 9581 } 9582 } 9583 } 9584 } 9585 9586 /// \brief Look for '&&' in the right hand of a '||' expr. 9587 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 9588 Expr *LHSExpr, Expr *RHSExpr) { 9589 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 9590 if (Bop->getOpcode() == BO_LAnd) { 9591 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 9592 if (EvaluatesAsFalse(S, LHSExpr)) 9593 return; 9594 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 9595 if (!EvaluatesAsTrue(S, Bop->getRHS())) 9596 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 9597 } 9598 } 9599 } 9600 9601 /// \brief Look for '&' in the left or right hand of a '|' expr. 9602 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 9603 Expr *OrArg) { 9604 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 9605 if (Bop->getOpcode() == BO_And) 9606 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 9607 } 9608 } 9609 9610 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 9611 Expr *SubExpr, StringRef Shift) { 9612 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 9613 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 9614 StringRef Op = Bop->getOpcodeStr(); 9615 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 9616 << Bop->getSourceRange() << OpLoc << Shift << Op; 9617 SuggestParentheses(S, Bop->getOperatorLoc(), 9618 S.PDiag(diag::note_precedence_silence) << Op, 9619 Bop->getSourceRange()); 9620 } 9621 } 9622 } 9623 9624 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 9625 Expr *LHSExpr, Expr *RHSExpr) { 9626 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 9627 if (!OCE) 9628 return; 9629 9630 FunctionDecl *FD = OCE->getDirectCallee(); 9631 if (!FD || !FD->isOverloadedOperator()) 9632 return; 9633 9634 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 9635 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 9636 return; 9637 9638 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 9639 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 9640 << (Kind == OO_LessLess); 9641 SuggestParentheses(S, OCE->getOperatorLoc(), 9642 S.PDiag(diag::note_precedence_silence) 9643 << (Kind == OO_LessLess ? "<<" : ">>"), 9644 OCE->getSourceRange()); 9645 SuggestParentheses(S, OpLoc, 9646 S.PDiag(diag::note_evaluate_comparison_first), 9647 SourceRange(OCE->getArg(1)->getLocStart(), 9648 RHSExpr->getLocEnd())); 9649 } 9650 9651 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 9652 /// precedence. 9653 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 9654 SourceLocation OpLoc, Expr *LHSExpr, 9655 Expr *RHSExpr){ 9656 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 9657 if (BinaryOperator::isBitwiseOp(Opc)) 9658 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 9659 9660 // Diagnose "arg1 & arg2 | arg3" 9661 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 9662 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr); 9663 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr); 9664 } 9665 9666 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 9667 // We don't warn for 'assert(a || b && "bad")' since this is safe. 9668 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 9669 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 9670 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 9671 } 9672 9673 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 9674 || Opc == BO_Shr) { 9675 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 9676 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 9677 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 9678 } 9679 9680 // Warn on overloaded shift operators and comparisons, such as: 9681 // cout << 5 == 4; 9682 if (BinaryOperator::isComparisonOp(Opc)) 9683 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 9684 } 9685 9686 // Binary Operators. 'Tok' is the token for the operator. 9687 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 9688 tok::TokenKind Kind, 9689 Expr *LHSExpr, Expr *RHSExpr) { 9690 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 9691 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 9692 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 9693 9694 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 9695 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 9696 9697 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 9698 } 9699 9700 /// Build an overloaded binary operator expression in the given scope. 9701 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 9702 BinaryOperatorKind Opc, 9703 Expr *LHS, Expr *RHS) { 9704 // Find all of the overloaded operators visible from this 9705 // point. We perform both an operator-name lookup from the local 9706 // scope and an argument-dependent lookup based on the types of 9707 // the arguments. 9708 UnresolvedSet<16> Functions; 9709 OverloadedOperatorKind OverOp 9710 = BinaryOperator::getOverloadedOperator(Opc); 9711 if (Sc && OverOp != OO_None) 9712 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 9713 RHS->getType(), Functions); 9714 9715 // Build the (potentially-overloaded, potentially-dependent) 9716 // binary operation. 9717 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 9718 } 9719 9720 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 9721 BinaryOperatorKind Opc, 9722 Expr *LHSExpr, Expr *RHSExpr) { 9723 // We want to end up calling one of checkPseudoObjectAssignment 9724 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 9725 // both expressions are overloadable or either is type-dependent), 9726 // or CreateBuiltinBinOp (in any other case). We also want to get 9727 // any placeholder types out of the way. 9728 9729 // Handle pseudo-objects in the LHS. 9730 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 9731 // Assignments with a pseudo-object l-value need special analysis. 9732 if (pty->getKind() == BuiltinType::PseudoObject && 9733 BinaryOperator::isAssignmentOp(Opc)) 9734 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 9735 9736 // Don't resolve overloads if the other type is overloadable. 9737 if (pty->getKind() == BuiltinType::Overload) { 9738 // We can't actually test that if we still have a placeholder, 9739 // though. Fortunately, none of the exceptions we see in that 9740 // code below are valid when the LHS is an overload set. Note 9741 // that an overload set can be dependently-typed, but it never 9742 // instantiates to having an overloadable type. 9743 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9744 if (resolvedRHS.isInvalid()) return ExprError(); 9745 RHSExpr = resolvedRHS.get(); 9746 9747 if (RHSExpr->isTypeDependent() || 9748 RHSExpr->getType()->isOverloadableType()) 9749 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9750 } 9751 9752 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 9753 if (LHS.isInvalid()) return ExprError(); 9754 LHSExpr = LHS.get(); 9755 } 9756 9757 // Handle pseudo-objects in the RHS. 9758 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 9759 // An overload in the RHS can potentially be resolved by the type 9760 // being assigned to. 9761 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 9762 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9763 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9764 9765 if (LHSExpr->getType()->isOverloadableType()) 9766 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9767 9768 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9769 } 9770 9771 // Don't resolve overloads if the other type is overloadable. 9772 if (pty->getKind() == BuiltinType::Overload && 9773 LHSExpr->getType()->isOverloadableType()) 9774 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9775 9776 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9777 if (!resolvedRHS.isUsable()) return ExprError(); 9778 RHSExpr = resolvedRHS.get(); 9779 } 9780 9781 if (getLangOpts().CPlusPlus) { 9782 // If either expression is type-dependent, always build an 9783 // overloaded op. 9784 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9785 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9786 9787 // Otherwise, build an overloaded op if either expression has an 9788 // overloadable type. 9789 if (LHSExpr->getType()->isOverloadableType() || 9790 RHSExpr->getType()->isOverloadableType()) 9791 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9792 } 9793 9794 // Build a built-in binary operation. 9795 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9796 } 9797 9798 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 9799 UnaryOperatorKind Opc, 9800 Expr *InputExpr) { 9801 ExprResult Input = InputExpr; 9802 ExprValueKind VK = VK_RValue; 9803 ExprObjectKind OK = OK_Ordinary; 9804 QualType resultType; 9805 switch (Opc) { 9806 case UO_PreInc: 9807 case UO_PreDec: 9808 case UO_PostInc: 9809 case UO_PostDec: 9810 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc, 9811 Opc == UO_PreInc || 9812 Opc == UO_PostInc, 9813 Opc == UO_PreInc || 9814 Opc == UO_PreDec); 9815 break; 9816 case UO_AddrOf: 9817 resultType = CheckAddressOfOperand(Input, OpLoc); 9818 break; 9819 case UO_Deref: { 9820 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 9821 if (Input.isInvalid()) return ExprError(); 9822 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 9823 break; 9824 } 9825 case UO_Plus: 9826 case UO_Minus: 9827 Input = UsualUnaryConversions(Input.get()); 9828 if (Input.isInvalid()) return ExprError(); 9829 resultType = Input.get()->getType(); 9830 if (resultType->isDependentType()) 9831 break; 9832 if (resultType->isArithmeticType() || // C99 6.5.3.3p1 9833 resultType->isVectorType()) 9834 break; 9835 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 9836 Opc == UO_Plus && 9837 resultType->isPointerType()) 9838 break; 9839 9840 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9841 << resultType << Input.get()->getSourceRange()); 9842 9843 case UO_Not: // bitwise complement 9844 Input = UsualUnaryConversions(Input.get()); 9845 if (Input.isInvalid()) 9846 return ExprError(); 9847 resultType = Input.get()->getType(); 9848 if (resultType->isDependentType()) 9849 break; 9850 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 9851 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 9852 // C99 does not support '~' for complex conjugation. 9853 Diag(OpLoc, diag::ext_integer_complement_complex) 9854 << resultType << Input.get()->getSourceRange(); 9855 else if (resultType->hasIntegerRepresentation()) 9856 break; 9857 else if (resultType->isExtVectorType()) { 9858 if (Context.getLangOpts().OpenCL) { 9859 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 9860 // on vector float types. 9861 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9862 if (!T->isIntegerType()) 9863 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9864 << resultType << Input.get()->getSourceRange()); 9865 } 9866 break; 9867 } else { 9868 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9869 << resultType << Input.get()->getSourceRange()); 9870 } 9871 break; 9872 9873 case UO_LNot: // logical negation 9874 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 9875 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 9876 if (Input.isInvalid()) return ExprError(); 9877 resultType = Input.get()->getType(); 9878 9879 // Though we still have to promote half FP to float... 9880 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 9881 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 9882 resultType = Context.FloatTy; 9883 } 9884 9885 if (resultType->isDependentType()) 9886 break; 9887 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 9888 // C99 6.5.3.3p1: ok, fallthrough; 9889 if (Context.getLangOpts().CPlusPlus) { 9890 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 9891 // operand contextually converted to bool. 9892 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 9893 ScalarTypeToBooleanCastKind(resultType)); 9894 } else if (Context.getLangOpts().OpenCL && 9895 Context.getLangOpts().OpenCLVersion < 120) { 9896 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9897 // operate on scalar float types. 9898 if (!resultType->isIntegerType()) 9899 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9900 << resultType << Input.get()->getSourceRange()); 9901 } 9902 } else if (resultType->isExtVectorType()) { 9903 if (Context.getLangOpts().OpenCL && 9904 Context.getLangOpts().OpenCLVersion < 120) { 9905 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9906 // operate on vector float types. 9907 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9908 if (!T->isIntegerType()) 9909 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9910 << resultType << Input.get()->getSourceRange()); 9911 } 9912 // Vector logical not returns the signed variant of the operand type. 9913 resultType = GetSignedVectorType(resultType); 9914 break; 9915 } else { 9916 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9917 << resultType << Input.get()->getSourceRange()); 9918 } 9919 9920 // LNot always has type int. C99 6.5.3.3p5. 9921 // In C++, it's bool. C++ 5.3.1p8 9922 resultType = Context.getLogicalOperationType(); 9923 break; 9924 case UO_Real: 9925 case UO_Imag: 9926 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 9927 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 9928 // complex l-values to ordinary l-values and all other values to r-values. 9929 if (Input.isInvalid()) return ExprError(); 9930 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 9931 if (Input.get()->getValueKind() != VK_RValue && 9932 Input.get()->getObjectKind() == OK_Ordinary) 9933 VK = Input.get()->getValueKind(); 9934 } else if (!getLangOpts().CPlusPlus) { 9935 // In C, a volatile scalar is read by __imag. In C++, it is not. 9936 Input = DefaultLvalueConversion(Input.get()); 9937 } 9938 break; 9939 case UO_Extension: 9940 resultType = Input.get()->getType(); 9941 VK = Input.get()->getValueKind(); 9942 OK = Input.get()->getObjectKind(); 9943 break; 9944 } 9945 if (resultType.isNull() || Input.isInvalid()) 9946 return ExprError(); 9947 9948 // Check for array bounds violations in the operand of the UnaryOperator, 9949 // except for the '*' and '&' operators that have to be handled specially 9950 // by CheckArrayAccess (as there are special cases like &array[arraysize] 9951 // that are explicitly defined as valid by the standard). 9952 if (Opc != UO_AddrOf && Opc != UO_Deref) 9953 CheckArrayAccess(Input.get()); 9954 9955 return new (Context) 9956 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 9957 } 9958 9959 /// \brief Determine whether the given expression is a qualified member 9960 /// access expression, of a form that could be turned into a pointer to member 9961 /// with the address-of operator. 9962 static bool isQualifiedMemberAccess(Expr *E) { 9963 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9964 if (!DRE->getQualifier()) 9965 return false; 9966 9967 ValueDecl *VD = DRE->getDecl(); 9968 if (!VD->isCXXClassMember()) 9969 return false; 9970 9971 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 9972 return true; 9973 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 9974 return Method->isInstance(); 9975 9976 return false; 9977 } 9978 9979 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 9980 if (!ULE->getQualifier()) 9981 return false; 9982 9983 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(), 9984 DEnd = ULE->decls_end(); 9985 D != DEnd; ++D) { 9986 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) { 9987 if (Method->isInstance()) 9988 return true; 9989 } else { 9990 // Overload set does not contain methods. 9991 break; 9992 } 9993 } 9994 9995 return false; 9996 } 9997 9998 return false; 9999 } 10000 10001 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 10002 UnaryOperatorKind Opc, Expr *Input) { 10003 // First things first: handle placeholders so that the 10004 // overloaded-operator check considers the right type. 10005 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 10006 // Increment and decrement of pseudo-object references. 10007 if (pty->getKind() == BuiltinType::PseudoObject && 10008 UnaryOperator::isIncrementDecrementOp(Opc)) 10009 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 10010 10011 // extension is always a builtin operator. 10012 if (Opc == UO_Extension) 10013 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10014 10015 // & gets special logic for several kinds of placeholder. 10016 // The builtin code knows what to do. 10017 if (Opc == UO_AddrOf && 10018 (pty->getKind() == BuiltinType::Overload || 10019 pty->getKind() == BuiltinType::UnknownAny || 10020 pty->getKind() == BuiltinType::BoundMember)) 10021 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10022 10023 // Anything else needs to be handled now. 10024 ExprResult Result = CheckPlaceholderExpr(Input); 10025 if (Result.isInvalid()) return ExprError(); 10026 Input = Result.get(); 10027 } 10028 10029 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 10030 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 10031 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 10032 // Find all of the overloaded operators visible from this 10033 // point. We perform both an operator-name lookup from the local 10034 // scope and an argument-dependent lookup based on the types of 10035 // the arguments. 10036 UnresolvedSet<16> Functions; 10037 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 10038 if (S && OverOp != OO_None) 10039 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 10040 Functions); 10041 10042 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 10043 } 10044 10045 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10046 } 10047 10048 // Unary Operators. 'Tok' is the token for the operator. 10049 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 10050 tok::TokenKind Op, Expr *Input) { 10051 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 10052 } 10053 10054 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 10055 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 10056 LabelDecl *TheDecl) { 10057 TheDecl->markUsed(Context); 10058 // Create the AST node. The address of a label always has type 'void*'. 10059 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 10060 Context.getPointerType(Context.VoidTy)); 10061 } 10062 10063 /// Given the last statement in a statement-expression, check whether 10064 /// the result is a producing expression (like a call to an 10065 /// ns_returns_retained function) and, if so, rebuild it to hoist the 10066 /// release out of the full-expression. Otherwise, return null. 10067 /// Cannot fail. 10068 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 10069 // Should always be wrapped with one of these. 10070 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 10071 if (!cleanups) return nullptr; 10072 10073 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 10074 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 10075 return nullptr; 10076 10077 // Splice out the cast. This shouldn't modify any interesting 10078 // features of the statement. 10079 Expr *producer = cast->getSubExpr(); 10080 assert(producer->getType() == cast->getType()); 10081 assert(producer->getValueKind() == cast->getValueKind()); 10082 cleanups->setSubExpr(producer); 10083 return cleanups; 10084 } 10085 10086 void Sema::ActOnStartStmtExpr() { 10087 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 10088 } 10089 10090 void Sema::ActOnStmtExprError() { 10091 // Note that function is also called by TreeTransform when leaving a 10092 // StmtExpr scope without rebuilding anything. 10093 10094 DiscardCleanupsInEvaluationContext(); 10095 PopExpressionEvaluationContext(); 10096 } 10097 10098 ExprResult 10099 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 10100 SourceLocation RPLoc) { // "({..})" 10101 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 10102 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 10103 10104 if (hasAnyUnrecoverableErrorsInThisFunction()) 10105 DiscardCleanupsInEvaluationContext(); 10106 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 10107 PopExpressionEvaluationContext(); 10108 10109 bool isFileScope 10110 = (getCurFunctionOrMethodDecl() == nullptr) && (getCurBlock() == nullptr); 10111 if (isFileScope) 10112 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 10113 10114 // FIXME: there are a variety of strange constraints to enforce here, for 10115 // example, it is not possible to goto into a stmt expression apparently. 10116 // More semantic analysis is needed. 10117 10118 // If there are sub-stmts in the compound stmt, take the type of the last one 10119 // as the type of the stmtexpr. 10120 QualType Ty = Context.VoidTy; 10121 bool StmtExprMayBindToTemp = false; 10122 if (!Compound->body_empty()) { 10123 Stmt *LastStmt = Compound->body_back(); 10124 LabelStmt *LastLabelStmt = nullptr; 10125 // If LastStmt is a label, skip down through into the body. 10126 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 10127 LastLabelStmt = Label; 10128 LastStmt = Label->getSubStmt(); 10129 } 10130 10131 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 10132 // Do function/array conversion on the last expression, but not 10133 // lvalue-to-rvalue. However, initialize an unqualified type. 10134 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 10135 if (LastExpr.isInvalid()) 10136 return ExprError(); 10137 Ty = LastExpr.get()->getType().getUnqualifiedType(); 10138 10139 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 10140 // In ARC, if the final expression ends in a consume, splice 10141 // the consume out and bind it later. In the alternate case 10142 // (when dealing with a retainable type), the result 10143 // initialization will create a produce. In both cases the 10144 // result will be +1, and we'll need to balance that out with 10145 // a bind. 10146 if (Expr *rebuiltLastStmt 10147 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 10148 LastExpr = rebuiltLastStmt; 10149 } else { 10150 LastExpr = PerformCopyInitialization( 10151 InitializedEntity::InitializeResult(LPLoc, 10152 Ty, 10153 false), 10154 SourceLocation(), 10155 LastExpr); 10156 } 10157 10158 if (LastExpr.isInvalid()) 10159 return ExprError(); 10160 if (LastExpr.get() != nullptr) { 10161 if (!LastLabelStmt) 10162 Compound->setLastStmt(LastExpr.get()); 10163 else 10164 LastLabelStmt->setSubStmt(LastExpr.get()); 10165 StmtExprMayBindToTemp = true; 10166 } 10167 } 10168 } 10169 } 10170 10171 // FIXME: Check that expression type is complete/non-abstract; statement 10172 // expressions are not lvalues. 10173 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 10174 if (StmtExprMayBindToTemp) 10175 return MaybeBindToTemporary(ResStmtExpr); 10176 return ResStmtExpr; 10177 } 10178 10179 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 10180 TypeSourceInfo *TInfo, 10181 OffsetOfComponent *CompPtr, 10182 unsigned NumComponents, 10183 SourceLocation RParenLoc) { 10184 QualType ArgTy = TInfo->getType(); 10185 bool Dependent = ArgTy->isDependentType(); 10186 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 10187 10188 // We must have at least one component that refers to the type, and the first 10189 // one is known to be a field designator. Verify that the ArgTy represents 10190 // a struct/union/class. 10191 if (!Dependent && !ArgTy->isRecordType()) 10192 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 10193 << ArgTy << TypeRange); 10194 10195 // Type must be complete per C99 7.17p3 because a declaring a variable 10196 // with an incomplete type would be ill-formed. 10197 if (!Dependent 10198 && RequireCompleteType(BuiltinLoc, ArgTy, 10199 diag::err_offsetof_incomplete_type, TypeRange)) 10200 return ExprError(); 10201 10202 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 10203 // GCC extension, diagnose them. 10204 // FIXME: This diagnostic isn't actually visible because the location is in 10205 // a system header! 10206 if (NumComponents != 1) 10207 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 10208 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 10209 10210 bool DidWarnAboutNonPOD = false; 10211 QualType CurrentType = ArgTy; 10212 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 10213 SmallVector<OffsetOfNode, 4> Comps; 10214 SmallVector<Expr*, 4> Exprs; 10215 for (unsigned i = 0; i != NumComponents; ++i) { 10216 const OffsetOfComponent &OC = CompPtr[i]; 10217 if (OC.isBrackets) { 10218 // Offset of an array sub-field. TODO: Should we allow vector elements? 10219 if (!CurrentType->isDependentType()) { 10220 const ArrayType *AT = Context.getAsArrayType(CurrentType); 10221 if(!AT) 10222 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 10223 << CurrentType); 10224 CurrentType = AT->getElementType(); 10225 } else 10226 CurrentType = Context.DependentTy; 10227 10228 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 10229 if (IdxRval.isInvalid()) 10230 return ExprError(); 10231 Expr *Idx = IdxRval.get(); 10232 10233 // The expression must be an integral expression. 10234 // FIXME: An integral constant expression? 10235 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 10236 !Idx->getType()->isIntegerType()) 10237 return ExprError(Diag(Idx->getLocStart(), 10238 diag::err_typecheck_subscript_not_integer) 10239 << Idx->getSourceRange()); 10240 10241 // Record this array index. 10242 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 10243 Exprs.push_back(Idx); 10244 continue; 10245 } 10246 10247 // Offset of a field. 10248 if (CurrentType->isDependentType()) { 10249 // We have the offset of a field, but we can't look into the dependent 10250 // type. Just record the identifier of the field. 10251 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 10252 CurrentType = Context.DependentTy; 10253 continue; 10254 } 10255 10256 // We need to have a complete type to look into. 10257 if (RequireCompleteType(OC.LocStart, CurrentType, 10258 diag::err_offsetof_incomplete_type)) 10259 return ExprError(); 10260 10261 // Look for the designated field. 10262 const RecordType *RC = CurrentType->getAs<RecordType>(); 10263 if (!RC) 10264 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 10265 << CurrentType); 10266 RecordDecl *RD = RC->getDecl(); 10267 10268 // C++ [lib.support.types]p5: 10269 // The macro offsetof accepts a restricted set of type arguments in this 10270 // International Standard. type shall be a POD structure or a POD union 10271 // (clause 9). 10272 // C++11 [support.types]p4: 10273 // If type is not a standard-layout class (Clause 9), the results are 10274 // undefined. 10275 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 10276 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 10277 unsigned DiagID = 10278 LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type 10279 : diag::warn_offsetof_non_pod_type; 10280 10281 if (!IsSafe && !DidWarnAboutNonPOD && 10282 DiagRuntimeBehavior(BuiltinLoc, nullptr, 10283 PDiag(DiagID) 10284 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 10285 << CurrentType)) 10286 DidWarnAboutNonPOD = true; 10287 } 10288 10289 // Look for the field. 10290 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 10291 LookupQualifiedName(R, RD); 10292 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 10293 IndirectFieldDecl *IndirectMemberDecl = nullptr; 10294 if (!MemberDecl) { 10295 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 10296 MemberDecl = IndirectMemberDecl->getAnonField(); 10297 } 10298 10299 if (!MemberDecl) 10300 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 10301 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 10302 OC.LocEnd)); 10303 10304 // C99 7.17p3: 10305 // (If the specified member is a bit-field, the behavior is undefined.) 10306 // 10307 // We diagnose this as an error. 10308 if (MemberDecl->isBitField()) { 10309 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 10310 << MemberDecl->getDeclName() 10311 << SourceRange(BuiltinLoc, RParenLoc); 10312 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 10313 return ExprError(); 10314 } 10315 10316 RecordDecl *Parent = MemberDecl->getParent(); 10317 if (IndirectMemberDecl) 10318 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 10319 10320 // If the member was found in a base class, introduce OffsetOfNodes for 10321 // the base class indirections. 10322 CXXBasePaths Paths; 10323 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 10324 if (Paths.getDetectedVirtual()) { 10325 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 10326 << MemberDecl->getDeclName() 10327 << SourceRange(BuiltinLoc, RParenLoc); 10328 return ExprError(); 10329 } 10330 10331 CXXBasePath &Path = Paths.front(); 10332 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 10333 B != BEnd; ++B) 10334 Comps.push_back(OffsetOfNode(B->Base)); 10335 } 10336 10337 if (IndirectMemberDecl) { 10338 for (auto *FI : IndirectMemberDecl->chain()) { 10339 assert(isa<FieldDecl>(FI)); 10340 Comps.push_back(OffsetOfNode(OC.LocStart, 10341 cast<FieldDecl>(FI), OC.LocEnd)); 10342 } 10343 } else 10344 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 10345 10346 CurrentType = MemberDecl->getType().getNonReferenceType(); 10347 } 10348 10349 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 10350 Comps, Exprs, RParenLoc); 10351 } 10352 10353 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 10354 SourceLocation BuiltinLoc, 10355 SourceLocation TypeLoc, 10356 ParsedType ParsedArgTy, 10357 OffsetOfComponent *CompPtr, 10358 unsigned NumComponents, 10359 SourceLocation RParenLoc) { 10360 10361 TypeSourceInfo *ArgTInfo; 10362 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 10363 if (ArgTy.isNull()) 10364 return ExprError(); 10365 10366 if (!ArgTInfo) 10367 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 10368 10369 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 10370 RParenLoc); 10371 } 10372 10373 10374 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 10375 Expr *CondExpr, 10376 Expr *LHSExpr, Expr *RHSExpr, 10377 SourceLocation RPLoc) { 10378 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 10379 10380 ExprValueKind VK = VK_RValue; 10381 ExprObjectKind OK = OK_Ordinary; 10382 QualType resType; 10383 bool ValueDependent = false; 10384 bool CondIsTrue = false; 10385 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 10386 resType = Context.DependentTy; 10387 ValueDependent = true; 10388 } else { 10389 // The conditional expression is required to be a constant expression. 10390 llvm::APSInt condEval(32); 10391 ExprResult CondICE 10392 = VerifyIntegerConstantExpression(CondExpr, &condEval, 10393 diag::err_typecheck_choose_expr_requires_constant, false); 10394 if (CondICE.isInvalid()) 10395 return ExprError(); 10396 CondExpr = CondICE.get(); 10397 CondIsTrue = condEval.getZExtValue(); 10398 10399 // If the condition is > zero, then the AST type is the same as the LSHExpr. 10400 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 10401 10402 resType = ActiveExpr->getType(); 10403 ValueDependent = ActiveExpr->isValueDependent(); 10404 VK = ActiveExpr->getValueKind(); 10405 OK = ActiveExpr->getObjectKind(); 10406 } 10407 10408 return new (Context) 10409 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 10410 CondIsTrue, resType->isDependentType(), ValueDependent); 10411 } 10412 10413 //===----------------------------------------------------------------------===// 10414 // Clang Extensions. 10415 //===----------------------------------------------------------------------===// 10416 10417 /// ActOnBlockStart - This callback is invoked when a block literal is started. 10418 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 10419 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 10420 10421 if (LangOpts.CPlusPlus) { 10422 Decl *ManglingContextDecl; 10423 if (MangleNumberingContext *MCtx = 10424 getCurrentMangleNumberContext(Block->getDeclContext(), 10425 ManglingContextDecl)) { 10426 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 10427 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 10428 } 10429 } 10430 10431 PushBlockScope(CurScope, Block); 10432 CurContext->addDecl(Block); 10433 if (CurScope) 10434 PushDeclContext(CurScope, Block); 10435 else 10436 CurContext = Block; 10437 10438 getCurBlock()->HasImplicitReturnType = true; 10439 10440 // Enter a new evaluation context to insulate the block from any 10441 // cleanups from the enclosing full-expression. 10442 PushExpressionEvaluationContext(PotentiallyEvaluated); 10443 } 10444 10445 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 10446 Scope *CurScope) { 10447 assert(ParamInfo.getIdentifier() == nullptr && 10448 "block-id should have no identifier!"); 10449 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 10450 BlockScopeInfo *CurBlock = getCurBlock(); 10451 10452 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 10453 QualType T = Sig->getType(); 10454 10455 // FIXME: We should allow unexpanded parameter packs here, but that would, 10456 // in turn, make the block expression contain unexpanded parameter packs. 10457 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 10458 // Drop the parameters. 10459 FunctionProtoType::ExtProtoInfo EPI; 10460 EPI.HasTrailingReturn = false; 10461 EPI.TypeQuals |= DeclSpec::TQ_const; 10462 T = Context.getFunctionType(Context.DependentTy, None, EPI); 10463 Sig = Context.getTrivialTypeSourceInfo(T); 10464 } 10465 10466 // GetTypeForDeclarator always produces a function type for a block 10467 // literal signature. Furthermore, it is always a FunctionProtoType 10468 // unless the function was written with a typedef. 10469 assert(T->isFunctionType() && 10470 "GetTypeForDeclarator made a non-function block signature"); 10471 10472 // Look for an explicit signature in that function type. 10473 FunctionProtoTypeLoc ExplicitSignature; 10474 10475 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 10476 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 10477 10478 // Check whether that explicit signature was synthesized by 10479 // GetTypeForDeclarator. If so, don't save that as part of the 10480 // written signature. 10481 if (ExplicitSignature.getLocalRangeBegin() == 10482 ExplicitSignature.getLocalRangeEnd()) { 10483 // This would be much cheaper if we stored TypeLocs instead of 10484 // TypeSourceInfos. 10485 TypeLoc Result = ExplicitSignature.getReturnLoc(); 10486 unsigned Size = Result.getFullDataSize(); 10487 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 10488 Sig->getTypeLoc().initializeFullCopy(Result, Size); 10489 10490 ExplicitSignature = FunctionProtoTypeLoc(); 10491 } 10492 } 10493 10494 CurBlock->TheDecl->setSignatureAsWritten(Sig); 10495 CurBlock->FunctionType = T; 10496 10497 const FunctionType *Fn = T->getAs<FunctionType>(); 10498 QualType RetTy = Fn->getReturnType(); 10499 bool isVariadic = 10500 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 10501 10502 CurBlock->TheDecl->setIsVariadic(isVariadic); 10503 10504 // Context.DependentTy is used as a placeholder for a missing block 10505 // return type. TODO: what should we do with declarators like: 10506 // ^ * { ... } 10507 // If the answer is "apply template argument deduction".... 10508 if (RetTy != Context.DependentTy) { 10509 CurBlock->ReturnType = RetTy; 10510 CurBlock->TheDecl->setBlockMissingReturnType(false); 10511 CurBlock->HasImplicitReturnType = false; 10512 } 10513 10514 // Push block parameters from the declarator if we had them. 10515 SmallVector<ParmVarDecl*, 8> Params; 10516 if (ExplicitSignature) { 10517 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 10518 ParmVarDecl *Param = ExplicitSignature.getParam(I); 10519 if (Param->getIdentifier() == nullptr && 10520 !Param->isImplicit() && 10521 !Param->isInvalidDecl() && 10522 !getLangOpts().CPlusPlus) 10523 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 10524 Params.push_back(Param); 10525 } 10526 10527 // Fake up parameter variables if we have a typedef, like 10528 // ^ fntype { ... } 10529 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 10530 for (const auto &I : Fn->param_types()) { 10531 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 10532 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 10533 Params.push_back(Param); 10534 } 10535 } 10536 10537 // Set the parameters on the block decl. 10538 if (!Params.empty()) { 10539 CurBlock->TheDecl->setParams(Params); 10540 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 10541 CurBlock->TheDecl->param_end(), 10542 /*CheckParameterNames=*/false); 10543 } 10544 10545 // Finally we can process decl attributes. 10546 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 10547 10548 // Put the parameter variables in scope. 10549 for (auto AI : CurBlock->TheDecl->params()) { 10550 AI->setOwningFunction(CurBlock->TheDecl); 10551 10552 // If this has an identifier, add it to the scope stack. 10553 if (AI->getIdentifier()) { 10554 CheckShadow(CurBlock->TheScope, AI); 10555 10556 PushOnScopeChains(AI, CurBlock->TheScope); 10557 } 10558 } 10559 } 10560 10561 /// ActOnBlockError - If there is an error parsing a block, this callback 10562 /// is invoked to pop the information about the block from the action impl. 10563 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 10564 // Leave the expression-evaluation context. 10565 DiscardCleanupsInEvaluationContext(); 10566 PopExpressionEvaluationContext(); 10567 10568 // Pop off CurBlock, handle nested blocks. 10569 PopDeclContext(); 10570 PopFunctionScopeInfo(); 10571 } 10572 10573 /// ActOnBlockStmtExpr - This is called when the body of a block statement 10574 /// literal was successfully completed. ^(int x){...} 10575 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 10576 Stmt *Body, Scope *CurScope) { 10577 // If blocks are disabled, emit an error. 10578 if (!LangOpts.Blocks) 10579 Diag(CaretLoc, diag::err_blocks_disable); 10580 10581 // Leave the expression-evaluation context. 10582 if (hasAnyUnrecoverableErrorsInThisFunction()) 10583 DiscardCleanupsInEvaluationContext(); 10584 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 10585 PopExpressionEvaluationContext(); 10586 10587 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 10588 10589 if (BSI->HasImplicitReturnType) 10590 deduceClosureReturnType(*BSI); 10591 10592 PopDeclContext(); 10593 10594 QualType RetTy = Context.VoidTy; 10595 if (!BSI->ReturnType.isNull()) 10596 RetTy = BSI->ReturnType; 10597 10598 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 10599 QualType BlockTy; 10600 10601 // Set the captured variables on the block. 10602 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 10603 SmallVector<BlockDecl::Capture, 4> Captures; 10604 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) { 10605 CapturingScopeInfo::Capture &Cap = BSI->Captures[i]; 10606 if (Cap.isThisCapture()) 10607 continue; 10608 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 10609 Cap.isNested(), Cap.getInitExpr()); 10610 Captures.push_back(NewCap); 10611 } 10612 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(), 10613 BSI->CXXThisCaptureIndex != 0); 10614 10615 // If the user wrote a function type in some form, try to use that. 10616 if (!BSI->FunctionType.isNull()) { 10617 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 10618 10619 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 10620 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 10621 10622 // Turn protoless block types into nullary block types. 10623 if (isa<FunctionNoProtoType>(FTy)) { 10624 FunctionProtoType::ExtProtoInfo EPI; 10625 EPI.ExtInfo = Ext; 10626 BlockTy = Context.getFunctionType(RetTy, None, EPI); 10627 10628 // Otherwise, if we don't need to change anything about the function type, 10629 // preserve its sugar structure. 10630 } else if (FTy->getReturnType() == RetTy && 10631 (!NoReturn || FTy->getNoReturnAttr())) { 10632 BlockTy = BSI->FunctionType; 10633 10634 // Otherwise, make the minimal modifications to the function type. 10635 } else { 10636 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 10637 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10638 EPI.TypeQuals = 0; // FIXME: silently? 10639 EPI.ExtInfo = Ext; 10640 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 10641 } 10642 10643 // If we don't have a function type, just build one from nothing. 10644 } else { 10645 FunctionProtoType::ExtProtoInfo EPI; 10646 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 10647 BlockTy = Context.getFunctionType(RetTy, None, EPI); 10648 } 10649 10650 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 10651 BSI->TheDecl->param_end()); 10652 BlockTy = Context.getBlockPointerType(BlockTy); 10653 10654 // If needed, diagnose invalid gotos and switches in the block. 10655 if (getCurFunction()->NeedsScopeChecking() && 10656 !PP.isCodeCompletionEnabled()) 10657 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 10658 10659 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 10660 10661 // Try to apply the named return value optimization. We have to check again 10662 // if we can do this, though, because blocks keep return statements around 10663 // to deduce an implicit return type. 10664 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 10665 !BSI->TheDecl->isDependentContext()) 10666 computeNRVO(Body, BSI); 10667 10668 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 10669 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 10670 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 10671 10672 // If the block isn't obviously global, i.e. it captures anything at 10673 // all, then we need to do a few things in the surrounding context: 10674 if (Result->getBlockDecl()->hasCaptures()) { 10675 // First, this expression has a new cleanup object. 10676 ExprCleanupObjects.push_back(Result->getBlockDecl()); 10677 ExprNeedsCleanups = true; 10678 10679 // It also gets a branch-protected scope if any of the captured 10680 // variables needs destruction. 10681 for (const auto &CI : Result->getBlockDecl()->captures()) { 10682 const VarDecl *var = CI.getVariable(); 10683 if (var->getType().isDestructedType() != QualType::DK_none) { 10684 getCurFunction()->setHasBranchProtectedScope(); 10685 break; 10686 } 10687 } 10688 } 10689 10690 return Result; 10691 } 10692 10693 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 10694 Expr *E, ParsedType Ty, 10695 SourceLocation RPLoc) { 10696 TypeSourceInfo *TInfo; 10697 GetTypeFromParser(Ty, &TInfo); 10698 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 10699 } 10700 10701 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 10702 Expr *E, TypeSourceInfo *TInfo, 10703 SourceLocation RPLoc) { 10704 Expr *OrigExpr = E; 10705 10706 // Get the va_list type 10707 QualType VaListType = Context.getBuiltinVaListType(); 10708 if (VaListType->isArrayType()) { 10709 // Deal with implicit array decay; for example, on x86-64, 10710 // va_list is an array, but it's supposed to decay to 10711 // a pointer for va_arg. 10712 VaListType = Context.getArrayDecayedType(VaListType); 10713 // Make sure the input expression also decays appropriately. 10714 ExprResult Result = UsualUnaryConversions(E); 10715 if (Result.isInvalid()) 10716 return ExprError(); 10717 E = Result.get(); 10718 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 10719 // If va_list is a record type and we are compiling in C++ mode, 10720 // check the argument using reference binding. 10721 InitializedEntity Entity 10722 = InitializedEntity::InitializeParameter(Context, 10723 Context.getLValueReferenceType(VaListType), false); 10724 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 10725 if (Init.isInvalid()) 10726 return ExprError(); 10727 E = Init.getAs<Expr>(); 10728 } else { 10729 // Otherwise, the va_list argument must be an l-value because 10730 // it is modified by va_arg. 10731 if (!E->isTypeDependent() && 10732 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 10733 return ExprError(); 10734 } 10735 10736 if (!E->isTypeDependent() && 10737 !Context.hasSameType(VaListType, E->getType())) { 10738 return ExprError(Diag(E->getLocStart(), 10739 diag::err_first_argument_to_va_arg_not_of_type_va_list) 10740 << OrigExpr->getType() << E->getSourceRange()); 10741 } 10742 10743 if (!TInfo->getType()->isDependentType()) { 10744 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 10745 diag::err_second_parameter_to_va_arg_incomplete, 10746 TInfo->getTypeLoc())) 10747 return ExprError(); 10748 10749 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 10750 TInfo->getType(), 10751 diag::err_second_parameter_to_va_arg_abstract, 10752 TInfo->getTypeLoc())) 10753 return ExprError(); 10754 10755 if (!TInfo->getType().isPODType(Context)) { 10756 Diag(TInfo->getTypeLoc().getBeginLoc(), 10757 TInfo->getType()->isObjCLifetimeType() 10758 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 10759 : diag::warn_second_parameter_to_va_arg_not_pod) 10760 << TInfo->getType() 10761 << TInfo->getTypeLoc().getSourceRange(); 10762 } 10763 10764 // Check for va_arg where arguments of the given type will be promoted 10765 // (i.e. this va_arg is guaranteed to have undefined behavior). 10766 QualType PromoteType; 10767 if (TInfo->getType()->isPromotableIntegerType()) { 10768 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 10769 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 10770 PromoteType = QualType(); 10771 } 10772 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 10773 PromoteType = Context.DoubleTy; 10774 if (!PromoteType.isNull()) 10775 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 10776 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 10777 << TInfo->getType() 10778 << PromoteType 10779 << TInfo->getTypeLoc().getSourceRange()); 10780 } 10781 10782 QualType T = TInfo->getType().getNonLValueExprType(Context); 10783 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T); 10784 } 10785 10786 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 10787 // The type of __null will be int or long, depending on the size of 10788 // pointers on the target. 10789 QualType Ty; 10790 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 10791 if (pw == Context.getTargetInfo().getIntWidth()) 10792 Ty = Context.IntTy; 10793 else if (pw == Context.getTargetInfo().getLongWidth()) 10794 Ty = Context.LongTy; 10795 else if (pw == Context.getTargetInfo().getLongLongWidth()) 10796 Ty = Context.LongLongTy; 10797 else { 10798 llvm_unreachable("I don't know size of pointer!"); 10799 } 10800 10801 return new (Context) GNUNullExpr(Ty, TokenLoc); 10802 } 10803 10804 bool 10805 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) { 10806 if (!getLangOpts().ObjC1) 10807 return false; 10808 10809 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 10810 if (!PT) 10811 return false; 10812 10813 if (!PT->isObjCIdType()) { 10814 // Check if the destination is the 'NSString' interface. 10815 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 10816 if (!ID || !ID->getIdentifier()->isStr("NSString")) 10817 return false; 10818 } 10819 10820 // Ignore any parens, implicit casts (should only be 10821 // array-to-pointer decays), and not-so-opaque values. The last is 10822 // important for making this trigger for property assignments. 10823 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 10824 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 10825 if (OV->getSourceExpr()) 10826 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 10827 10828 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 10829 if (!SL || !SL->isAscii()) 10830 return false; 10831 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 10832 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 10833 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 10834 return true; 10835 } 10836 10837 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 10838 SourceLocation Loc, 10839 QualType DstType, QualType SrcType, 10840 Expr *SrcExpr, AssignmentAction Action, 10841 bool *Complained) { 10842 if (Complained) 10843 *Complained = false; 10844 10845 // Decode the result (notice that AST's are still created for extensions). 10846 bool CheckInferredResultType = false; 10847 bool isInvalid = false; 10848 unsigned DiagKind = 0; 10849 FixItHint Hint; 10850 ConversionFixItGenerator ConvHints; 10851 bool MayHaveConvFixit = false; 10852 bool MayHaveFunctionDiff = false; 10853 const ObjCInterfaceDecl *IFace = nullptr; 10854 const ObjCProtocolDecl *PDecl = nullptr; 10855 10856 switch (ConvTy) { 10857 case Compatible: 10858 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 10859 return false; 10860 10861 case PointerToInt: 10862 DiagKind = diag::ext_typecheck_convert_pointer_int; 10863 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10864 MayHaveConvFixit = true; 10865 break; 10866 case IntToPointer: 10867 DiagKind = diag::ext_typecheck_convert_int_pointer; 10868 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10869 MayHaveConvFixit = true; 10870 break; 10871 case IncompatiblePointer: 10872 DiagKind = 10873 (Action == AA_Passing_CFAudited ? 10874 diag::err_arc_typecheck_convert_incompatible_pointer : 10875 diag::ext_typecheck_convert_incompatible_pointer); 10876 CheckInferredResultType = DstType->isObjCObjectPointerType() && 10877 SrcType->isObjCObjectPointerType(); 10878 if (Hint.isNull() && !CheckInferredResultType) { 10879 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10880 } 10881 else if (CheckInferredResultType) { 10882 SrcType = SrcType.getUnqualifiedType(); 10883 DstType = DstType.getUnqualifiedType(); 10884 } 10885 MayHaveConvFixit = true; 10886 break; 10887 case IncompatiblePointerSign: 10888 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 10889 break; 10890 case FunctionVoidPointer: 10891 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 10892 break; 10893 case IncompatiblePointerDiscardsQualifiers: { 10894 // Perform array-to-pointer decay if necessary. 10895 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 10896 10897 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 10898 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 10899 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 10900 DiagKind = diag::err_typecheck_incompatible_address_space; 10901 break; 10902 10903 10904 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 10905 DiagKind = diag::err_typecheck_incompatible_ownership; 10906 break; 10907 } 10908 10909 llvm_unreachable("unknown error case for discarding qualifiers!"); 10910 // fallthrough 10911 } 10912 case CompatiblePointerDiscardsQualifiers: 10913 // If the qualifiers lost were because we were applying the 10914 // (deprecated) C++ conversion from a string literal to a char* 10915 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 10916 // Ideally, this check would be performed in 10917 // checkPointerTypesForAssignment. However, that would require a 10918 // bit of refactoring (so that the second argument is an 10919 // expression, rather than a type), which should be done as part 10920 // of a larger effort to fix checkPointerTypesForAssignment for 10921 // C++ semantics. 10922 if (getLangOpts().CPlusPlus && 10923 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 10924 return false; 10925 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 10926 break; 10927 case IncompatibleNestedPointerQualifiers: 10928 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 10929 break; 10930 case IntToBlockPointer: 10931 DiagKind = diag::err_int_to_block_pointer; 10932 break; 10933 case IncompatibleBlockPointer: 10934 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 10935 break; 10936 case IncompatibleObjCQualifiedId: { 10937 if (SrcType->isObjCQualifiedIdType()) { 10938 const ObjCObjectPointerType *srcOPT = 10939 SrcType->getAs<ObjCObjectPointerType>(); 10940 for (auto *srcProto : srcOPT->quals()) { 10941 PDecl = srcProto; 10942 break; 10943 } 10944 if (const ObjCInterfaceType *IFaceT = 10945 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 10946 IFace = IFaceT->getDecl(); 10947 } 10948 else if (DstType->isObjCQualifiedIdType()) { 10949 const ObjCObjectPointerType *dstOPT = 10950 DstType->getAs<ObjCObjectPointerType>(); 10951 for (auto *dstProto : dstOPT->quals()) { 10952 PDecl = dstProto; 10953 break; 10954 } 10955 if (const ObjCInterfaceType *IFaceT = 10956 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 10957 IFace = IFaceT->getDecl(); 10958 } 10959 DiagKind = diag::warn_incompatible_qualified_id; 10960 break; 10961 } 10962 case IncompatibleVectors: 10963 DiagKind = diag::warn_incompatible_vectors; 10964 break; 10965 case IncompatibleObjCWeakRef: 10966 DiagKind = diag::err_arc_weak_unavailable_assign; 10967 break; 10968 case Incompatible: 10969 DiagKind = diag::err_typecheck_convert_incompatible; 10970 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10971 MayHaveConvFixit = true; 10972 isInvalid = true; 10973 MayHaveFunctionDiff = true; 10974 break; 10975 } 10976 10977 QualType FirstType, SecondType; 10978 switch (Action) { 10979 case AA_Assigning: 10980 case AA_Initializing: 10981 // The destination type comes first. 10982 FirstType = DstType; 10983 SecondType = SrcType; 10984 break; 10985 10986 case AA_Returning: 10987 case AA_Passing: 10988 case AA_Passing_CFAudited: 10989 case AA_Converting: 10990 case AA_Sending: 10991 case AA_Casting: 10992 // The source type comes first. 10993 FirstType = SrcType; 10994 SecondType = DstType; 10995 break; 10996 } 10997 10998 PartialDiagnostic FDiag = PDiag(DiagKind); 10999 if (Action == AA_Passing_CFAudited) 11000 FDiag << FirstType << SecondType << SrcExpr->getSourceRange(); 11001 else 11002 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 11003 11004 // If we can fix the conversion, suggest the FixIts. 11005 assert(ConvHints.isNull() || Hint.isNull()); 11006 if (!ConvHints.isNull()) { 11007 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(), 11008 HE = ConvHints.Hints.end(); HI != HE; ++HI) 11009 FDiag << *HI; 11010 } else { 11011 FDiag << Hint; 11012 } 11013 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 11014 11015 if (MayHaveFunctionDiff) 11016 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 11017 11018 Diag(Loc, FDiag); 11019 if (DiagKind == diag::warn_incompatible_qualified_id && 11020 PDecl && IFace && !IFace->hasDefinition()) 11021 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id) 11022 << IFace->getName() << PDecl->getName(); 11023 11024 if (SecondType == Context.OverloadTy) 11025 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 11026 FirstType); 11027 11028 if (CheckInferredResultType) 11029 EmitRelatedResultTypeNote(SrcExpr); 11030 11031 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 11032 EmitRelatedResultTypeNoteForReturn(DstType); 11033 11034 if (Complained) 11035 *Complained = true; 11036 return isInvalid; 11037 } 11038 11039 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 11040 llvm::APSInt *Result) { 11041 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 11042 public: 11043 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 11044 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 11045 } 11046 } Diagnoser; 11047 11048 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 11049 } 11050 11051 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 11052 llvm::APSInt *Result, 11053 unsigned DiagID, 11054 bool AllowFold) { 11055 class IDDiagnoser : public VerifyICEDiagnoser { 11056 unsigned DiagID; 11057 11058 public: 11059 IDDiagnoser(unsigned DiagID) 11060 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 11061 11062 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 11063 S.Diag(Loc, DiagID) << SR; 11064 } 11065 } Diagnoser(DiagID); 11066 11067 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 11068 } 11069 11070 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 11071 SourceRange SR) { 11072 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 11073 } 11074 11075 ExprResult 11076 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 11077 VerifyICEDiagnoser &Diagnoser, 11078 bool AllowFold) { 11079 SourceLocation DiagLoc = E->getLocStart(); 11080 11081 if (getLangOpts().CPlusPlus11) { 11082 // C++11 [expr.const]p5: 11083 // If an expression of literal class type is used in a context where an 11084 // integral constant expression is required, then that class type shall 11085 // have a single non-explicit conversion function to an integral or 11086 // unscoped enumeration type 11087 ExprResult Converted; 11088 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 11089 public: 11090 CXX11ConvertDiagnoser(bool Silent) 11091 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 11092 Silent, true) {} 11093 11094 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 11095 QualType T) override { 11096 return S.Diag(Loc, diag::err_ice_not_integral) << T; 11097 } 11098 11099 SemaDiagnosticBuilder diagnoseIncomplete( 11100 Sema &S, SourceLocation Loc, QualType T) override { 11101 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 11102 } 11103 11104 SemaDiagnosticBuilder diagnoseExplicitConv( 11105 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 11106 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 11107 } 11108 11109 SemaDiagnosticBuilder noteExplicitConv( 11110 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 11111 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 11112 << ConvTy->isEnumeralType() << ConvTy; 11113 } 11114 11115 SemaDiagnosticBuilder diagnoseAmbiguous( 11116 Sema &S, SourceLocation Loc, QualType T) override { 11117 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 11118 } 11119 11120 SemaDiagnosticBuilder noteAmbiguous( 11121 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 11122 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 11123 << ConvTy->isEnumeralType() << ConvTy; 11124 } 11125 11126 SemaDiagnosticBuilder diagnoseConversion( 11127 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 11128 llvm_unreachable("conversion functions are permitted"); 11129 } 11130 } ConvertDiagnoser(Diagnoser.Suppress); 11131 11132 Converted = PerformContextualImplicitConversion(DiagLoc, E, 11133 ConvertDiagnoser); 11134 if (Converted.isInvalid()) 11135 return Converted; 11136 E = Converted.get(); 11137 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 11138 return ExprError(); 11139 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 11140 // An ICE must be of integral or unscoped enumeration type. 11141 if (!Diagnoser.Suppress) 11142 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 11143 return ExprError(); 11144 } 11145 11146 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 11147 // in the non-ICE case. 11148 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 11149 if (Result) 11150 *Result = E->EvaluateKnownConstInt(Context); 11151 return E; 11152 } 11153 11154 Expr::EvalResult EvalResult; 11155 SmallVector<PartialDiagnosticAt, 8> Notes; 11156 EvalResult.Diag = &Notes; 11157 11158 // Try to evaluate the expression, and produce diagnostics explaining why it's 11159 // not a constant expression as a side-effect. 11160 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 11161 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 11162 11163 // In C++11, we can rely on diagnostics being produced for any expression 11164 // which is not a constant expression. If no diagnostics were produced, then 11165 // this is a constant expression. 11166 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 11167 if (Result) 11168 *Result = EvalResult.Val.getInt(); 11169 return E; 11170 } 11171 11172 // If our only note is the usual "invalid subexpression" note, just point 11173 // the caret at its location rather than producing an essentially 11174 // redundant note. 11175 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 11176 diag::note_invalid_subexpr_in_const_expr) { 11177 DiagLoc = Notes[0].first; 11178 Notes.clear(); 11179 } 11180 11181 if (!Folded || !AllowFold) { 11182 if (!Diagnoser.Suppress) { 11183 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 11184 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11185 Diag(Notes[I].first, Notes[I].second); 11186 } 11187 11188 return ExprError(); 11189 } 11190 11191 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 11192 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11193 Diag(Notes[I].first, Notes[I].second); 11194 11195 if (Result) 11196 *Result = EvalResult.Val.getInt(); 11197 return E; 11198 } 11199 11200 namespace { 11201 // Handle the case where we conclude a expression which we speculatively 11202 // considered to be unevaluated is actually evaluated. 11203 class TransformToPE : public TreeTransform<TransformToPE> { 11204 typedef TreeTransform<TransformToPE> BaseTransform; 11205 11206 public: 11207 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 11208 11209 // Make sure we redo semantic analysis 11210 bool AlwaysRebuild() { return true; } 11211 11212 // Make sure we handle LabelStmts correctly. 11213 // FIXME: This does the right thing, but maybe we need a more general 11214 // fix to TreeTransform? 11215 StmtResult TransformLabelStmt(LabelStmt *S) { 11216 S->getDecl()->setStmt(nullptr); 11217 return BaseTransform::TransformLabelStmt(S); 11218 } 11219 11220 // We need to special-case DeclRefExprs referring to FieldDecls which 11221 // are not part of a member pointer formation; normal TreeTransforming 11222 // doesn't catch this case because of the way we represent them in the AST. 11223 // FIXME: This is a bit ugly; is it really the best way to handle this 11224 // case? 11225 // 11226 // Error on DeclRefExprs referring to FieldDecls. 11227 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 11228 if (isa<FieldDecl>(E->getDecl()) && 11229 !SemaRef.isUnevaluatedContext()) 11230 return SemaRef.Diag(E->getLocation(), 11231 diag::err_invalid_non_static_member_use) 11232 << E->getDecl() << E->getSourceRange(); 11233 11234 return BaseTransform::TransformDeclRefExpr(E); 11235 } 11236 11237 // Exception: filter out member pointer formation 11238 ExprResult TransformUnaryOperator(UnaryOperator *E) { 11239 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 11240 return E; 11241 11242 return BaseTransform::TransformUnaryOperator(E); 11243 } 11244 11245 ExprResult TransformLambdaExpr(LambdaExpr *E) { 11246 // Lambdas never need to be transformed. 11247 return E; 11248 } 11249 }; 11250 } 11251 11252 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 11253 assert(isUnevaluatedContext() && 11254 "Should only transform unevaluated expressions"); 11255 ExprEvalContexts.back().Context = 11256 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 11257 if (isUnevaluatedContext()) 11258 return E; 11259 return TransformToPE(*this).TransformExpr(E); 11260 } 11261 11262 void 11263 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 11264 Decl *LambdaContextDecl, 11265 bool IsDecltype) { 11266 ExprEvalContexts.push_back( 11267 ExpressionEvaluationContextRecord(NewContext, 11268 ExprCleanupObjects.size(), 11269 ExprNeedsCleanups, 11270 LambdaContextDecl, 11271 IsDecltype)); 11272 ExprNeedsCleanups = false; 11273 if (!MaybeODRUseExprs.empty()) 11274 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 11275 } 11276 11277 void 11278 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 11279 ReuseLambdaContextDecl_t, 11280 bool IsDecltype) { 11281 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 11282 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 11283 } 11284 11285 void Sema::PopExpressionEvaluationContext() { 11286 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 11287 11288 if (!Rec.Lambdas.empty()) { 11289 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 11290 unsigned D; 11291 if (Rec.isUnevaluated()) { 11292 // C++11 [expr.prim.lambda]p2: 11293 // A lambda-expression shall not appear in an unevaluated operand 11294 // (Clause 5). 11295 D = diag::err_lambda_unevaluated_operand; 11296 } else { 11297 // C++1y [expr.const]p2: 11298 // A conditional-expression e is a core constant expression unless the 11299 // evaluation of e, following the rules of the abstract machine, would 11300 // evaluate [...] a lambda-expression. 11301 D = diag::err_lambda_in_constant_expression; 11302 } 11303 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) 11304 Diag(Rec.Lambdas[I]->getLocStart(), D); 11305 } else { 11306 // Mark the capture expressions odr-used. This was deferred 11307 // during lambda expression creation. 11308 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) { 11309 LambdaExpr *Lambda = Rec.Lambdas[I]; 11310 for (LambdaExpr::capture_init_iterator 11311 C = Lambda->capture_init_begin(), 11312 CEnd = Lambda->capture_init_end(); 11313 C != CEnd; ++C) { 11314 MarkDeclarationsReferencedInExpr(*C); 11315 } 11316 } 11317 } 11318 } 11319 11320 // When are coming out of an unevaluated context, clear out any 11321 // temporaries that we may have created as part of the evaluation of 11322 // the expression in that context: they aren't relevant because they 11323 // will never be constructed. 11324 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 11325 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 11326 ExprCleanupObjects.end()); 11327 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 11328 CleanupVarDeclMarking(); 11329 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 11330 // Otherwise, merge the contexts together. 11331 } else { 11332 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 11333 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 11334 Rec.SavedMaybeODRUseExprs.end()); 11335 } 11336 11337 // Pop the current expression evaluation context off the stack. 11338 ExprEvalContexts.pop_back(); 11339 } 11340 11341 void Sema::DiscardCleanupsInEvaluationContext() { 11342 ExprCleanupObjects.erase( 11343 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 11344 ExprCleanupObjects.end()); 11345 ExprNeedsCleanups = false; 11346 MaybeODRUseExprs.clear(); 11347 } 11348 11349 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 11350 if (!E->getType()->isVariablyModifiedType()) 11351 return E; 11352 return TransformToPotentiallyEvaluated(E); 11353 } 11354 11355 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 11356 // Do not mark anything as "used" within a dependent context; wait for 11357 // an instantiation. 11358 if (SemaRef.CurContext->isDependentContext()) 11359 return false; 11360 11361 switch (SemaRef.ExprEvalContexts.back().Context) { 11362 case Sema::Unevaluated: 11363 case Sema::UnevaluatedAbstract: 11364 // We are in an expression that is not potentially evaluated; do nothing. 11365 // (Depending on how you read the standard, we actually do need to do 11366 // something here for null pointer constants, but the standard's 11367 // definition of a null pointer constant is completely crazy.) 11368 return false; 11369 11370 case Sema::ConstantEvaluated: 11371 case Sema::PotentiallyEvaluated: 11372 // We are in a potentially evaluated expression (or a constant-expression 11373 // in C++03); we need to do implicit template instantiation, implicitly 11374 // define class members, and mark most declarations as used. 11375 return true; 11376 11377 case Sema::PotentiallyEvaluatedIfUsed: 11378 // Referenced declarations will only be used if the construct in the 11379 // containing expression is used. 11380 return false; 11381 } 11382 llvm_unreachable("Invalid context"); 11383 } 11384 11385 /// \brief Mark a function referenced, and check whether it is odr-used 11386 /// (C++ [basic.def.odr]p2, C99 6.9p3) 11387 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) { 11388 assert(Func && "No function?"); 11389 11390 Func->setReferenced(); 11391 11392 // C++11 [basic.def.odr]p3: 11393 // A function whose name appears as a potentially-evaluated expression is 11394 // odr-used if it is the unique lookup result or the selected member of a 11395 // set of overloaded functions [...]. 11396 // 11397 // We (incorrectly) mark overload resolution as an unevaluated context, so we 11398 // can just check that here. Skip the rest of this function if we've already 11399 // marked the function as used. 11400 if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) { 11401 // C++11 [temp.inst]p3: 11402 // Unless a function template specialization has been explicitly 11403 // instantiated or explicitly specialized, the function template 11404 // specialization is implicitly instantiated when the specialization is 11405 // referenced in a context that requires a function definition to exist. 11406 // 11407 // We consider constexpr function templates to be referenced in a context 11408 // that requires a definition to exist whenever they are referenced. 11409 // 11410 // FIXME: This instantiates constexpr functions too frequently. If this is 11411 // really an unevaluated context (and we're not just in the definition of a 11412 // function template or overload resolution or other cases which we 11413 // incorrectly consider to be unevaluated contexts), and we're not in a 11414 // subexpression which we actually need to evaluate (for instance, a 11415 // template argument, array bound or an expression in a braced-init-list), 11416 // we are not permitted to instantiate this constexpr function definition. 11417 // 11418 // FIXME: This also implicitly defines special members too frequently. They 11419 // are only supposed to be implicitly defined if they are odr-used, but they 11420 // are not odr-used from constant expressions in unevaluated contexts. 11421 // However, they cannot be referenced if they are deleted, and they are 11422 // deleted whenever the implicit definition of the special member would 11423 // fail. 11424 if (!Func->isConstexpr() || Func->getBody()) 11425 return; 11426 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 11427 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 11428 return; 11429 } 11430 11431 // Note that this declaration has been used. 11432 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 11433 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 11434 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 11435 if (Constructor->isDefaultConstructor()) { 11436 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 11437 return; 11438 DefineImplicitDefaultConstructor(Loc, Constructor); 11439 } else if (Constructor->isCopyConstructor()) { 11440 DefineImplicitCopyConstructor(Loc, Constructor); 11441 } else if (Constructor->isMoveConstructor()) { 11442 DefineImplicitMoveConstructor(Loc, Constructor); 11443 } 11444 } else if (Constructor->getInheritedConstructor()) { 11445 DefineInheritingConstructor(Loc, Constructor); 11446 } 11447 11448 MarkVTableUsed(Loc, Constructor->getParent()); 11449 } else if (CXXDestructorDecl *Destructor = 11450 dyn_cast<CXXDestructorDecl>(Func)) { 11451 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 11452 if (Destructor->isDefaulted() && !Destructor->isDeleted()) 11453 DefineImplicitDestructor(Loc, Destructor); 11454 if (Destructor->isVirtual()) 11455 MarkVTableUsed(Loc, Destructor->getParent()); 11456 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 11457 if (MethodDecl->isOverloadedOperator() && 11458 MethodDecl->getOverloadedOperator() == OO_Equal) { 11459 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 11460 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 11461 if (MethodDecl->isCopyAssignmentOperator()) 11462 DefineImplicitCopyAssignment(Loc, MethodDecl); 11463 else 11464 DefineImplicitMoveAssignment(Loc, MethodDecl); 11465 } 11466 } else if (isa<CXXConversionDecl>(MethodDecl) && 11467 MethodDecl->getParent()->isLambda()) { 11468 CXXConversionDecl *Conversion = 11469 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 11470 if (Conversion->isLambdaToBlockPointerConversion()) 11471 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 11472 else 11473 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 11474 } else if (MethodDecl->isVirtual()) 11475 MarkVTableUsed(Loc, MethodDecl->getParent()); 11476 } 11477 11478 // Recursive functions should be marked when used from another function. 11479 // FIXME: Is this really right? 11480 if (CurContext == Func) return; 11481 11482 // Resolve the exception specification for any function which is 11483 // used: CodeGen will need it. 11484 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 11485 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 11486 ResolveExceptionSpec(Loc, FPT); 11487 11488 // Implicit instantiation of function templates and member functions of 11489 // class templates. 11490 if (Func->isImplicitlyInstantiable()) { 11491 bool AlreadyInstantiated = false; 11492 SourceLocation PointOfInstantiation = Loc; 11493 if (FunctionTemplateSpecializationInfo *SpecInfo 11494 = Func->getTemplateSpecializationInfo()) { 11495 if (SpecInfo->getPointOfInstantiation().isInvalid()) 11496 SpecInfo->setPointOfInstantiation(Loc); 11497 else if (SpecInfo->getTemplateSpecializationKind() 11498 == TSK_ImplicitInstantiation) { 11499 AlreadyInstantiated = true; 11500 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 11501 } 11502 } else if (MemberSpecializationInfo *MSInfo 11503 = Func->getMemberSpecializationInfo()) { 11504 if (MSInfo->getPointOfInstantiation().isInvalid()) 11505 MSInfo->setPointOfInstantiation(Loc); 11506 else if (MSInfo->getTemplateSpecializationKind() 11507 == TSK_ImplicitInstantiation) { 11508 AlreadyInstantiated = true; 11509 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 11510 } 11511 } 11512 11513 if (!AlreadyInstantiated || Func->isConstexpr()) { 11514 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 11515 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 11516 ActiveTemplateInstantiations.size()) 11517 PendingLocalImplicitInstantiations.push_back( 11518 std::make_pair(Func, PointOfInstantiation)); 11519 else if (Func->isConstexpr()) 11520 // Do not defer instantiations of constexpr functions, to avoid the 11521 // expression evaluator needing to call back into Sema if it sees a 11522 // call to such a function. 11523 InstantiateFunctionDefinition(PointOfInstantiation, Func); 11524 else { 11525 PendingInstantiations.push_back(std::make_pair(Func, 11526 PointOfInstantiation)); 11527 // Notify the consumer that a function was implicitly instantiated. 11528 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 11529 } 11530 } 11531 } else { 11532 // Walk redefinitions, as some of them may be instantiable. 11533 for (auto i : Func->redecls()) { 11534 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 11535 MarkFunctionReferenced(Loc, i); 11536 } 11537 } 11538 11539 // Keep track of used but undefined functions. 11540 if (!Func->isDefined()) { 11541 if (mightHaveNonExternalLinkage(Func)) 11542 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 11543 else if (Func->getMostRecentDecl()->isInlined() && 11544 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 11545 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 11546 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 11547 } 11548 11549 // Normally the most current decl is marked used while processing the use and 11550 // any subsequent decls are marked used by decl merging. This fails with 11551 // template instantiation since marking can happen at the end of the file 11552 // and, because of the two phase lookup, this function is called with at 11553 // decl in the middle of a decl chain. We loop to maintain the invariant 11554 // that once a decl is used, all decls after it are also used. 11555 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) { 11556 F->markUsed(Context); 11557 if (F == Func) 11558 break; 11559 } 11560 } 11561 11562 static void 11563 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 11564 VarDecl *var, DeclContext *DC) { 11565 DeclContext *VarDC = var->getDeclContext(); 11566 11567 // If the parameter still belongs to the translation unit, then 11568 // we're actually just using one parameter in the declaration of 11569 // the next. 11570 if (isa<ParmVarDecl>(var) && 11571 isa<TranslationUnitDecl>(VarDC)) 11572 return; 11573 11574 // For C code, don't diagnose about capture if we're not actually in code 11575 // right now; it's impossible to write a non-constant expression outside of 11576 // function context, so we'll get other (more useful) diagnostics later. 11577 // 11578 // For C++, things get a bit more nasty... it would be nice to suppress this 11579 // diagnostic for certain cases like using a local variable in an array bound 11580 // for a member of a local class, but the correct predicate is not obvious. 11581 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 11582 return; 11583 11584 if (isa<CXXMethodDecl>(VarDC) && 11585 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 11586 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 11587 << var->getIdentifier(); 11588 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 11589 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 11590 << var->getIdentifier() << fn->getDeclName(); 11591 } else if (isa<BlockDecl>(VarDC)) { 11592 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 11593 << var->getIdentifier(); 11594 } else { 11595 // FIXME: Is there any other context where a local variable can be 11596 // declared? 11597 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 11598 << var->getIdentifier(); 11599 } 11600 11601 S.Diag(var->getLocation(), diag::note_entity_declared_at) 11602 << var->getIdentifier(); 11603 11604 // FIXME: Add additional diagnostic info about class etc. which prevents 11605 // capture. 11606 } 11607 11608 11609 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 11610 bool &SubCapturesAreNested, 11611 QualType &CaptureType, 11612 QualType &DeclRefType) { 11613 // Check whether we've already captured it. 11614 if (CSI->CaptureMap.count(Var)) { 11615 // If we found a capture, any subcaptures are nested. 11616 SubCapturesAreNested = true; 11617 11618 // Retrieve the capture type for this variable. 11619 CaptureType = CSI->getCapture(Var).getCaptureType(); 11620 11621 // Compute the type of an expression that refers to this variable. 11622 DeclRefType = CaptureType.getNonReferenceType(); 11623 11624 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 11625 if (Cap.isCopyCapture() && 11626 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable)) 11627 DeclRefType.addConst(); 11628 return true; 11629 } 11630 return false; 11631 } 11632 11633 // Only block literals, captured statements, and lambda expressions can 11634 // capture; other scopes don't work. 11635 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 11636 SourceLocation Loc, 11637 const bool Diagnose, Sema &S) { 11638 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 11639 return getLambdaAwareParentOfDeclContext(DC); 11640 else { 11641 if (Diagnose) 11642 diagnoseUncapturableValueReference(S, Loc, Var, DC); 11643 } 11644 return nullptr; 11645 } 11646 11647 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 11648 // certain types of variables (unnamed, variably modified types etc.) 11649 // so check for eligibility. 11650 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 11651 SourceLocation Loc, 11652 const bool Diagnose, Sema &S) { 11653 11654 bool IsBlock = isa<BlockScopeInfo>(CSI); 11655 bool IsLambda = isa<LambdaScopeInfo>(CSI); 11656 11657 // Lambdas are not allowed to capture unnamed variables 11658 // (e.g. anonymous unions). 11659 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 11660 // assuming that's the intent. 11661 if (IsLambda && !Var->getDeclName()) { 11662 if (Diagnose) { 11663 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 11664 S.Diag(Var->getLocation(), diag::note_declared_at); 11665 } 11666 return false; 11667 } 11668 11669 // Prohibit variably-modified types; they're difficult to deal with. 11670 if (Var->getType()->isVariablyModifiedType()) { 11671 if (Diagnose) { 11672 if (IsBlock) 11673 S.Diag(Loc, diag::err_ref_vm_type); 11674 else 11675 S.Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName(); 11676 S.Diag(Var->getLocation(), diag::note_previous_decl) 11677 << Var->getDeclName(); 11678 } 11679 return false; 11680 } 11681 // Prohibit structs with flexible array members too. 11682 // We cannot capture what is in the tail end of the struct. 11683 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 11684 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 11685 if (Diagnose) { 11686 if (IsBlock) 11687 S.Diag(Loc, diag::err_ref_flexarray_type); 11688 else 11689 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 11690 << Var->getDeclName(); 11691 S.Diag(Var->getLocation(), diag::note_previous_decl) 11692 << Var->getDeclName(); 11693 } 11694 return false; 11695 } 11696 } 11697 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 11698 // Lambdas and captured statements are not allowed to capture __block 11699 // variables; they don't support the expected semantics. 11700 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 11701 if (Diagnose) { 11702 S.Diag(Loc, diag::err_capture_block_variable) 11703 << Var->getDeclName() << !IsLambda; 11704 S.Diag(Var->getLocation(), diag::note_previous_decl) 11705 << Var->getDeclName(); 11706 } 11707 return false; 11708 } 11709 11710 return true; 11711 } 11712 11713 // Returns true if the capture by block was successful. 11714 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 11715 SourceLocation Loc, 11716 const bool BuildAndDiagnose, 11717 QualType &CaptureType, 11718 QualType &DeclRefType, 11719 const bool Nested, 11720 Sema &S) { 11721 Expr *CopyExpr = nullptr; 11722 bool ByRef = false; 11723 11724 // Blocks are not allowed to capture arrays. 11725 if (CaptureType->isArrayType()) { 11726 if (BuildAndDiagnose) { 11727 S.Diag(Loc, diag::err_ref_array_type); 11728 S.Diag(Var->getLocation(), diag::note_previous_decl) 11729 << Var->getDeclName(); 11730 } 11731 return false; 11732 } 11733 11734 // Forbid the block-capture of autoreleasing variables. 11735 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11736 if (BuildAndDiagnose) { 11737 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 11738 << /*block*/ 0; 11739 S.Diag(Var->getLocation(), diag::note_previous_decl) 11740 << Var->getDeclName(); 11741 } 11742 return false; 11743 } 11744 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 11745 if (HasBlocksAttr || CaptureType->isReferenceType()) { 11746 // Block capture by reference does not change the capture or 11747 // declaration reference types. 11748 ByRef = true; 11749 } else { 11750 // Block capture by copy introduces 'const'. 11751 CaptureType = CaptureType.getNonReferenceType().withConst(); 11752 DeclRefType = CaptureType; 11753 11754 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 11755 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 11756 // The capture logic needs the destructor, so make sure we mark it. 11757 // Usually this is unnecessary because most local variables have 11758 // their destructors marked at declaration time, but parameters are 11759 // an exception because it's technically only the call site that 11760 // actually requires the destructor. 11761 if (isa<ParmVarDecl>(Var)) 11762 S.FinalizeVarWithDestructor(Var, Record); 11763 11764 // Enter a new evaluation context to insulate the copy 11765 // full-expression. 11766 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 11767 11768 // According to the blocks spec, the capture of a variable from 11769 // the stack requires a const copy constructor. This is not true 11770 // of the copy/move done to move a __block variable to the heap. 11771 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 11772 DeclRefType.withConst(), 11773 VK_LValue, Loc); 11774 11775 ExprResult Result 11776 = S.PerformCopyInitialization( 11777 InitializedEntity::InitializeBlock(Var->getLocation(), 11778 CaptureType, false), 11779 Loc, DeclRef); 11780 11781 // Build a full-expression copy expression if initialization 11782 // succeeded and used a non-trivial constructor. Recover from 11783 // errors by pretending that the copy isn't necessary. 11784 if (!Result.isInvalid() && 11785 !cast<CXXConstructExpr>(Result.get())->getConstructor() 11786 ->isTrivial()) { 11787 Result = S.MaybeCreateExprWithCleanups(Result); 11788 CopyExpr = Result.get(); 11789 } 11790 } 11791 } 11792 } 11793 11794 // Actually capture the variable. 11795 if (BuildAndDiagnose) 11796 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 11797 SourceLocation(), CaptureType, CopyExpr); 11798 11799 return true; 11800 11801 } 11802 11803 11804 /// \brief Capture the given variable in the captured region. 11805 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 11806 VarDecl *Var, 11807 SourceLocation Loc, 11808 const bool BuildAndDiagnose, 11809 QualType &CaptureType, 11810 QualType &DeclRefType, 11811 const bool RefersToEnclosingLocal, 11812 Sema &S) { 11813 11814 // By default, capture variables by reference. 11815 bool ByRef = true; 11816 // Using an LValue reference type is consistent with Lambdas (see below). 11817 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 11818 Expr *CopyExpr = nullptr; 11819 if (BuildAndDiagnose) { 11820 // The current implementation assumes that all variables are captured 11821 // by references. Since there is no capture by copy, no expression 11822 // evaluation will be needed. 11823 RecordDecl *RD = RSI->TheRecordDecl; 11824 11825 FieldDecl *Field 11826 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 11827 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 11828 nullptr, false, ICIS_NoInit); 11829 Field->setImplicit(true); 11830 Field->setAccess(AS_private); 11831 RD->addDecl(Field); 11832 11833 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 11834 DeclRefType, VK_LValue, Loc); 11835 Var->setReferenced(true); 11836 Var->markUsed(S.Context); 11837 } 11838 11839 // Actually capture the variable. 11840 if (BuildAndDiagnose) 11841 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc, 11842 SourceLocation(), CaptureType, CopyExpr); 11843 11844 11845 return true; 11846 } 11847 11848 /// \brief Create a field within the lambda class for the variable 11849 /// being captured. Handle Array captures. 11850 static ExprResult addAsFieldToClosureType(Sema &S, 11851 LambdaScopeInfo *LSI, 11852 VarDecl *Var, QualType FieldType, 11853 QualType DeclRefType, 11854 SourceLocation Loc, 11855 bool RefersToEnclosingLocal) { 11856 CXXRecordDecl *Lambda = LSI->Lambda; 11857 11858 // Build the non-static data member. 11859 FieldDecl *Field 11860 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 11861 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 11862 nullptr, false, ICIS_NoInit); 11863 Field->setImplicit(true); 11864 Field->setAccess(AS_private); 11865 Lambda->addDecl(Field); 11866 11867 // C++11 [expr.prim.lambda]p21: 11868 // When the lambda-expression is evaluated, the entities that 11869 // are captured by copy are used to direct-initialize each 11870 // corresponding non-static data member of the resulting closure 11871 // object. (For array members, the array elements are 11872 // direct-initialized in increasing subscript order.) These 11873 // initializations are performed in the (unspecified) order in 11874 // which the non-static data members are declared. 11875 11876 // Introduce a new evaluation context for the initialization, so 11877 // that temporaries introduced as part of the capture are retained 11878 // to be re-"exported" from the lambda expression itself. 11879 EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated); 11880 11881 // C++ [expr.prim.labda]p12: 11882 // An entity captured by a lambda-expression is odr-used (3.2) in 11883 // the scope containing the lambda-expression. 11884 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 11885 DeclRefType, VK_LValue, Loc); 11886 Var->setReferenced(true); 11887 Var->markUsed(S.Context); 11888 11889 // When the field has array type, create index variables for each 11890 // dimension of the array. We use these index variables to subscript 11891 // the source array, and other clients (e.g., CodeGen) will perform 11892 // the necessary iteration with these index variables. 11893 SmallVector<VarDecl *, 4> IndexVariables; 11894 QualType BaseType = FieldType; 11895 QualType SizeType = S.Context.getSizeType(); 11896 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size()); 11897 while (const ConstantArrayType *Array 11898 = S.Context.getAsConstantArrayType(BaseType)) { 11899 // Create the iteration variable for this array index. 11900 IdentifierInfo *IterationVarName = nullptr; 11901 { 11902 SmallString<8> Str; 11903 llvm::raw_svector_ostream OS(Str); 11904 OS << "__i" << IndexVariables.size(); 11905 IterationVarName = &S.Context.Idents.get(OS.str()); 11906 } 11907 VarDecl *IterationVar 11908 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11909 IterationVarName, SizeType, 11910 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11911 SC_None); 11912 IndexVariables.push_back(IterationVar); 11913 LSI->ArrayIndexVars.push_back(IterationVar); 11914 11915 // Create a reference to the iteration variable. 11916 ExprResult IterationVarRef 11917 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 11918 assert(!IterationVarRef.isInvalid() && 11919 "Reference to invented variable cannot fail!"); 11920 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.get()); 11921 assert(!IterationVarRef.isInvalid() && 11922 "Conversion of invented variable cannot fail!"); 11923 11924 // Subscript the array with this iteration variable. 11925 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr( 11926 Ref, Loc, IterationVarRef.get(), Loc); 11927 if (Subscript.isInvalid()) { 11928 S.CleanupVarDeclMarking(); 11929 S.DiscardCleanupsInEvaluationContext(); 11930 return ExprError(); 11931 } 11932 11933 Ref = Subscript.get(); 11934 BaseType = Array->getElementType(); 11935 } 11936 11937 // Construct the entity that we will be initializing. For an array, this 11938 // will be first element in the array, which may require several levels 11939 // of array-subscript entities. 11940 SmallVector<InitializedEntity, 4> Entities; 11941 Entities.reserve(1 + IndexVariables.size()); 11942 Entities.push_back( 11943 InitializedEntity::InitializeLambdaCapture(Var->getIdentifier(), 11944 Field->getType(), Loc)); 11945 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 11946 Entities.push_back(InitializedEntity::InitializeElement(S.Context, 11947 0, 11948 Entities.back())); 11949 11950 InitializationKind InitKind 11951 = InitializationKind::CreateDirect(Loc, Loc, Loc); 11952 InitializationSequence Init(S, Entities.back(), InitKind, Ref); 11953 ExprResult Result(true); 11954 if (!Init.Diagnose(S, Entities.back(), InitKind, Ref)) 11955 Result = Init.Perform(S, Entities.back(), InitKind, Ref); 11956 11957 // If this initialization requires any cleanups (e.g., due to a 11958 // default argument to a copy constructor), note that for the 11959 // lambda. 11960 if (S.ExprNeedsCleanups) 11961 LSI->ExprNeedsCleanups = true; 11962 11963 // Exit the expression evaluation context used for the capture. 11964 S.CleanupVarDeclMarking(); 11965 S.DiscardCleanupsInEvaluationContext(); 11966 return Result; 11967 } 11968 11969 11970 11971 /// \brief Capture the given variable in the lambda. 11972 static bool captureInLambda(LambdaScopeInfo *LSI, 11973 VarDecl *Var, 11974 SourceLocation Loc, 11975 const bool BuildAndDiagnose, 11976 QualType &CaptureType, 11977 QualType &DeclRefType, 11978 const bool RefersToEnclosingLocal, 11979 const Sema::TryCaptureKind Kind, 11980 SourceLocation EllipsisLoc, 11981 const bool IsTopScope, 11982 Sema &S) { 11983 11984 // Determine whether we are capturing by reference or by value. 11985 bool ByRef = false; 11986 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 11987 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 11988 } else { 11989 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 11990 } 11991 11992 // Compute the type of the field that will capture this variable. 11993 if (ByRef) { 11994 // C++11 [expr.prim.lambda]p15: 11995 // An entity is captured by reference if it is implicitly or 11996 // explicitly captured but not captured by copy. It is 11997 // unspecified whether additional unnamed non-static data 11998 // members are declared in the closure type for entities 11999 // captured by reference. 12000 // 12001 // FIXME: It is not clear whether we want to build an lvalue reference 12002 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 12003 // to do the former, while EDG does the latter. Core issue 1249 will 12004 // clarify, but for now we follow GCC because it's a more permissive and 12005 // easily defensible position. 12006 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 12007 } else { 12008 // C++11 [expr.prim.lambda]p14: 12009 // For each entity captured by copy, an unnamed non-static 12010 // data member is declared in the closure type. The 12011 // declaration order of these members is unspecified. The type 12012 // of such a data member is the type of the corresponding 12013 // captured entity if the entity is not a reference to an 12014 // object, or the referenced type otherwise. [Note: If the 12015 // captured entity is a reference to a function, the 12016 // corresponding data member is also a reference to a 12017 // function. - end note ] 12018 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 12019 if (!RefType->getPointeeType()->isFunctionType()) 12020 CaptureType = RefType->getPointeeType(); 12021 } 12022 12023 // Forbid the lambda copy-capture of autoreleasing variables. 12024 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 12025 if (BuildAndDiagnose) { 12026 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 12027 S.Diag(Var->getLocation(), diag::note_previous_decl) 12028 << Var->getDeclName(); 12029 } 12030 return false; 12031 } 12032 12033 // Make sure that by-copy captures are of a complete and non-abstract type. 12034 if (BuildAndDiagnose) { 12035 if (!CaptureType->isDependentType() && 12036 S.RequireCompleteType(Loc, CaptureType, 12037 diag::err_capture_of_incomplete_type, 12038 Var->getDeclName())) 12039 return false; 12040 12041 if (S.RequireNonAbstractType(Loc, CaptureType, 12042 diag::err_capture_of_abstract_type)) 12043 return false; 12044 } 12045 } 12046 12047 // Capture this variable in the lambda. 12048 Expr *CopyExpr = nullptr; 12049 if (BuildAndDiagnose) { 12050 ExprResult Result = addAsFieldToClosureType(S, LSI, Var, 12051 CaptureType, DeclRefType, Loc, 12052 RefersToEnclosingLocal); 12053 if (!Result.isInvalid()) 12054 CopyExpr = Result.get(); 12055 } 12056 12057 // Compute the type of a reference to this captured variable. 12058 if (ByRef) 12059 DeclRefType = CaptureType.getNonReferenceType(); 12060 else { 12061 // C++ [expr.prim.lambda]p5: 12062 // The closure type for a lambda-expression has a public inline 12063 // function call operator [...]. This function call operator is 12064 // declared const (9.3.1) if and only if the lambda-expression’s 12065 // parameter-declaration-clause is not followed by mutable. 12066 DeclRefType = CaptureType.getNonReferenceType(); 12067 if (!LSI->Mutable && !CaptureType->isReferenceType()) 12068 DeclRefType.addConst(); 12069 } 12070 12071 // Add the capture. 12072 if (BuildAndDiagnose) 12073 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal, 12074 Loc, EllipsisLoc, CaptureType, CopyExpr); 12075 12076 return true; 12077 } 12078 12079 12080 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc, 12081 TryCaptureKind Kind, SourceLocation EllipsisLoc, 12082 bool BuildAndDiagnose, 12083 QualType &CaptureType, 12084 QualType &DeclRefType, 12085 const unsigned *const FunctionScopeIndexToStopAt) { 12086 bool Nested = false; 12087 12088 DeclContext *DC = CurContext; 12089 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 12090 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 12091 // We need to sync up the Declaration Context with the 12092 // FunctionScopeIndexToStopAt 12093 if (FunctionScopeIndexToStopAt) { 12094 unsigned FSIndex = FunctionScopes.size() - 1; 12095 while (FSIndex != MaxFunctionScopesIndex) { 12096 DC = getLambdaAwareParentOfDeclContext(DC); 12097 --FSIndex; 12098 } 12099 } 12100 12101 12102 // If the variable is declared in the current context (and is not an 12103 // init-capture), there is no need to capture it. 12104 if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true; 12105 if (!Var->hasLocalStorage()) return true; 12106 12107 // Walk up the stack to determine whether we can capture the variable, 12108 // performing the "simple" checks that don't depend on type. We stop when 12109 // we've either hit the declared scope of the variable or find an existing 12110 // capture of that variable. We start from the innermost capturing-entity 12111 // (the DC) and ensure that all intervening capturing-entities 12112 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 12113 // declcontext can either capture the variable or have already captured 12114 // the variable. 12115 CaptureType = Var->getType(); 12116 DeclRefType = CaptureType.getNonReferenceType(); 12117 bool Explicit = (Kind != TryCapture_Implicit); 12118 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 12119 do { 12120 // Only block literals, captured statements, and lambda expressions can 12121 // capture; other scopes don't work. 12122 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 12123 ExprLoc, 12124 BuildAndDiagnose, 12125 *this); 12126 if (!ParentDC) return true; 12127 12128 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 12129 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 12130 12131 12132 // Check whether we've already captured it. 12133 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 12134 DeclRefType)) 12135 break; 12136 // If we are instantiating a generic lambda call operator body, 12137 // we do not want to capture new variables. What was captured 12138 // during either a lambdas transformation or initial parsing 12139 // should be used. 12140 if (isGenericLambdaCallOperatorSpecialization(DC)) { 12141 if (BuildAndDiagnose) { 12142 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 12143 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 12144 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 12145 Diag(Var->getLocation(), diag::note_previous_decl) 12146 << Var->getDeclName(); 12147 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 12148 } else 12149 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 12150 } 12151 return true; 12152 } 12153 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 12154 // certain types of variables (unnamed, variably modified types etc.) 12155 // so check for eligibility. 12156 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 12157 return true; 12158 12159 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 12160 // No capture-default, and this is not an explicit capture 12161 // so cannot capture this variable. 12162 if (BuildAndDiagnose) { 12163 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 12164 Diag(Var->getLocation(), diag::note_previous_decl) 12165 << Var->getDeclName(); 12166 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 12167 diag::note_lambda_decl); 12168 // FIXME: If we error out because an outer lambda can not implicitly 12169 // capture a variable that an inner lambda explicitly captures, we 12170 // should have the inner lambda do the explicit capture - because 12171 // it makes for cleaner diagnostics later. This would purely be done 12172 // so that the diagnostic does not misleadingly claim that a variable 12173 // can not be captured by a lambda implicitly even though it is captured 12174 // explicitly. Suggestion: 12175 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 12176 // at the function head 12177 // - cache the StartingDeclContext - this must be a lambda 12178 // - captureInLambda in the innermost lambda the variable. 12179 } 12180 return true; 12181 } 12182 12183 FunctionScopesIndex--; 12184 DC = ParentDC; 12185 Explicit = false; 12186 } while (!Var->getDeclContext()->Equals(DC)); 12187 12188 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 12189 // computing the type of the capture at each step, checking type-specific 12190 // requirements, and adding captures if requested. 12191 // If the variable had already been captured previously, we start capturing 12192 // at the lambda nested within that one. 12193 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 12194 ++I) { 12195 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 12196 12197 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 12198 if (!captureInBlock(BSI, Var, ExprLoc, 12199 BuildAndDiagnose, CaptureType, 12200 DeclRefType, Nested, *this)) 12201 return true; 12202 Nested = true; 12203 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 12204 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 12205 BuildAndDiagnose, CaptureType, 12206 DeclRefType, Nested, *this)) 12207 return true; 12208 Nested = true; 12209 } else { 12210 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 12211 if (!captureInLambda(LSI, Var, ExprLoc, 12212 BuildAndDiagnose, CaptureType, 12213 DeclRefType, Nested, Kind, EllipsisLoc, 12214 /*IsTopScope*/I == N - 1, *this)) 12215 return true; 12216 Nested = true; 12217 } 12218 } 12219 return false; 12220 } 12221 12222 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 12223 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 12224 QualType CaptureType; 12225 QualType DeclRefType; 12226 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 12227 /*BuildAndDiagnose=*/true, CaptureType, 12228 DeclRefType, nullptr); 12229 } 12230 12231 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 12232 QualType CaptureType; 12233 QualType DeclRefType; 12234 12235 // Determine whether we can capture this variable. 12236 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 12237 /*BuildAndDiagnose=*/false, CaptureType, 12238 DeclRefType, nullptr)) 12239 return QualType(); 12240 12241 return DeclRefType; 12242 } 12243 12244 12245 12246 // If either the type of the variable or the initializer is dependent, 12247 // return false. Otherwise, determine whether the variable is a constant 12248 // expression. Use this if you need to know if a variable that might or 12249 // might not be dependent is truly a constant expression. 12250 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 12251 ASTContext &Context) { 12252 12253 if (Var->getType()->isDependentType()) 12254 return false; 12255 const VarDecl *DefVD = nullptr; 12256 Var->getAnyInitializer(DefVD); 12257 if (!DefVD) 12258 return false; 12259 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 12260 Expr *Init = cast<Expr>(Eval->Value); 12261 if (Init->isValueDependent()) 12262 return false; 12263 return IsVariableAConstantExpression(Var, Context); 12264 } 12265 12266 12267 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 12268 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 12269 // an object that satisfies the requirements for appearing in a 12270 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 12271 // is immediately applied." This function handles the lvalue-to-rvalue 12272 // conversion part. 12273 MaybeODRUseExprs.erase(E->IgnoreParens()); 12274 12275 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 12276 // to a variable that is a constant expression, and if so, identify it as 12277 // a reference to a variable that does not involve an odr-use of that 12278 // variable. 12279 if (LambdaScopeInfo *LSI = getCurLambda()) { 12280 Expr *SansParensExpr = E->IgnoreParens(); 12281 VarDecl *Var = nullptr; 12282 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 12283 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 12284 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 12285 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 12286 12287 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 12288 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 12289 } 12290 } 12291 12292 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 12293 if (!Res.isUsable()) 12294 return Res; 12295 12296 // If a constant-expression is a reference to a variable where we delay 12297 // deciding whether it is an odr-use, just assume we will apply the 12298 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 12299 // (a non-type template argument), we have special handling anyway. 12300 UpdateMarkingForLValueToRValue(Res.get()); 12301 return Res; 12302 } 12303 12304 void Sema::CleanupVarDeclMarking() { 12305 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(), 12306 e = MaybeODRUseExprs.end(); 12307 i != e; ++i) { 12308 VarDecl *Var; 12309 SourceLocation Loc; 12310 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) { 12311 Var = cast<VarDecl>(DRE->getDecl()); 12312 Loc = DRE->getLocation(); 12313 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) { 12314 Var = cast<VarDecl>(ME->getMemberDecl()); 12315 Loc = ME->getMemberLoc(); 12316 } else { 12317 llvm_unreachable("Unexpcted expression"); 12318 } 12319 12320 MarkVarDeclODRUsed(Var, Loc, *this, 12321 /*MaxFunctionScopeIndex Pointer*/ nullptr); 12322 } 12323 12324 MaybeODRUseExprs.clear(); 12325 } 12326 12327 12328 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 12329 VarDecl *Var, Expr *E) { 12330 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 12331 "Invalid Expr argument to DoMarkVarDeclReferenced"); 12332 Var->setReferenced(); 12333 12334 // If the context is not potentially evaluated, this is not an odr-use and 12335 // does not trigger instantiation. 12336 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 12337 if (SemaRef.isUnevaluatedContext()) 12338 return; 12339 12340 // If we don't yet know whether this context is going to end up being an 12341 // evaluated context, and we're referencing a variable from an enclosing 12342 // scope, add a potential capture. 12343 // 12344 // FIXME: Is this necessary? These contexts are only used for default 12345 // arguments, where local variables can't be used. 12346 const bool RefersToEnclosingScope = 12347 (SemaRef.CurContext != Var->getDeclContext() && 12348 Var->getDeclContext()->isFunctionOrMethod() && 12349 Var->hasLocalStorage()); 12350 if (!RefersToEnclosingScope) 12351 return; 12352 12353 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 12354 // If a variable could potentially be odr-used, defer marking it so 12355 // until we finish analyzing the full expression for any lvalue-to-rvalue 12356 // or discarded value conversions that would obviate odr-use. 12357 // Add it to the list of potential captures that will be analyzed 12358 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 12359 // unless the variable is a reference that was initialized by a constant 12360 // expression (this will never need to be captured or odr-used). 12361 assert(E && "Capture variable should be used in an expression."); 12362 if (!Var->getType()->isReferenceType() || 12363 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 12364 LSI->addPotentialCapture(E->IgnoreParens()); 12365 } 12366 return; 12367 } 12368 12369 VarTemplateSpecializationDecl *VarSpec = 12370 dyn_cast<VarTemplateSpecializationDecl>(Var); 12371 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 12372 "Can't instantiate a partial template specialization."); 12373 12374 // Perform implicit instantiation of static data members, static data member 12375 // templates of class templates, and variable template specializations. Delay 12376 // instantiations of variable templates, except for those that could be used 12377 // in a constant expression. 12378 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 12379 if (isTemplateInstantiation(TSK)) { 12380 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 12381 12382 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 12383 if (Var->getPointOfInstantiation().isInvalid()) { 12384 // This is a modification of an existing AST node. Notify listeners. 12385 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 12386 L->StaticDataMemberInstantiated(Var); 12387 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 12388 // Don't bother trying to instantiate it again, unless we might need 12389 // its initializer before we get to the end of the TU. 12390 TryInstantiating = false; 12391 } 12392 12393 if (Var->getPointOfInstantiation().isInvalid()) 12394 Var->setTemplateSpecializationKind(TSK, Loc); 12395 12396 if (TryInstantiating) { 12397 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 12398 bool InstantiationDependent = false; 12399 bool IsNonDependent = 12400 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 12401 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 12402 : true; 12403 12404 // Do not instantiate specializations that are still type-dependent. 12405 if (IsNonDependent) { 12406 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 12407 // Do not defer instantiations of variables which could be used in a 12408 // constant expression. 12409 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 12410 } else { 12411 SemaRef.PendingInstantiations 12412 .push_back(std::make_pair(Var, PointOfInstantiation)); 12413 } 12414 } 12415 } 12416 } 12417 12418 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 12419 // the requirements for appearing in a constant expression (5.19) and, if 12420 // it is an object, the lvalue-to-rvalue conversion (4.1) 12421 // is immediately applied." We check the first part here, and 12422 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 12423 // Note that we use the C++11 definition everywhere because nothing in 12424 // C++03 depends on whether we get the C++03 version correct. The second 12425 // part does not apply to references, since they are not objects. 12426 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 12427 // A reference initialized by a constant expression can never be 12428 // odr-used, so simply ignore it. 12429 if (!Var->getType()->isReferenceType()) 12430 SemaRef.MaybeODRUseExprs.insert(E); 12431 } else 12432 MarkVarDeclODRUsed(Var, Loc, SemaRef, 12433 /*MaxFunctionScopeIndex ptr*/ nullptr); 12434 } 12435 12436 /// \brief Mark a variable referenced, and check whether it is odr-used 12437 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 12438 /// used directly for normal expressions referring to VarDecl. 12439 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 12440 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 12441 } 12442 12443 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 12444 Decl *D, Expr *E, bool OdrUse) { 12445 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 12446 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 12447 return; 12448 } 12449 12450 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse); 12451 12452 // If this is a call to a method via a cast, also mark the method in the 12453 // derived class used in case codegen can devirtualize the call. 12454 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12455 if (!ME) 12456 return; 12457 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 12458 if (!MD) 12459 return; 12460 const Expr *Base = ME->getBase(); 12461 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 12462 if (!MostDerivedClassDecl) 12463 return; 12464 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 12465 if (!DM || DM->isPure()) 12466 return; 12467 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse); 12468 } 12469 12470 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 12471 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 12472 // TODO: update this with DR# once a defect report is filed. 12473 // C++11 defect. The address of a pure member should not be an ODR use, even 12474 // if it's a qualified reference. 12475 bool OdrUse = true; 12476 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 12477 if (Method->isVirtual()) 12478 OdrUse = false; 12479 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 12480 } 12481 12482 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 12483 void Sema::MarkMemberReferenced(MemberExpr *E) { 12484 // C++11 [basic.def.odr]p2: 12485 // A non-overloaded function whose name appears as a potentially-evaluated 12486 // expression or a member of a set of candidate functions, if selected by 12487 // overload resolution when referred to from a potentially-evaluated 12488 // expression, is odr-used, unless it is a pure virtual function and its 12489 // name is not explicitly qualified. 12490 bool OdrUse = true; 12491 if (!E->hasQualifier()) { 12492 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 12493 if (Method->isPure()) 12494 OdrUse = false; 12495 } 12496 SourceLocation Loc = E->getMemberLoc().isValid() ? 12497 E->getMemberLoc() : E->getLocStart(); 12498 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse); 12499 } 12500 12501 /// \brief Perform marking for a reference to an arbitrary declaration. It 12502 /// marks the declaration referenced, and performs odr-use checking for 12503 /// functions and variables. This method should not be used when building a 12504 /// normal expression which refers to a variable. 12505 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) { 12506 if (OdrUse) { 12507 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 12508 MarkVariableReferenced(Loc, VD); 12509 return; 12510 } 12511 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 12512 MarkFunctionReferenced(Loc, FD); 12513 return; 12514 } 12515 } 12516 D->setReferenced(); 12517 } 12518 12519 namespace { 12520 // Mark all of the declarations referenced 12521 // FIXME: Not fully implemented yet! We need to have a better understanding 12522 // of when we're entering 12523 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 12524 Sema &S; 12525 SourceLocation Loc; 12526 12527 public: 12528 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 12529 12530 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 12531 12532 bool TraverseTemplateArgument(const TemplateArgument &Arg); 12533 bool TraverseRecordType(RecordType *T); 12534 }; 12535 } 12536 12537 bool MarkReferencedDecls::TraverseTemplateArgument( 12538 const TemplateArgument &Arg) { 12539 if (Arg.getKind() == TemplateArgument::Declaration) { 12540 if (Decl *D = Arg.getAsDecl()) 12541 S.MarkAnyDeclReferenced(Loc, D, true); 12542 } 12543 12544 return Inherited::TraverseTemplateArgument(Arg); 12545 } 12546 12547 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 12548 if (ClassTemplateSpecializationDecl *Spec 12549 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 12550 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 12551 return TraverseTemplateArguments(Args.data(), Args.size()); 12552 } 12553 12554 return true; 12555 } 12556 12557 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 12558 MarkReferencedDecls Marker(*this, Loc); 12559 Marker.TraverseType(Context.getCanonicalType(T)); 12560 } 12561 12562 namespace { 12563 /// \brief Helper class that marks all of the declarations referenced by 12564 /// potentially-evaluated subexpressions as "referenced". 12565 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 12566 Sema &S; 12567 bool SkipLocalVariables; 12568 12569 public: 12570 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 12571 12572 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 12573 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 12574 12575 void VisitDeclRefExpr(DeclRefExpr *E) { 12576 // If we were asked not to visit local variables, don't. 12577 if (SkipLocalVariables) { 12578 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 12579 if (VD->hasLocalStorage()) 12580 return; 12581 } 12582 12583 S.MarkDeclRefReferenced(E); 12584 } 12585 12586 void VisitMemberExpr(MemberExpr *E) { 12587 S.MarkMemberReferenced(E); 12588 Inherited::VisitMemberExpr(E); 12589 } 12590 12591 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 12592 S.MarkFunctionReferenced(E->getLocStart(), 12593 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 12594 Visit(E->getSubExpr()); 12595 } 12596 12597 void VisitCXXNewExpr(CXXNewExpr *E) { 12598 if (E->getOperatorNew()) 12599 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 12600 if (E->getOperatorDelete()) 12601 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 12602 Inherited::VisitCXXNewExpr(E); 12603 } 12604 12605 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 12606 if (E->getOperatorDelete()) 12607 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 12608 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 12609 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 12610 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 12611 S.MarkFunctionReferenced(E->getLocStart(), 12612 S.LookupDestructor(Record)); 12613 } 12614 12615 Inherited::VisitCXXDeleteExpr(E); 12616 } 12617 12618 void VisitCXXConstructExpr(CXXConstructExpr *E) { 12619 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 12620 Inherited::VisitCXXConstructExpr(E); 12621 } 12622 12623 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 12624 Visit(E->getExpr()); 12625 } 12626 12627 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 12628 Inherited::VisitImplicitCastExpr(E); 12629 12630 if (E->getCastKind() == CK_LValueToRValue) 12631 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 12632 } 12633 }; 12634 } 12635 12636 /// \brief Mark any declarations that appear within this expression or any 12637 /// potentially-evaluated subexpressions as "referenced". 12638 /// 12639 /// \param SkipLocalVariables If true, don't mark local variables as 12640 /// 'referenced'. 12641 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 12642 bool SkipLocalVariables) { 12643 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 12644 } 12645 12646 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 12647 /// of the program being compiled. 12648 /// 12649 /// This routine emits the given diagnostic when the code currently being 12650 /// type-checked is "potentially evaluated", meaning that there is a 12651 /// possibility that the code will actually be executable. Code in sizeof() 12652 /// expressions, code used only during overload resolution, etc., are not 12653 /// potentially evaluated. This routine will suppress such diagnostics or, 12654 /// in the absolutely nutty case of potentially potentially evaluated 12655 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 12656 /// later. 12657 /// 12658 /// This routine should be used for all diagnostics that describe the run-time 12659 /// behavior of a program, such as passing a non-POD value through an ellipsis. 12660 /// Failure to do so will likely result in spurious diagnostics or failures 12661 /// during overload resolution or within sizeof/alignof/typeof/typeid. 12662 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 12663 const PartialDiagnostic &PD) { 12664 switch (ExprEvalContexts.back().Context) { 12665 case Unevaluated: 12666 case UnevaluatedAbstract: 12667 // The argument will never be evaluated, so don't complain. 12668 break; 12669 12670 case ConstantEvaluated: 12671 // Relevant diagnostics should be produced by constant evaluation. 12672 break; 12673 12674 case PotentiallyEvaluated: 12675 case PotentiallyEvaluatedIfUsed: 12676 if (Statement && getCurFunctionOrMethodDecl()) { 12677 FunctionScopes.back()->PossiblyUnreachableDiags. 12678 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 12679 } 12680 else 12681 Diag(Loc, PD); 12682 12683 return true; 12684 } 12685 12686 return false; 12687 } 12688 12689 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 12690 CallExpr *CE, FunctionDecl *FD) { 12691 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 12692 return false; 12693 12694 // If we're inside a decltype's expression, don't check for a valid return 12695 // type or construct temporaries until we know whether this is the last call. 12696 if (ExprEvalContexts.back().IsDecltype) { 12697 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 12698 return false; 12699 } 12700 12701 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 12702 FunctionDecl *FD; 12703 CallExpr *CE; 12704 12705 public: 12706 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 12707 : FD(FD), CE(CE) { } 12708 12709 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 12710 if (!FD) { 12711 S.Diag(Loc, diag::err_call_incomplete_return) 12712 << T << CE->getSourceRange(); 12713 return; 12714 } 12715 12716 S.Diag(Loc, diag::err_call_function_incomplete_return) 12717 << CE->getSourceRange() << FD->getDeclName() << T; 12718 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 12719 << FD->getDeclName(); 12720 } 12721 } Diagnoser(FD, CE); 12722 12723 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 12724 return true; 12725 12726 return false; 12727 } 12728 12729 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 12730 // will prevent this condition from triggering, which is what we want. 12731 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 12732 SourceLocation Loc; 12733 12734 unsigned diagnostic = diag::warn_condition_is_assignment; 12735 bool IsOrAssign = false; 12736 12737 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 12738 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 12739 return; 12740 12741 IsOrAssign = Op->getOpcode() == BO_OrAssign; 12742 12743 // Greylist some idioms by putting them into a warning subcategory. 12744 if (ObjCMessageExpr *ME 12745 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 12746 Selector Sel = ME->getSelector(); 12747 12748 // self = [<foo> init...] 12749 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 12750 diagnostic = diag::warn_condition_is_idiomatic_assignment; 12751 12752 // <foo> = [<bar> nextObject] 12753 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 12754 diagnostic = diag::warn_condition_is_idiomatic_assignment; 12755 } 12756 12757 Loc = Op->getOperatorLoc(); 12758 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 12759 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 12760 return; 12761 12762 IsOrAssign = Op->getOperator() == OO_PipeEqual; 12763 Loc = Op->getOperatorLoc(); 12764 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 12765 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 12766 else { 12767 // Not an assignment. 12768 return; 12769 } 12770 12771 Diag(Loc, diagnostic) << E->getSourceRange(); 12772 12773 SourceLocation Open = E->getLocStart(); 12774 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 12775 Diag(Loc, diag::note_condition_assign_silence) 12776 << FixItHint::CreateInsertion(Open, "(") 12777 << FixItHint::CreateInsertion(Close, ")"); 12778 12779 if (IsOrAssign) 12780 Diag(Loc, diag::note_condition_or_assign_to_comparison) 12781 << FixItHint::CreateReplacement(Loc, "!="); 12782 else 12783 Diag(Loc, diag::note_condition_assign_to_comparison) 12784 << FixItHint::CreateReplacement(Loc, "=="); 12785 } 12786 12787 /// \brief Redundant parentheses over an equality comparison can indicate 12788 /// that the user intended an assignment used as condition. 12789 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 12790 // Don't warn if the parens came from a macro. 12791 SourceLocation parenLoc = ParenE->getLocStart(); 12792 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 12793 return; 12794 // Don't warn for dependent expressions. 12795 if (ParenE->isTypeDependent()) 12796 return; 12797 12798 Expr *E = ParenE->IgnoreParens(); 12799 12800 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 12801 if (opE->getOpcode() == BO_EQ && 12802 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 12803 == Expr::MLV_Valid) { 12804 SourceLocation Loc = opE->getOperatorLoc(); 12805 12806 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 12807 SourceRange ParenERange = ParenE->getSourceRange(); 12808 Diag(Loc, diag::note_equality_comparison_silence) 12809 << FixItHint::CreateRemoval(ParenERange.getBegin()) 12810 << FixItHint::CreateRemoval(ParenERange.getEnd()); 12811 Diag(Loc, diag::note_equality_comparison_to_assign) 12812 << FixItHint::CreateReplacement(Loc, "="); 12813 } 12814 } 12815 12816 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 12817 DiagnoseAssignmentAsCondition(E); 12818 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 12819 DiagnoseEqualityWithExtraParens(parenE); 12820 12821 ExprResult result = CheckPlaceholderExpr(E); 12822 if (result.isInvalid()) return ExprError(); 12823 E = result.get(); 12824 12825 if (!E->isTypeDependent()) { 12826 if (getLangOpts().CPlusPlus) 12827 return CheckCXXBooleanCondition(E); // C++ 6.4p4 12828 12829 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 12830 if (ERes.isInvalid()) 12831 return ExprError(); 12832 E = ERes.get(); 12833 12834 QualType T = E->getType(); 12835 if (!T->isScalarType()) { // C99 6.8.4.1p1 12836 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 12837 << T << E->getSourceRange(); 12838 return ExprError(); 12839 } 12840 } 12841 12842 return E; 12843 } 12844 12845 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 12846 Expr *SubExpr) { 12847 if (!SubExpr) 12848 return ExprError(); 12849 12850 return CheckBooleanCondition(SubExpr, Loc); 12851 } 12852 12853 namespace { 12854 /// A visitor for rebuilding a call to an __unknown_any expression 12855 /// to have an appropriate type. 12856 struct RebuildUnknownAnyFunction 12857 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 12858 12859 Sema &S; 12860 12861 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 12862 12863 ExprResult VisitStmt(Stmt *S) { 12864 llvm_unreachable("unexpected statement!"); 12865 } 12866 12867 ExprResult VisitExpr(Expr *E) { 12868 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 12869 << E->getSourceRange(); 12870 return ExprError(); 12871 } 12872 12873 /// Rebuild an expression which simply semantically wraps another 12874 /// expression which it shares the type and value kind of. 12875 template <class T> ExprResult rebuildSugarExpr(T *E) { 12876 ExprResult SubResult = Visit(E->getSubExpr()); 12877 if (SubResult.isInvalid()) return ExprError(); 12878 12879 Expr *SubExpr = SubResult.get(); 12880 E->setSubExpr(SubExpr); 12881 E->setType(SubExpr->getType()); 12882 E->setValueKind(SubExpr->getValueKind()); 12883 assert(E->getObjectKind() == OK_Ordinary); 12884 return E; 12885 } 12886 12887 ExprResult VisitParenExpr(ParenExpr *E) { 12888 return rebuildSugarExpr(E); 12889 } 12890 12891 ExprResult VisitUnaryExtension(UnaryOperator *E) { 12892 return rebuildSugarExpr(E); 12893 } 12894 12895 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 12896 ExprResult SubResult = Visit(E->getSubExpr()); 12897 if (SubResult.isInvalid()) return ExprError(); 12898 12899 Expr *SubExpr = SubResult.get(); 12900 E->setSubExpr(SubExpr); 12901 E->setType(S.Context.getPointerType(SubExpr->getType())); 12902 assert(E->getValueKind() == VK_RValue); 12903 assert(E->getObjectKind() == OK_Ordinary); 12904 return E; 12905 } 12906 12907 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 12908 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 12909 12910 E->setType(VD->getType()); 12911 12912 assert(E->getValueKind() == VK_RValue); 12913 if (S.getLangOpts().CPlusPlus && 12914 !(isa<CXXMethodDecl>(VD) && 12915 cast<CXXMethodDecl>(VD)->isInstance())) 12916 E->setValueKind(VK_LValue); 12917 12918 return E; 12919 } 12920 12921 ExprResult VisitMemberExpr(MemberExpr *E) { 12922 return resolveDecl(E, E->getMemberDecl()); 12923 } 12924 12925 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 12926 return resolveDecl(E, E->getDecl()); 12927 } 12928 }; 12929 } 12930 12931 /// Given a function expression of unknown-any type, try to rebuild it 12932 /// to have a function type. 12933 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 12934 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 12935 if (Result.isInvalid()) return ExprError(); 12936 return S.DefaultFunctionArrayConversion(Result.get()); 12937 } 12938 12939 namespace { 12940 /// A visitor for rebuilding an expression of type __unknown_anytype 12941 /// into one which resolves the type directly on the referring 12942 /// expression. Strict preservation of the original source 12943 /// structure is not a goal. 12944 struct RebuildUnknownAnyExpr 12945 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 12946 12947 Sema &S; 12948 12949 /// The current destination type. 12950 QualType DestType; 12951 12952 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 12953 : S(S), DestType(CastType) {} 12954 12955 ExprResult VisitStmt(Stmt *S) { 12956 llvm_unreachable("unexpected statement!"); 12957 } 12958 12959 ExprResult VisitExpr(Expr *E) { 12960 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 12961 << E->getSourceRange(); 12962 return ExprError(); 12963 } 12964 12965 ExprResult VisitCallExpr(CallExpr *E); 12966 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 12967 12968 /// Rebuild an expression which simply semantically wraps another 12969 /// expression which it shares the type and value kind of. 12970 template <class T> ExprResult rebuildSugarExpr(T *E) { 12971 ExprResult SubResult = Visit(E->getSubExpr()); 12972 if (SubResult.isInvalid()) return ExprError(); 12973 Expr *SubExpr = SubResult.get(); 12974 E->setSubExpr(SubExpr); 12975 E->setType(SubExpr->getType()); 12976 E->setValueKind(SubExpr->getValueKind()); 12977 assert(E->getObjectKind() == OK_Ordinary); 12978 return E; 12979 } 12980 12981 ExprResult VisitParenExpr(ParenExpr *E) { 12982 return rebuildSugarExpr(E); 12983 } 12984 12985 ExprResult VisitUnaryExtension(UnaryOperator *E) { 12986 return rebuildSugarExpr(E); 12987 } 12988 12989 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 12990 const PointerType *Ptr = DestType->getAs<PointerType>(); 12991 if (!Ptr) { 12992 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 12993 << E->getSourceRange(); 12994 return ExprError(); 12995 } 12996 assert(E->getValueKind() == VK_RValue); 12997 assert(E->getObjectKind() == OK_Ordinary); 12998 E->setType(DestType); 12999 13000 // Build the sub-expression as if it were an object of the pointee type. 13001 DestType = Ptr->getPointeeType(); 13002 ExprResult SubResult = Visit(E->getSubExpr()); 13003 if (SubResult.isInvalid()) return ExprError(); 13004 E->setSubExpr(SubResult.get()); 13005 return E; 13006 } 13007 13008 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 13009 13010 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 13011 13012 ExprResult VisitMemberExpr(MemberExpr *E) { 13013 return resolveDecl(E, E->getMemberDecl()); 13014 } 13015 13016 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 13017 return resolveDecl(E, E->getDecl()); 13018 } 13019 }; 13020 } 13021 13022 /// Rebuilds a call expression which yielded __unknown_anytype. 13023 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 13024 Expr *CalleeExpr = E->getCallee(); 13025 13026 enum FnKind { 13027 FK_MemberFunction, 13028 FK_FunctionPointer, 13029 FK_BlockPointer 13030 }; 13031 13032 FnKind Kind; 13033 QualType CalleeType = CalleeExpr->getType(); 13034 if (CalleeType == S.Context.BoundMemberTy) { 13035 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 13036 Kind = FK_MemberFunction; 13037 CalleeType = Expr::findBoundMemberType(CalleeExpr); 13038 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 13039 CalleeType = Ptr->getPointeeType(); 13040 Kind = FK_FunctionPointer; 13041 } else { 13042 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 13043 Kind = FK_BlockPointer; 13044 } 13045 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 13046 13047 // Verify that this is a legal result type of a function. 13048 if (DestType->isArrayType() || DestType->isFunctionType()) { 13049 unsigned diagID = diag::err_func_returning_array_function; 13050 if (Kind == FK_BlockPointer) 13051 diagID = diag::err_block_returning_array_function; 13052 13053 S.Diag(E->getExprLoc(), diagID) 13054 << DestType->isFunctionType() << DestType; 13055 return ExprError(); 13056 } 13057 13058 // Otherwise, go ahead and set DestType as the call's result. 13059 E->setType(DestType.getNonLValueExprType(S.Context)); 13060 E->setValueKind(Expr::getValueKindForType(DestType)); 13061 assert(E->getObjectKind() == OK_Ordinary); 13062 13063 // Rebuild the function type, replacing the result type with DestType. 13064 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 13065 if (Proto) { 13066 // __unknown_anytype(...) is a special case used by the debugger when 13067 // it has no idea what a function's signature is. 13068 // 13069 // We want to build this call essentially under the K&R 13070 // unprototyped rules, but making a FunctionNoProtoType in C++ 13071 // would foul up all sorts of assumptions. However, we cannot 13072 // simply pass all arguments as variadic arguments, nor can we 13073 // portably just call the function under a non-variadic type; see 13074 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 13075 // However, it turns out that in practice it is generally safe to 13076 // call a function declared as "A foo(B,C,D);" under the prototype 13077 // "A foo(B,C,D,...);". The only known exception is with the 13078 // Windows ABI, where any variadic function is implicitly cdecl 13079 // regardless of its normal CC. Therefore we change the parameter 13080 // types to match the types of the arguments. 13081 // 13082 // This is a hack, but it is far superior to moving the 13083 // corresponding target-specific code from IR-gen to Sema/AST. 13084 13085 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 13086 SmallVector<QualType, 8> ArgTypes; 13087 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 13088 ArgTypes.reserve(E->getNumArgs()); 13089 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 13090 Expr *Arg = E->getArg(i); 13091 QualType ArgType = Arg->getType(); 13092 if (E->isLValue()) { 13093 ArgType = S.Context.getLValueReferenceType(ArgType); 13094 } else if (E->isXValue()) { 13095 ArgType = S.Context.getRValueReferenceType(ArgType); 13096 } 13097 ArgTypes.push_back(ArgType); 13098 } 13099 ParamTypes = ArgTypes; 13100 } 13101 DestType = S.Context.getFunctionType(DestType, ParamTypes, 13102 Proto->getExtProtoInfo()); 13103 } else { 13104 DestType = S.Context.getFunctionNoProtoType(DestType, 13105 FnType->getExtInfo()); 13106 } 13107 13108 // Rebuild the appropriate pointer-to-function type. 13109 switch (Kind) { 13110 case FK_MemberFunction: 13111 // Nothing to do. 13112 break; 13113 13114 case FK_FunctionPointer: 13115 DestType = S.Context.getPointerType(DestType); 13116 break; 13117 13118 case FK_BlockPointer: 13119 DestType = S.Context.getBlockPointerType(DestType); 13120 break; 13121 } 13122 13123 // Finally, we can recurse. 13124 ExprResult CalleeResult = Visit(CalleeExpr); 13125 if (!CalleeResult.isUsable()) return ExprError(); 13126 E->setCallee(CalleeResult.get()); 13127 13128 // Bind a temporary if necessary. 13129 return S.MaybeBindToTemporary(E); 13130 } 13131 13132 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 13133 // Verify that this is a legal result type of a call. 13134 if (DestType->isArrayType() || DestType->isFunctionType()) { 13135 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 13136 << DestType->isFunctionType() << DestType; 13137 return ExprError(); 13138 } 13139 13140 // Rewrite the method result type if available. 13141 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 13142 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 13143 Method->setReturnType(DestType); 13144 } 13145 13146 // Change the type of the message. 13147 E->setType(DestType.getNonReferenceType()); 13148 E->setValueKind(Expr::getValueKindForType(DestType)); 13149 13150 return S.MaybeBindToTemporary(E); 13151 } 13152 13153 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 13154 // The only case we should ever see here is a function-to-pointer decay. 13155 if (E->getCastKind() == CK_FunctionToPointerDecay) { 13156 assert(E->getValueKind() == VK_RValue); 13157 assert(E->getObjectKind() == OK_Ordinary); 13158 13159 E->setType(DestType); 13160 13161 // Rebuild the sub-expression as the pointee (function) type. 13162 DestType = DestType->castAs<PointerType>()->getPointeeType(); 13163 13164 ExprResult Result = Visit(E->getSubExpr()); 13165 if (!Result.isUsable()) return ExprError(); 13166 13167 E->setSubExpr(Result.get()); 13168 return E; 13169 } else if (E->getCastKind() == CK_LValueToRValue) { 13170 assert(E->getValueKind() == VK_RValue); 13171 assert(E->getObjectKind() == OK_Ordinary); 13172 13173 assert(isa<BlockPointerType>(E->getType())); 13174 13175 E->setType(DestType); 13176 13177 // The sub-expression has to be a lvalue reference, so rebuild it as such. 13178 DestType = S.Context.getLValueReferenceType(DestType); 13179 13180 ExprResult Result = Visit(E->getSubExpr()); 13181 if (!Result.isUsable()) return ExprError(); 13182 13183 E->setSubExpr(Result.get()); 13184 return E; 13185 } else { 13186 llvm_unreachable("Unhandled cast type!"); 13187 } 13188 } 13189 13190 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 13191 ExprValueKind ValueKind = VK_LValue; 13192 QualType Type = DestType; 13193 13194 // We know how to make this work for certain kinds of decls: 13195 13196 // - functions 13197 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 13198 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 13199 DestType = Ptr->getPointeeType(); 13200 ExprResult Result = resolveDecl(E, VD); 13201 if (Result.isInvalid()) return ExprError(); 13202 return S.ImpCastExprToType(Result.get(), Type, 13203 CK_FunctionToPointerDecay, VK_RValue); 13204 } 13205 13206 if (!Type->isFunctionType()) { 13207 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 13208 << VD << E->getSourceRange(); 13209 return ExprError(); 13210 } 13211 13212 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 13213 if (MD->isInstance()) { 13214 ValueKind = VK_RValue; 13215 Type = S.Context.BoundMemberTy; 13216 } 13217 13218 // Function references aren't l-values in C. 13219 if (!S.getLangOpts().CPlusPlus) 13220 ValueKind = VK_RValue; 13221 13222 // - variables 13223 } else if (isa<VarDecl>(VD)) { 13224 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 13225 Type = RefTy->getPointeeType(); 13226 } else if (Type->isFunctionType()) { 13227 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 13228 << VD << E->getSourceRange(); 13229 return ExprError(); 13230 } 13231 13232 // - nothing else 13233 } else { 13234 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 13235 << VD << E->getSourceRange(); 13236 return ExprError(); 13237 } 13238 13239 // Modifying the declaration like this is friendly to IR-gen but 13240 // also really dangerous. 13241 VD->setType(DestType); 13242 E->setType(Type); 13243 E->setValueKind(ValueKind); 13244 return E; 13245 } 13246 13247 /// Check a cast of an unknown-any type. We intentionally only 13248 /// trigger this for C-style casts. 13249 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 13250 Expr *CastExpr, CastKind &CastKind, 13251 ExprValueKind &VK, CXXCastPath &Path) { 13252 // Rewrite the casted expression from scratch. 13253 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 13254 if (!result.isUsable()) return ExprError(); 13255 13256 CastExpr = result.get(); 13257 VK = CastExpr->getValueKind(); 13258 CastKind = CK_NoOp; 13259 13260 return CastExpr; 13261 } 13262 13263 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 13264 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 13265 } 13266 13267 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 13268 Expr *arg, QualType ¶mType) { 13269 // If the syntactic form of the argument is not an explicit cast of 13270 // any sort, just do default argument promotion. 13271 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 13272 if (!castArg) { 13273 ExprResult result = DefaultArgumentPromotion(arg); 13274 if (result.isInvalid()) return ExprError(); 13275 paramType = result.get()->getType(); 13276 return result; 13277 } 13278 13279 // Otherwise, use the type that was written in the explicit cast. 13280 assert(!arg->hasPlaceholderType()); 13281 paramType = castArg->getTypeAsWritten(); 13282 13283 // Copy-initialize a parameter of that type. 13284 InitializedEntity entity = 13285 InitializedEntity::InitializeParameter(Context, paramType, 13286 /*consumed*/ false); 13287 return PerformCopyInitialization(entity, callLoc, arg); 13288 } 13289 13290 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 13291 Expr *orig = E; 13292 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 13293 while (true) { 13294 E = E->IgnoreParenImpCasts(); 13295 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 13296 E = call->getCallee(); 13297 diagID = diag::err_uncasted_call_of_unknown_any; 13298 } else { 13299 break; 13300 } 13301 } 13302 13303 SourceLocation loc; 13304 NamedDecl *d; 13305 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 13306 loc = ref->getLocation(); 13307 d = ref->getDecl(); 13308 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 13309 loc = mem->getMemberLoc(); 13310 d = mem->getMemberDecl(); 13311 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 13312 diagID = diag::err_uncasted_call_of_unknown_any; 13313 loc = msg->getSelectorStartLoc(); 13314 d = msg->getMethodDecl(); 13315 if (!d) { 13316 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 13317 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 13318 << orig->getSourceRange(); 13319 return ExprError(); 13320 } 13321 } else { 13322 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 13323 << E->getSourceRange(); 13324 return ExprError(); 13325 } 13326 13327 S.Diag(loc, diagID) << d << orig->getSourceRange(); 13328 13329 // Never recoverable. 13330 return ExprError(); 13331 } 13332 13333 /// Check for operands with placeholder types and complain if found. 13334 /// Returns true if there was an error and no recovery was possible. 13335 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 13336 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 13337 if (!placeholderType) return E; 13338 13339 switch (placeholderType->getKind()) { 13340 13341 // Overloaded expressions. 13342 case BuiltinType::Overload: { 13343 // Try to resolve a single function template specialization. 13344 // This is obligatory. 13345 ExprResult result = E; 13346 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 13347 return result; 13348 13349 // If that failed, try to recover with a call. 13350 } else { 13351 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 13352 /*complain*/ true); 13353 return result; 13354 } 13355 } 13356 13357 // Bound member functions. 13358 case BuiltinType::BoundMember: { 13359 ExprResult result = E; 13360 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function), 13361 /*complain*/ true); 13362 return result; 13363 } 13364 13365 // ARC unbridged casts. 13366 case BuiltinType::ARCUnbridgedCast: { 13367 Expr *realCast = stripARCUnbridgedCast(E); 13368 diagnoseARCUnbridgedCast(realCast); 13369 return realCast; 13370 } 13371 13372 // Expressions of unknown type. 13373 case BuiltinType::UnknownAny: 13374 return diagnoseUnknownAnyExpr(*this, E); 13375 13376 // Pseudo-objects. 13377 case BuiltinType::PseudoObject: 13378 return checkPseudoObjectRValue(E); 13379 13380 case BuiltinType::BuiltinFn: 13381 Diag(E->getLocStart(), diag::err_builtin_fn_use); 13382 return ExprError(); 13383 13384 // Everything else should be impossible. 13385 #define BUILTIN_TYPE(Id, SingletonId) \ 13386 case BuiltinType::Id: 13387 #define PLACEHOLDER_TYPE(Id, SingletonId) 13388 #include "clang/AST/BuiltinTypes.def" 13389 break; 13390 } 13391 13392 llvm_unreachable("invalid placeholder type!"); 13393 } 13394 13395 bool Sema::CheckCaseExpression(Expr *E) { 13396 if (E->isTypeDependent()) 13397 return true; 13398 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 13399 return E->getType()->isIntegralOrEnumerationType(); 13400 return false; 13401 } 13402 13403 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 13404 ExprResult 13405 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 13406 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 13407 "Unknown Objective-C Boolean value!"); 13408 QualType BoolT = Context.ObjCBuiltinBoolTy; 13409 if (!Context.getBOOLDecl()) { 13410 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 13411 Sema::LookupOrdinaryName); 13412 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 13413 NamedDecl *ND = Result.getFoundDecl(); 13414 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 13415 Context.setBOOLDecl(TD); 13416 } 13417 } 13418 if (Context.getBOOLDecl()) 13419 BoolT = Context.getBOOLType(); 13420 return new (Context) 13421 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 13422 } 13423