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/ExprOpenMP.h" 28 #include "clang/AST/RecursiveASTVisitor.h" 29 #include "clang/AST/TypeLoc.h" 30 #include "clang/Basic/PartialDiagnostic.h" 31 #include "clang/Basic/SourceManager.h" 32 #include "clang/Basic/TargetInfo.h" 33 #include "clang/Lex/LiteralSupport.h" 34 #include "clang/Lex/Preprocessor.h" 35 #include "clang/Sema/AnalysisBasedWarnings.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Designator.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/SemaFixItUtils.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/Support/ConvertUTF.h" 47 using namespace clang; 48 using namespace sema; 49 50 /// \brief Determine whether the use of this declaration is valid, without 51 /// emitting diagnostics. 52 bool Sema::CanUseDecl(NamedDecl *D) { 53 // See if this is an auto-typed variable whose initializer we are parsing. 54 if (ParsingInitForAutoVars.count(D)) 55 return false; 56 57 // See if this is a deleted function. 58 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 59 if (FD->isDeleted()) 60 return false; 61 62 // If the function has a deduced return type, and we can't deduce it, 63 // then we can't use it either. 64 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 65 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 66 return false; 67 } 68 69 // See if this function is unavailable. 70 if (D->getAvailability() == AR_Unavailable && 71 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 72 return false; 73 74 return true; 75 } 76 77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 78 // Warn if this is used but marked unused. 79 if (D->hasAttr<UnusedAttr>()) { 80 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 81 if (DC && !DC->hasAttr<UnusedAttr>()) 82 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 83 } 84 } 85 86 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) { 87 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 88 if (!OMD) 89 return false; 90 const ObjCInterfaceDecl *OID = OMD->getClassInterface(); 91 if (!OID) 92 return false; 93 94 for (const ObjCCategoryDecl *Cat : OID->visible_categories()) 95 if (ObjCMethodDecl *CatMeth = 96 Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod())) 97 if (!CatMeth->hasAttr<AvailabilityAttr>()) 98 return true; 99 return false; 100 } 101 102 static AvailabilityResult 103 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc, 104 const ObjCInterfaceDecl *UnknownObjCClass, 105 bool ObjCPropertyAccess) { 106 // See if this declaration is unavailable or deprecated. 107 std::string Message; 108 AvailabilityResult Result = D->getAvailability(&Message); 109 110 // For typedefs, if the typedef declaration appears available look 111 // to the underlying type to see if it is more restrictive. 112 while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 113 if (Result == AR_Available) { 114 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 115 D = TT->getDecl(); 116 Result = D->getAvailability(&Message); 117 continue; 118 } 119 } 120 break; 121 } 122 123 // Forward class declarations get their attributes from their definition. 124 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) { 125 if (IDecl->getDefinition()) { 126 D = IDecl->getDefinition(); 127 Result = D->getAvailability(&Message); 128 } 129 } 130 131 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 132 if (Result == AR_Available) { 133 const DeclContext *DC = ECD->getDeclContext(); 134 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 135 Result = TheEnumDecl->getAvailability(&Message); 136 } 137 138 const ObjCPropertyDecl *ObjCPDecl = nullptr; 139 if (Result == AR_Deprecated || Result == AR_Unavailable || 140 AR_NotYetIntroduced) { 141 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 142 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 143 AvailabilityResult PDeclResult = PD->getAvailability(nullptr); 144 if (PDeclResult == Result) 145 ObjCPDecl = PD; 146 } 147 } 148 } 149 150 switch (Result) { 151 case AR_Available: 152 break; 153 154 case AR_Deprecated: 155 if (S.getCurContextAvailability() != AR_Deprecated) 156 S.EmitAvailabilityWarning(Sema::AD_Deprecation, 157 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 158 ObjCPropertyAccess); 159 break; 160 161 case AR_NotYetIntroduced: { 162 // Don't do this for enums, they can't be redeclared. 163 if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D)) 164 break; 165 166 bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited(); 167 // Objective-C method declarations in categories are not modelled as 168 // redeclarations, so manually look for a redeclaration in a category 169 // if necessary. 170 if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D)) 171 Warn = false; 172 // In general, D will point to the most recent redeclaration. However, 173 // for `@class A;` decls, this isn't true -- manually go through the 174 // redecl chain in that case. 175 if (Warn && isa<ObjCInterfaceDecl>(D)) 176 for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn; 177 Redecl = Redecl->getPreviousDecl()) 178 if (!Redecl->hasAttr<AvailabilityAttr>() || 179 Redecl->getAttr<AvailabilityAttr>()->isInherited()) 180 Warn = false; 181 182 if (Warn) 183 S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc, 184 UnknownObjCClass, ObjCPDecl, 185 ObjCPropertyAccess); 186 break; 187 } 188 189 case AR_Unavailable: 190 if (S.getCurContextAvailability() != AR_Unavailable) 191 S.EmitAvailabilityWarning(Sema::AD_Unavailable, 192 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 193 ObjCPropertyAccess); 194 break; 195 196 } 197 return Result; 198 } 199 200 /// \brief Emit a note explaining that this function is deleted. 201 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 202 assert(Decl->isDeleted()); 203 204 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 205 206 if (Method && Method->isDeleted() && Method->isDefaulted()) { 207 // If the method was explicitly defaulted, point at that declaration. 208 if (!Method->isImplicit()) 209 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 210 211 // Try to diagnose why this special member function was implicitly 212 // deleted. This might fail, if that reason no longer applies. 213 CXXSpecialMember CSM = getSpecialMember(Method); 214 if (CSM != CXXInvalid) 215 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true); 216 217 return; 218 } 219 220 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) { 221 if (CXXConstructorDecl *BaseCD = 222 const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) { 223 Diag(Decl->getLocation(), diag::note_inherited_deleted_here); 224 if (BaseCD->isDeleted()) { 225 NoteDeletedFunction(BaseCD); 226 } else { 227 // FIXME: An explanation of why exactly it can't be inherited 228 // would be nice. 229 Diag(BaseCD->getLocation(), diag::note_cannot_inherit); 230 } 231 return; 232 } 233 } 234 235 Diag(Decl->getLocation(), diag::note_availability_specified_here) 236 << Decl << true; 237 } 238 239 /// \brief Determine whether a FunctionDecl was ever declared with an 240 /// explicit storage class. 241 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 242 for (auto I : D->redecls()) { 243 if (I->getStorageClass() != SC_None) 244 return true; 245 } 246 return false; 247 } 248 249 /// \brief Check whether we're in an extern inline function and referring to a 250 /// variable or function with internal linkage (C11 6.7.4p3). 251 /// 252 /// This is only a warning because we used to silently accept this code, but 253 /// in many cases it will not behave correctly. This is not enabled in C++ mode 254 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 255 /// and so while there may still be user mistakes, most of the time we can't 256 /// prove that there are errors. 257 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 258 const NamedDecl *D, 259 SourceLocation Loc) { 260 // This is disabled under C++; there are too many ways for this to fire in 261 // contexts where the warning is a false positive, or where it is technically 262 // correct but benign. 263 if (S.getLangOpts().CPlusPlus) 264 return; 265 266 // Check if this is an inlined function or method. 267 FunctionDecl *Current = S.getCurFunctionDecl(); 268 if (!Current) 269 return; 270 if (!Current->isInlined()) 271 return; 272 if (!Current->isExternallyVisible()) 273 return; 274 275 // Check if the decl has internal linkage. 276 if (D->getFormalLinkage() != InternalLinkage) 277 return; 278 279 // Downgrade from ExtWarn to Extension if 280 // (1) the supposedly external inline function is in the main file, 281 // and probably won't be included anywhere else. 282 // (2) the thing we're referencing is a pure function. 283 // (3) the thing we're referencing is another inline function. 284 // This last can give us false negatives, but it's better than warning on 285 // wrappers for simple C library functions. 286 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 287 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 288 if (!DowngradeWarning && UsedFn) 289 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 290 291 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 292 : diag::ext_internal_in_extern_inline) 293 << /*IsVar=*/!UsedFn << D; 294 295 S.MaybeSuggestAddingStaticToDecl(Current); 296 297 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 298 << D; 299 } 300 301 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 302 const FunctionDecl *First = Cur->getFirstDecl(); 303 304 // Suggest "static" on the function, if possible. 305 if (!hasAnyExplicitStorageClass(First)) { 306 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 307 Diag(DeclBegin, diag::note_convert_inline_to_static) 308 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 309 } 310 } 311 312 /// \brief Determine whether the use of this declaration is valid, and 313 /// emit any corresponding diagnostics. 314 /// 315 /// This routine diagnoses various problems with referencing 316 /// declarations that can occur when using a declaration. For example, 317 /// it might warn if a deprecated or unavailable declaration is being 318 /// used, or produce an error (and return true) if a C++0x deleted 319 /// function is being used. 320 /// 321 /// \returns true if there was an error (this declaration cannot be 322 /// referenced), false otherwise. 323 /// 324 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 325 const ObjCInterfaceDecl *UnknownObjCClass, 326 bool ObjCPropertyAccess) { 327 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 328 // If there were any diagnostics suppressed by template argument deduction, 329 // emit them now. 330 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 331 if (Pos != SuppressedDiagnostics.end()) { 332 for (const PartialDiagnosticAt &Suppressed : Pos->second) 333 Diag(Suppressed.first, Suppressed.second); 334 335 // Clear out the list of suppressed diagnostics, so that we don't emit 336 // them again for this specialization. However, we don't obsolete this 337 // entry from the table, because we want to avoid ever emitting these 338 // diagnostics again. 339 Pos->second.clear(); 340 } 341 342 // C++ [basic.start.main]p3: 343 // The function 'main' shall not be used within a program. 344 if (cast<FunctionDecl>(D)->isMain()) 345 Diag(Loc, diag::ext_main_used); 346 } 347 348 // See if this is an auto-typed variable whose initializer we are parsing. 349 if (ParsingInitForAutoVars.count(D)) { 350 const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType(); 351 352 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 353 << D->getDeclName() << (unsigned)AT->getKeyword(); 354 return true; 355 } 356 357 // See if this is a deleted function. 358 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 359 if (FD->isDeleted()) { 360 Diag(Loc, diag::err_deleted_function_use); 361 NoteDeletedFunction(FD); 362 return true; 363 } 364 365 // If the function has a deduced return type, and we can't deduce it, 366 // then we can't use it either. 367 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 368 DeduceReturnType(FD, Loc)) 369 return true; 370 } 371 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, 372 ObjCPropertyAccess); 373 374 DiagnoseUnusedOfDecl(*this, D, Loc); 375 376 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 377 378 return false; 379 } 380 381 /// \brief Retrieve the message suffix that should be added to a 382 /// diagnostic complaining about the given function being deleted or 383 /// unavailable. 384 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 385 std::string Message; 386 if (FD->getAvailability(&Message)) 387 return ": " + Message; 388 389 return std::string(); 390 } 391 392 /// DiagnoseSentinelCalls - This routine checks whether a call or 393 /// message-send is to a declaration with the sentinel attribute, and 394 /// if so, it checks that the requirements of the sentinel are 395 /// satisfied. 396 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 397 ArrayRef<Expr *> Args) { 398 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 399 if (!attr) 400 return; 401 402 // The number of formal parameters of the declaration. 403 unsigned numFormalParams; 404 405 // The kind of declaration. This is also an index into a %select in 406 // the diagnostic. 407 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 408 409 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 410 numFormalParams = MD->param_size(); 411 calleeType = CT_Method; 412 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 413 numFormalParams = FD->param_size(); 414 calleeType = CT_Function; 415 } else if (isa<VarDecl>(D)) { 416 QualType type = cast<ValueDecl>(D)->getType(); 417 const FunctionType *fn = nullptr; 418 if (const PointerType *ptr = type->getAs<PointerType>()) { 419 fn = ptr->getPointeeType()->getAs<FunctionType>(); 420 if (!fn) return; 421 calleeType = CT_Function; 422 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 423 fn = ptr->getPointeeType()->castAs<FunctionType>(); 424 calleeType = CT_Block; 425 } else { 426 return; 427 } 428 429 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 430 numFormalParams = proto->getNumParams(); 431 } else { 432 numFormalParams = 0; 433 } 434 } else { 435 return; 436 } 437 438 // "nullPos" is the number of formal parameters at the end which 439 // effectively count as part of the variadic arguments. This is 440 // useful if you would prefer to not have *any* formal parameters, 441 // but the language forces you to have at least one. 442 unsigned nullPos = attr->getNullPos(); 443 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 444 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 445 446 // The number of arguments which should follow the sentinel. 447 unsigned numArgsAfterSentinel = attr->getSentinel(); 448 449 // If there aren't enough arguments for all the formal parameters, 450 // the sentinel, and the args after the sentinel, complain. 451 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 452 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 453 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 454 return; 455 } 456 457 // Otherwise, find the sentinel expression. 458 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 459 if (!sentinelExpr) return; 460 if (sentinelExpr->isValueDependent()) return; 461 if (Context.isSentinelNullExpr(sentinelExpr)) return; 462 463 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 464 // or 'NULL' if those are actually defined in the context. Only use 465 // 'nil' for ObjC methods, where it's much more likely that the 466 // variadic arguments form a list of object pointers. 467 SourceLocation MissingNilLoc 468 = getLocForEndOfToken(sentinelExpr->getLocEnd()); 469 std::string NullValue; 470 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 471 NullValue = "nil"; 472 else if (getLangOpts().CPlusPlus11) 473 NullValue = "nullptr"; 474 else if (PP.isMacroDefined("NULL")) 475 NullValue = "NULL"; 476 else 477 NullValue = "(void*) 0"; 478 479 if (MissingNilLoc.isInvalid()) 480 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 481 else 482 Diag(MissingNilLoc, diag::warn_missing_sentinel) 483 << int(calleeType) 484 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 485 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 486 } 487 488 SourceRange Sema::getExprRange(Expr *E) const { 489 return E ? E->getSourceRange() : SourceRange(); 490 } 491 492 //===----------------------------------------------------------------------===// 493 // Standard Promotions and Conversions 494 //===----------------------------------------------------------------------===// 495 496 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 497 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 498 // Handle any placeholder expressions which made it here. 499 if (E->getType()->isPlaceholderType()) { 500 ExprResult result = CheckPlaceholderExpr(E); 501 if (result.isInvalid()) return ExprError(); 502 E = result.get(); 503 } 504 505 QualType Ty = E->getType(); 506 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 507 508 if (Ty->isFunctionType()) { 509 // If we are here, we are not calling a function but taking 510 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 511 if (getLangOpts().OpenCL) { 512 if (Diagnose) 513 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 514 return ExprError(); 515 } 516 517 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 518 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 519 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 520 return ExprError(); 521 522 E = ImpCastExprToType(E, Context.getPointerType(Ty), 523 CK_FunctionToPointerDecay).get(); 524 } else if (Ty->isArrayType()) { 525 // In C90 mode, arrays only promote to pointers if the array expression is 526 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 527 // type 'array of type' is converted to an expression that has type 'pointer 528 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 529 // that has type 'array of type' ...". The relevant change is "an lvalue" 530 // (C90) to "an expression" (C99). 531 // 532 // C++ 4.2p1: 533 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 534 // T" can be converted to an rvalue of type "pointer to T". 535 // 536 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 537 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 538 CK_ArrayToPointerDecay).get(); 539 } 540 return E; 541 } 542 543 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 544 // Check to see if we are dereferencing a null pointer. If so, 545 // and if not volatile-qualified, this is undefined behavior that the 546 // optimizer will delete, so warn about it. People sometimes try to use this 547 // to get a deterministic trap and are surprised by clang's behavior. This 548 // only handles the pattern "*null", which is a very syntactic check. 549 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 550 if (UO->getOpcode() == UO_Deref && 551 UO->getSubExpr()->IgnoreParenCasts()-> 552 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 553 !UO->getType().isVolatileQualified()) { 554 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 555 S.PDiag(diag::warn_indirection_through_null) 556 << UO->getSubExpr()->getSourceRange()); 557 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 558 S.PDiag(diag::note_indirection_through_null)); 559 } 560 } 561 562 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 563 SourceLocation AssignLoc, 564 const Expr* RHS) { 565 const ObjCIvarDecl *IV = OIRE->getDecl(); 566 if (!IV) 567 return; 568 569 DeclarationName MemberName = IV->getDeclName(); 570 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 571 if (!Member || !Member->isStr("isa")) 572 return; 573 574 const Expr *Base = OIRE->getBase(); 575 QualType BaseType = Base->getType(); 576 if (OIRE->isArrow()) 577 BaseType = BaseType->getPointeeType(); 578 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 579 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 580 ObjCInterfaceDecl *ClassDeclared = nullptr; 581 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 582 if (!ClassDeclared->getSuperClass() 583 && (*ClassDeclared->ivar_begin()) == IV) { 584 if (RHS) { 585 NamedDecl *ObjectSetClass = 586 S.LookupSingleName(S.TUScope, 587 &S.Context.Idents.get("object_setClass"), 588 SourceLocation(), S.LookupOrdinaryName); 589 if (ObjectSetClass) { 590 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 591 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 592 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 593 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 594 AssignLoc), ",") << 595 FixItHint::CreateInsertion(RHSLocEnd, ")"); 596 } 597 else 598 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 599 } else { 600 NamedDecl *ObjectGetClass = 601 S.LookupSingleName(S.TUScope, 602 &S.Context.Idents.get("object_getClass"), 603 SourceLocation(), S.LookupOrdinaryName); 604 if (ObjectGetClass) 605 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 606 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 607 FixItHint::CreateReplacement( 608 SourceRange(OIRE->getOpLoc(), 609 OIRE->getLocEnd()), ")"); 610 else 611 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 612 } 613 S.Diag(IV->getLocation(), diag::note_ivar_decl); 614 } 615 } 616 } 617 618 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 619 // Handle any placeholder expressions which made it here. 620 if (E->getType()->isPlaceholderType()) { 621 ExprResult result = CheckPlaceholderExpr(E); 622 if (result.isInvalid()) return ExprError(); 623 E = result.get(); 624 } 625 626 // C++ [conv.lval]p1: 627 // A glvalue of a non-function, non-array type T can be 628 // converted to a prvalue. 629 if (!E->isGLValue()) return E; 630 631 QualType T = E->getType(); 632 assert(!T.isNull() && "r-value conversion on typeless expression?"); 633 634 // We don't want to throw lvalue-to-rvalue casts on top of 635 // expressions of certain types in C++. 636 if (getLangOpts().CPlusPlus && 637 (E->getType() == Context.OverloadTy || 638 T->isDependentType() || 639 T->isRecordType())) 640 return E; 641 642 // The C standard is actually really unclear on this point, and 643 // DR106 tells us what the result should be but not why. It's 644 // generally best to say that void types just doesn't undergo 645 // lvalue-to-rvalue at all. Note that expressions of unqualified 646 // 'void' type are never l-values, but qualified void can be. 647 if (T->isVoidType()) 648 return E; 649 650 // OpenCL usually rejects direct accesses to values of 'half' type. 651 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 652 T->isHalfType()) { 653 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 654 << 0 << T; 655 return ExprError(); 656 } 657 658 CheckForNullPointerDereference(*this, E); 659 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 660 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 661 &Context.Idents.get("object_getClass"), 662 SourceLocation(), LookupOrdinaryName); 663 if (ObjectGetClass) 664 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 665 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 666 FixItHint::CreateReplacement( 667 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 668 else 669 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 670 } 671 else if (const ObjCIvarRefExpr *OIRE = 672 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 673 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 674 675 // C++ [conv.lval]p1: 676 // [...] If T is a non-class type, the type of the prvalue is the 677 // cv-unqualified version of T. Otherwise, the type of the 678 // rvalue is T. 679 // 680 // C99 6.3.2.1p2: 681 // If the lvalue has qualified type, the value has the unqualified 682 // version of the type of the lvalue; otherwise, the value has the 683 // type of the lvalue. 684 if (T.hasQualifiers()) 685 T = T.getUnqualifiedType(); 686 687 // Under the MS ABI, lock down the inheritance model now. 688 if (T->isMemberPointerType() && 689 Context.getTargetInfo().getCXXABI().isMicrosoft()) 690 (void)isCompleteType(E->getExprLoc(), T); 691 692 UpdateMarkingForLValueToRValue(E); 693 694 // Loading a __weak object implicitly retains the value, so we need a cleanup to 695 // balance that. 696 if (getLangOpts().ObjCAutoRefCount && 697 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 698 ExprNeedsCleanups = true; 699 700 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 701 nullptr, VK_RValue); 702 703 // C11 6.3.2.1p2: 704 // ... if the lvalue has atomic type, the value has the non-atomic version 705 // of the type of the lvalue ... 706 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 707 T = Atomic->getValueType().getUnqualifiedType(); 708 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 709 nullptr, VK_RValue); 710 } 711 712 return Res; 713 } 714 715 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 716 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 717 if (Res.isInvalid()) 718 return ExprError(); 719 Res = DefaultLvalueConversion(Res.get()); 720 if (Res.isInvalid()) 721 return ExprError(); 722 return Res; 723 } 724 725 /// CallExprUnaryConversions - a special case of an unary conversion 726 /// performed on a function designator of a call expression. 727 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 728 QualType Ty = E->getType(); 729 ExprResult Res = E; 730 // Only do implicit cast for a function type, but not for a pointer 731 // to function type. 732 if (Ty->isFunctionType()) { 733 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 734 CK_FunctionToPointerDecay).get(); 735 if (Res.isInvalid()) 736 return ExprError(); 737 } 738 Res = DefaultLvalueConversion(Res.get()); 739 if (Res.isInvalid()) 740 return ExprError(); 741 return Res.get(); 742 } 743 744 /// UsualUnaryConversions - Performs various conversions that are common to most 745 /// operators (C99 6.3). The conversions of array and function types are 746 /// sometimes suppressed. For example, the array->pointer conversion doesn't 747 /// apply if the array is an argument to the sizeof or address (&) operators. 748 /// In these instances, this routine should *not* be called. 749 ExprResult Sema::UsualUnaryConversions(Expr *E) { 750 // First, convert to an r-value. 751 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 752 if (Res.isInvalid()) 753 return ExprError(); 754 E = Res.get(); 755 756 QualType Ty = E->getType(); 757 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 758 759 // Half FP have to be promoted to float unless it is natively supported 760 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 761 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 762 763 // Try to perform integral promotions if the object has a theoretically 764 // promotable type. 765 if (Ty->isIntegralOrUnscopedEnumerationType()) { 766 // C99 6.3.1.1p2: 767 // 768 // The following may be used in an expression wherever an int or 769 // unsigned int may be used: 770 // - an object or expression with an integer type whose integer 771 // conversion rank is less than or equal to the rank of int 772 // and unsigned int. 773 // - A bit-field of type _Bool, int, signed int, or unsigned int. 774 // 775 // If an int can represent all values of the original type, the 776 // value is converted to an int; otherwise, it is converted to an 777 // unsigned int. These are called the integer promotions. All 778 // other types are unchanged by the integer promotions. 779 780 QualType PTy = Context.isPromotableBitField(E); 781 if (!PTy.isNull()) { 782 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 783 return E; 784 } 785 if (Ty->isPromotableIntegerType()) { 786 QualType PT = Context.getPromotedIntegerType(Ty); 787 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 788 return E; 789 } 790 } 791 return E; 792 } 793 794 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 795 /// do not have a prototype. Arguments that have type float or __fp16 796 /// are promoted to double. All other argument types are converted by 797 /// UsualUnaryConversions(). 798 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 799 QualType Ty = E->getType(); 800 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 801 802 ExprResult Res = UsualUnaryConversions(E); 803 if (Res.isInvalid()) 804 return ExprError(); 805 E = Res.get(); 806 807 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 808 // double. 809 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 810 if (BTy && (BTy->getKind() == BuiltinType::Half || 811 BTy->getKind() == BuiltinType::Float)) 812 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 813 814 // C++ performs lvalue-to-rvalue conversion as a default argument 815 // promotion, even on class types, but note: 816 // C++11 [conv.lval]p2: 817 // When an lvalue-to-rvalue conversion occurs in an unevaluated 818 // operand or a subexpression thereof the value contained in the 819 // referenced object is not accessed. Otherwise, if the glvalue 820 // has a class type, the conversion copy-initializes a temporary 821 // of type T from the glvalue and the result of the conversion 822 // is a prvalue for the temporary. 823 // FIXME: add some way to gate this entire thing for correctness in 824 // potentially potentially evaluated contexts. 825 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 826 ExprResult Temp = PerformCopyInitialization( 827 InitializedEntity::InitializeTemporary(E->getType()), 828 E->getExprLoc(), E); 829 if (Temp.isInvalid()) 830 return ExprError(); 831 E = Temp.get(); 832 } 833 834 return E; 835 } 836 837 /// Determine the degree of POD-ness for an expression. 838 /// Incomplete types are considered POD, since this check can be performed 839 /// when we're in an unevaluated context. 840 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 841 if (Ty->isIncompleteType()) { 842 // C++11 [expr.call]p7: 843 // After these conversions, if the argument does not have arithmetic, 844 // enumeration, pointer, pointer to member, or class type, the program 845 // is ill-formed. 846 // 847 // Since we've already performed array-to-pointer and function-to-pointer 848 // decay, the only such type in C++ is cv void. This also handles 849 // initializer lists as variadic arguments. 850 if (Ty->isVoidType()) 851 return VAK_Invalid; 852 853 if (Ty->isObjCObjectType()) 854 return VAK_Invalid; 855 return VAK_Valid; 856 } 857 858 if (Ty.isCXX98PODType(Context)) 859 return VAK_Valid; 860 861 // C++11 [expr.call]p7: 862 // Passing a potentially-evaluated argument of class type (Clause 9) 863 // having a non-trivial copy constructor, a non-trivial move constructor, 864 // or a non-trivial destructor, with no corresponding parameter, 865 // is conditionally-supported with implementation-defined semantics. 866 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 867 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 868 if (!Record->hasNonTrivialCopyConstructor() && 869 !Record->hasNonTrivialMoveConstructor() && 870 !Record->hasNonTrivialDestructor()) 871 return VAK_ValidInCXX11; 872 873 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 874 return VAK_Valid; 875 876 if (Ty->isObjCObjectType()) 877 return VAK_Invalid; 878 879 if (getLangOpts().MSVCCompat) 880 return VAK_MSVCUndefined; 881 882 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 883 // permitted to reject them. We should consider doing so. 884 return VAK_Undefined; 885 } 886 887 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 888 // Don't allow one to pass an Objective-C interface to a vararg. 889 const QualType &Ty = E->getType(); 890 VarArgKind VAK = isValidVarArgType(Ty); 891 892 // Complain about passing non-POD types through varargs. 893 switch (VAK) { 894 case VAK_ValidInCXX11: 895 DiagRuntimeBehavior( 896 E->getLocStart(), nullptr, 897 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 898 << Ty << CT); 899 // Fall through. 900 case VAK_Valid: 901 if (Ty->isRecordType()) { 902 // This is unlikely to be what the user intended. If the class has a 903 // 'c_str' member function, the user probably meant to call that. 904 DiagRuntimeBehavior(E->getLocStart(), nullptr, 905 PDiag(diag::warn_pass_class_arg_to_vararg) 906 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 907 } 908 break; 909 910 case VAK_Undefined: 911 case VAK_MSVCUndefined: 912 DiagRuntimeBehavior( 913 E->getLocStart(), nullptr, 914 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 915 << getLangOpts().CPlusPlus11 << Ty << CT); 916 break; 917 918 case VAK_Invalid: 919 if (Ty->isObjCObjectType()) 920 DiagRuntimeBehavior( 921 E->getLocStart(), nullptr, 922 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 923 << Ty << CT); 924 else 925 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 926 << isa<InitListExpr>(E) << Ty << CT; 927 break; 928 } 929 } 930 931 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 932 /// will create a trap if the resulting type is not a POD type. 933 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 934 FunctionDecl *FDecl) { 935 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 936 // Strip the unbridged-cast placeholder expression off, if applicable. 937 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 938 (CT == VariadicMethod || 939 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 940 E = stripARCUnbridgedCast(E); 941 942 // Otherwise, do normal placeholder checking. 943 } else { 944 ExprResult ExprRes = CheckPlaceholderExpr(E); 945 if (ExprRes.isInvalid()) 946 return ExprError(); 947 E = ExprRes.get(); 948 } 949 } 950 951 ExprResult ExprRes = DefaultArgumentPromotion(E); 952 if (ExprRes.isInvalid()) 953 return ExprError(); 954 E = ExprRes.get(); 955 956 // Diagnostics regarding non-POD argument types are 957 // emitted along with format string checking in Sema::CheckFunctionCall(). 958 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 959 // Turn this into a trap. 960 CXXScopeSpec SS; 961 SourceLocation TemplateKWLoc; 962 UnqualifiedId Name; 963 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 964 E->getLocStart()); 965 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 966 Name, true, false); 967 if (TrapFn.isInvalid()) 968 return ExprError(); 969 970 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 971 E->getLocStart(), None, 972 E->getLocEnd()); 973 if (Call.isInvalid()) 974 return ExprError(); 975 976 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 977 Call.get(), E); 978 if (Comma.isInvalid()) 979 return ExprError(); 980 return Comma.get(); 981 } 982 983 if (!getLangOpts().CPlusPlus && 984 RequireCompleteType(E->getExprLoc(), E->getType(), 985 diag::err_call_incomplete_argument)) 986 return ExprError(); 987 988 return E; 989 } 990 991 /// \brief Converts an integer to complex float type. Helper function of 992 /// UsualArithmeticConversions() 993 /// 994 /// \return false if the integer expression is an integer type and is 995 /// successfully converted to the complex type. 996 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 997 ExprResult &ComplexExpr, 998 QualType IntTy, 999 QualType ComplexTy, 1000 bool SkipCast) { 1001 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1002 if (SkipCast) return false; 1003 if (IntTy->isIntegerType()) { 1004 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1005 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1006 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1007 CK_FloatingRealToComplex); 1008 } else { 1009 assert(IntTy->isComplexIntegerType()); 1010 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1011 CK_IntegralComplexToFloatingComplex); 1012 } 1013 return false; 1014 } 1015 1016 /// \brief Handle arithmetic conversion with complex types. Helper function of 1017 /// UsualArithmeticConversions() 1018 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1019 ExprResult &RHS, QualType LHSType, 1020 QualType RHSType, 1021 bool IsCompAssign) { 1022 // if we have an integer operand, the result is the complex type. 1023 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1024 /*skipCast*/false)) 1025 return LHSType; 1026 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1027 /*skipCast*/IsCompAssign)) 1028 return RHSType; 1029 1030 // This handles complex/complex, complex/float, or float/complex. 1031 // When both operands are complex, the shorter operand is converted to the 1032 // type of the longer, and that is the type of the result. This corresponds 1033 // to what is done when combining two real floating-point operands. 1034 // The fun begins when size promotion occur across type domains. 1035 // From H&S 6.3.4: When one operand is complex and the other is a real 1036 // floating-point type, the less precise type is converted, within it's 1037 // real or complex domain, to the precision of the other type. For example, 1038 // when combining a "long double" with a "double _Complex", the 1039 // "double _Complex" is promoted to "long double _Complex". 1040 1041 // Compute the rank of the two types, regardless of whether they are complex. 1042 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1043 1044 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1045 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1046 QualType LHSElementType = 1047 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1048 QualType RHSElementType = 1049 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1050 1051 QualType ResultType = S.Context.getComplexType(LHSElementType); 1052 if (Order < 0) { 1053 // Promote the precision of the LHS if not an assignment. 1054 ResultType = S.Context.getComplexType(RHSElementType); 1055 if (!IsCompAssign) { 1056 if (LHSComplexType) 1057 LHS = 1058 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1059 else 1060 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1061 } 1062 } else if (Order > 0) { 1063 // Promote the precision of the RHS. 1064 if (RHSComplexType) 1065 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1066 else 1067 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1068 } 1069 return ResultType; 1070 } 1071 1072 /// \brief Hande arithmetic conversion from integer to float. Helper function 1073 /// of UsualArithmeticConversions() 1074 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1075 ExprResult &IntExpr, 1076 QualType FloatTy, QualType IntTy, 1077 bool ConvertFloat, bool ConvertInt) { 1078 if (IntTy->isIntegerType()) { 1079 if (ConvertInt) 1080 // Convert intExpr to the lhs floating point type. 1081 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1082 CK_IntegralToFloating); 1083 return FloatTy; 1084 } 1085 1086 // Convert both sides to the appropriate complex float. 1087 assert(IntTy->isComplexIntegerType()); 1088 QualType result = S.Context.getComplexType(FloatTy); 1089 1090 // _Complex int -> _Complex float 1091 if (ConvertInt) 1092 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1093 CK_IntegralComplexToFloatingComplex); 1094 1095 // float -> _Complex float 1096 if (ConvertFloat) 1097 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1098 CK_FloatingRealToComplex); 1099 1100 return result; 1101 } 1102 1103 /// \brief Handle arithmethic conversion with floating point types. Helper 1104 /// function of UsualArithmeticConversions() 1105 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1106 ExprResult &RHS, QualType LHSType, 1107 QualType RHSType, bool IsCompAssign) { 1108 bool LHSFloat = LHSType->isRealFloatingType(); 1109 bool RHSFloat = RHSType->isRealFloatingType(); 1110 1111 // If we have two real floating types, convert the smaller operand 1112 // to the bigger result. 1113 if (LHSFloat && RHSFloat) { 1114 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1115 if (order > 0) { 1116 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1117 return LHSType; 1118 } 1119 1120 assert(order < 0 && "illegal float comparison"); 1121 if (!IsCompAssign) 1122 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1123 return RHSType; 1124 } 1125 1126 if (LHSFloat) { 1127 // Half FP has to be promoted to float unless it is natively supported 1128 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1129 LHSType = S.Context.FloatTy; 1130 1131 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1132 /*convertFloat=*/!IsCompAssign, 1133 /*convertInt=*/ true); 1134 } 1135 assert(RHSFloat); 1136 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1137 /*convertInt=*/ true, 1138 /*convertFloat=*/!IsCompAssign); 1139 } 1140 1141 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1142 1143 namespace { 1144 /// These helper callbacks are placed in an anonymous namespace to 1145 /// permit their use as function template parameters. 1146 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1147 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1148 } 1149 1150 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1151 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1152 CK_IntegralComplexCast); 1153 } 1154 } 1155 1156 /// \brief Handle integer arithmetic conversions. Helper function of 1157 /// UsualArithmeticConversions() 1158 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1159 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1160 ExprResult &RHS, QualType LHSType, 1161 QualType RHSType, bool IsCompAssign) { 1162 // The rules for this case are in C99 6.3.1.8 1163 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1164 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1165 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1166 if (LHSSigned == RHSSigned) { 1167 // Same signedness; use the higher-ranked type 1168 if (order >= 0) { 1169 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1170 return LHSType; 1171 } else if (!IsCompAssign) 1172 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1173 return RHSType; 1174 } else if (order != (LHSSigned ? 1 : -1)) { 1175 // The unsigned type has greater than or equal rank to the 1176 // signed type, so use the unsigned type 1177 if (RHSSigned) { 1178 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1179 return LHSType; 1180 } else if (!IsCompAssign) 1181 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1182 return RHSType; 1183 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1184 // The two types are different widths; if we are here, that 1185 // means the signed type is larger than the unsigned type, so 1186 // use the signed type. 1187 if (LHSSigned) { 1188 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1189 return LHSType; 1190 } else if (!IsCompAssign) 1191 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1192 return RHSType; 1193 } else { 1194 // The signed type is higher-ranked than the unsigned type, 1195 // but isn't actually any bigger (like unsigned int and long 1196 // on most 32-bit systems). Use the unsigned type corresponding 1197 // to the signed type. 1198 QualType result = 1199 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1200 RHS = (*doRHSCast)(S, RHS.get(), result); 1201 if (!IsCompAssign) 1202 LHS = (*doLHSCast)(S, LHS.get(), result); 1203 return result; 1204 } 1205 } 1206 1207 /// \brief Handle conversions with GCC complex int extension. Helper function 1208 /// of UsualArithmeticConversions() 1209 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1210 ExprResult &RHS, QualType LHSType, 1211 QualType RHSType, 1212 bool IsCompAssign) { 1213 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1214 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1215 1216 if (LHSComplexInt && RHSComplexInt) { 1217 QualType LHSEltType = LHSComplexInt->getElementType(); 1218 QualType RHSEltType = RHSComplexInt->getElementType(); 1219 QualType ScalarType = 1220 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1221 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1222 1223 return S.Context.getComplexType(ScalarType); 1224 } 1225 1226 if (LHSComplexInt) { 1227 QualType LHSEltType = LHSComplexInt->getElementType(); 1228 QualType ScalarType = 1229 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1230 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1231 QualType ComplexType = S.Context.getComplexType(ScalarType); 1232 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1233 CK_IntegralRealToComplex); 1234 1235 return ComplexType; 1236 } 1237 1238 assert(RHSComplexInt); 1239 1240 QualType RHSEltType = RHSComplexInt->getElementType(); 1241 QualType ScalarType = 1242 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1243 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1244 QualType ComplexType = S.Context.getComplexType(ScalarType); 1245 1246 if (!IsCompAssign) 1247 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1248 CK_IntegralRealToComplex); 1249 return ComplexType; 1250 } 1251 1252 /// UsualArithmeticConversions - Performs various conversions that are common to 1253 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1254 /// routine returns the first non-arithmetic type found. The client is 1255 /// responsible for emitting appropriate error diagnostics. 1256 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1257 bool IsCompAssign) { 1258 if (!IsCompAssign) { 1259 LHS = UsualUnaryConversions(LHS.get()); 1260 if (LHS.isInvalid()) 1261 return QualType(); 1262 } 1263 1264 RHS = UsualUnaryConversions(RHS.get()); 1265 if (RHS.isInvalid()) 1266 return QualType(); 1267 1268 // For conversion purposes, we ignore any qualifiers. 1269 // For example, "const float" and "float" are equivalent. 1270 QualType LHSType = 1271 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1272 QualType RHSType = 1273 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1274 1275 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1276 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1277 LHSType = AtomicLHS->getValueType(); 1278 1279 // If both types are identical, no conversion is needed. 1280 if (LHSType == RHSType) 1281 return LHSType; 1282 1283 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1284 // The caller can deal with this (e.g. pointer + int). 1285 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1286 return QualType(); 1287 1288 // Apply unary and bitfield promotions to the LHS's type. 1289 QualType LHSUnpromotedType = LHSType; 1290 if (LHSType->isPromotableIntegerType()) 1291 LHSType = Context.getPromotedIntegerType(LHSType); 1292 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1293 if (!LHSBitfieldPromoteTy.isNull()) 1294 LHSType = LHSBitfieldPromoteTy; 1295 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1296 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1297 1298 // If both types are identical, no conversion is needed. 1299 if (LHSType == RHSType) 1300 return LHSType; 1301 1302 // At this point, we have two different arithmetic types. 1303 1304 // Handle complex types first (C99 6.3.1.8p1). 1305 if (LHSType->isComplexType() || RHSType->isComplexType()) 1306 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1307 IsCompAssign); 1308 1309 // Now handle "real" floating types (i.e. float, double, long double). 1310 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1311 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1312 IsCompAssign); 1313 1314 // Handle GCC complex int extension. 1315 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1316 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1317 IsCompAssign); 1318 1319 // Finally, we have two differing integer types. 1320 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1321 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1322 } 1323 1324 1325 //===----------------------------------------------------------------------===// 1326 // Semantic Analysis for various Expression Types 1327 //===----------------------------------------------------------------------===// 1328 1329 1330 ExprResult 1331 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1332 SourceLocation DefaultLoc, 1333 SourceLocation RParenLoc, 1334 Expr *ControllingExpr, 1335 ArrayRef<ParsedType> ArgTypes, 1336 ArrayRef<Expr *> ArgExprs) { 1337 unsigned NumAssocs = ArgTypes.size(); 1338 assert(NumAssocs == ArgExprs.size()); 1339 1340 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1341 for (unsigned i = 0; i < NumAssocs; ++i) { 1342 if (ArgTypes[i]) 1343 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1344 else 1345 Types[i] = nullptr; 1346 } 1347 1348 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1349 ControllingExpr, 1350 llvm::makeArrayRef(Types, NumAssocs), 1351 ArgExprs); 1352 delete [] Types; 1353 return ER; 1354 } 1355 1356 ExprResult 1357 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1358 SourceLocation DefaultLoc, 1359 SourceLocation RParenLoc, 1360 Expr *ControllingExpr, 1361 ArrayRef<TypeSourceInfo *> Types, 1362 ArrayRef<Expr *> Exprs) { 1363 unsigned NumAssocs = Types.size(); 1364 assert(NumAssocs == Exprs.size()); 1365 1366 // Decay and strip qualifiers for the controlling expression type, and handle 1367 // placeholder type replacement. See committee discussion from WG14 DR423. 1368 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1369 if (R.isInvalid()) 1370 return ExprError(); 1371 ControllingExpr = R.get(); 1372 1373 // The controlling expression is an unevaluated operand, so side effects are 1374 // likely unintended. 1375 if (ActiveTemplateInstantiations.empty() && 1376 ControllingExpr->HasSideEffects(Context, false)) 1377 Diag(ControllingExpr->getExprLoc(), 1378 diag::warn_side_effects_unevaluated_context); 1379 1380 bool TypeErrorFound = false, 1381 IsResultDependent = ControllingExpr->isTypeDependent(), 1382 ContainsUnexpandedParameterPack 1383 = ControllingExpr->containsUnexpandedParameterPack(); 1384 1385 for (unsigned i = 0; i < NumAssocs; ++i) { 1386 if (Exprs[i]->containsUnexpandedParameterPack()) 1387 ContainsUnexpandedParameterPack = true; 1388 1389 if (Types[i]) { 1390 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1391 ContainsUnexpandedParameterPack = true; 1392 1393 if (Types[i]->getType()->isDependentType()) { 1394 IsResultDependent = true; 1395 } else { 1396 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1397 // complete object type other than a variably modified type." 1398 unsigned D = 0; 1399 if (Types[i]->getType()->isIncompleteType()) 1400 D = diag::err_assoc_type_incomplete; 1401 else if (!Types[i]->getType()->isObjectType()) 1402 D = diag::err_assoc_type_nonobject; 1403 else if (Types[i]->getType()->isVariablyModifiedType()) 1404 D = diag::err_assoc_type_variably_modified; 1405 1406 if (D != 0) { 1407 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1408 << Types[i]->getTypeLoc().getSourceRange() 1409 << Types[i]->getType(); 1410 TypeErrorFound = true; 1411 } 1412 1413 // C11 6.5.1.1p2 "No two generic associations in the same generic 1414 // selection shall specify compatible types." 1415 for (unsigned j = i+1; j < NumAssocs; ++j) 1416 if (Types[j] && !Types[j]->getType()->isDependentType() && 1417 Context.typesAreCompatible(Types[i]->getType(), 1418 Types[j]->getType())) { 1419 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1420 diag::err_assoc_compatible_types) 1421 << Types[j]->getTypeLoc().getSourceRange() 1422 << Types[j]->getType() 1423 << Types[i]->getType(); 1424 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1425 diag::note_compat_assoc) 1426 << Types[i]->getTypeLoc().getSourceRange() 1427 << Types[i]->getType(); 1428 TypeErrorFound = true; 1429 } 1430 } 1431 } 1432 } 1433 if (TypeErrorFound) 1434 return ExprError(); 1435 1436 // If we determined that the generic selection is result-dependent, don't 1437 // try to compute the result expression. 1438 if (IsResultDependent) 1439 return new (Context) GenericSelectionExpr( 1440 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1441 ContainsUnexpandedParameterPack); 1442 1443 SmallVector<unsigned, 1> CompatIndices; 1444 unsigned DefaultIndex = -1U; 1445 for (unsigned i = 0; i < NumAssocs; ++i) { 1446 if (!Types[i]) 1447 DefaultIndex = i; 1448 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1449 Types[i]->getType())) 1450 CompatIndices.push_back(i); 1451 } 1452 1453 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1454 // type compatible with at most one of the types named in its generic 1455 // association list." 1456 if (CompatIndices.size() > 1) { 1457 // We strip parens here because the controlling expression is typically 1458 // parenthesized in macro definitions. 1459 ControllingExpr = ControllingExpr->IgnoreParens(); 1460 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1461 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1462 << (unsigned) CompatIndices.size(); 1463 for (unsigned I : CompatIndices) { 1464 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1465 diag::note_compat_assoc) 1466 << Types[I]->getTypeLoc().getSourceRange() 1467 << Types[I]->getType(); 1468 } 1469 return ExprError(); 1470 } 1471 1472 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1473 // its controlling expression shall have type compatible with exactly one of 1474 // the types named in its generic association list." 1475 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1476 // We strip parens here because the controlling expression is typically 1477 // parenthesized in macro definitions. 1478 ControllingExpr = ControllingExpr->IgnoreParens(); 1479 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1480 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1481 return ExprError(); 1482 } 1483 1484 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1485 // type name that is compatible with the type of the controlling expression, 1486 // then the result expression of the generic selection is the expression 1487 // in that generic association. Otherwise, the result expression of the 1488 // generic selection is the expression in the default generic association." 1489 unsigned ResultIndex = 1490 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1491 1492 return new (Context) GenericSelectionExpr( 1493 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1494 ContainsUnexpandedParameterPack, ResultIndex); 1495 } 1496 1497 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1498 /// location of the token and the offset of the ud-suffix within it. 1499 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1500 unsigned Offset) { 1501 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1502 S.getLangOpts()); 1503 } 1504 1505 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1506 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1507 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1508 IdentifierInfo *UDSuffix, 1509 SourceLocation UDSuffixLoc, 1510 ArrayRef<Expr*> Args, 1511 SourceLocation LitEndLoc) { 1512 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1513 1514 QualType ArgTy[2]; 1515 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1516 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1517 if (ArgTy[ArgIdx]->isArrayType()) 1518 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1519 } 1520 1521 DeclarationName OpName = 1522 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1523 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1524 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1525 1526 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1527 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1528 /*AllowRaw*/false, /*AllowTemplate*/false, 1529 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1530 return ExprError(); 1531 1532 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1533 } 1534 1535 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1536 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1537 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1538 /// multiple tokens. However, the common case is that StringToks points to one 1539 /// string. 1540 /// 1541 ExprResult 1542 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1543 assert(!StringToks.empty() && "Must have at least one string!"); 1544 1545 StringLiteralParser Literal(StringToks, PP); 1546 if (Literal.hadError) 1547 return ExprError(); 1548 1549 SmallVector<SourceLocation, 4> StringTokLocs; 1550 for (const Token &Tok : StringToks) 1551 StringTokLocs.push_back(Tok.getLocation()); 1552 1553 QualType CharTy = Context.CharTy; 1554 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1555 if (Literal.isWide()) { 1556 CharTy = Context.getWideCharType(); 1557 Kind = StringLiteral::Wide; 1558 } else if (Literal.isUTF8()) { 1559 Kind = StringLiteral::UTF8; 1560 } else if (Literal.isUTF16()) { 1561 CharTy = Context.Char16Ty; 1562 Kind = StringLiteral::UTF16; 1563 } else if (Literal.isUTF32()) { 1564 CharTy = Context.Char32Ty; 1565 Kind = StringLiteral::UTF32; 1566 } else if (Literal.isPascal()) { 1567 CharTy = Context.UnsignedCharTy; 1568 } 1569 1570 QualType CharTyConst = CharTy; 1571 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1572 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1573 CharTyConst.addConst(); 1574 1575 // Get an array type for the string, according to C99 6.4.5. This includes 1576 // the nul terminator character as well as the string length for pascal 1577 // strings. 1578 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1579 llvm::APInt(32, Literal.GetNumStringChars()+1), 1580 ArrayType::Normal, 0); 1581 1582 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1583 if (getLangOpts().OpenCL) { 1584 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1585 } 1586 1587 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1588 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1589 Kind, Literal.Pascal, StrTy, 1590 &StringTokLocs[0], 1591 StringTokLocs.size()); 1592 if (Literal.getUDSuffix().empty()) 1593 return Lit; 1594 1595 // We're building a user-defined literal. 1596 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1597 SourceLocation UDSuffixLoc = 1598 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1599 Literal.getUDSuffixOffset()); 1600 1601 // Make sure we're allowed user-defined literals here. 1602 if (!UDLScope) 1603 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1604 1605 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1606 // operator "" X (str, len) 1607 QualType SizeType = Context.getSizeType(); 1608 1609 DeclarationName OpName = 1610 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1611 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1612 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1613 1614 QualType ArgTy[] = { 1615 Context.getArrayDecayedType(StrTy), SizeType 1616 }; 1617 1618 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1619 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1620 /*AllowRaw*/false, /*AllowTemplate*/false, 1621 /*AllowStringTemplate*/true)) { 1622 1623 case LOLR_Cooked: { 1624 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1625 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1626 StringTokLocs[0]); 1627 Expr *Args[] = { Lit, LenArg }; 1628 1629 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1630 } 1631 1632 case LOLR_StringTemplate: { 1633 TemplateArgumentListInfo ExplicitArgs; 1634 1635 unsigned CharBits = Context.getIntWidth(CharTy); 1636 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1637 llvm::APSInt Value(CharBits, CharIsUnsigned); 1638 1639 TemplateArgument TypeArg(CharTy); 1640 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1641 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1642 1643 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1644 Value = Lit->getCodeUnit(I); 1645 TemplateArgument Arg(Context, Value, CharTy); 1646 TemplateArgumentLocInfo ArgInfo; 1647 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1648 } 1649 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1650 &ExplicitArgs); 1651 } 1652 case LOLR_Raw: 1653 case LOLR_Template: 1654 llvm_unreachable("unexpected literal operator lookup result"); 1655 case LOLR_Error: 1656 return ExprError(); 1657 } 1658 llvm_unreachable("unexpected literal operator lookup result"); 1659 } 1660 1661 ExprResult 1662 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1663 SourceLocation Loc, 1664 const CXXScopeSpec *SS) { 1665 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1666 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1667 } 1668 1669 /// BuildDeclRefExpr - Build an expression that references a 1670 /// declaration that does not require a closure capture. 1671 ExprResult 1672 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1673 const DeclarationNameInfo &NameInfo, 1674 const CXXScopeSpec *SS, NamedDecl *FoundD, 1675 const TemplateArgumentListInfo *TemplateArgs) { 1676 if (getLangOpts().CUDA) 1677 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1678 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1679 if (CheckCUDATarget(Caller, Callee)) { 1680 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1681 << IdentifyCUDATarget(Callee) << D->getIdentifier() 1682 << IdentifyCUDATarget(Caller); 1683 Diag(D->getLocation(), diag::note_previous_decl) 1684 << D->getIdentifier(); 1685 return ExprError(); 1686 } 1687 } 1688 1689 bool RefersToCapturedVariable = 1690 isa<VarDecl>(D) && 1691 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1692 1693 DeclRefExpr *E; 1694 if (isa<VarTemplateSpecializationDecl>(D)) { 1695 VarTemplateSpecializationDecl *VarSpec = 1696 cast<VarTemplateSpecializationDecl>(D); 1697 1698 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1699 : NestedNameSpecifierLoc(), 1700 VarSpec->getTemplateKeywordLoc(), D, 1701 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1702 FoundD, TemplateArgs); 1703 } else { 1704 assert(!TemplateArgs && "No template arguments for non-variable" 1705 " template specialization references"); 1706 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1707 : NestedNameSpecifierLoc(), 1708 SourceLocation(), D, RefersToCapturedVariable, 1709 NameInfo, Ty, VK, FoundD); 1710 } 1711 1712 MarkDeclRefReferenced(E); 1713 1714 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1715 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1716 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1717 recordUseOfEvaluatedWeak(E); 1718 1719 // Just in case we're building an illegal pointer-to-member. 1720 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1721 if (FD && FD->isBitField()) 1722 E->setObjectKind(OK_BitField); 1723 1724 return E; 1725 } 1726 1727 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1728 /// possibly a list of template arguments. 1729 /// 1730 /// If this produces template arguments, it is permitted to call 1731 /// DecomposeTemplateName. 1732 /// 1733 /// This actually loses a lot of source location information for 1734 /// non-standard name kinds; we should consider preserving that in 1735 /// some way. 1736 void 1737 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1738 TemplateArgumentListInfo &Buffer, 1739 DeclarationNameInfo &NameInfo, 1740 const TemplateArgumentListInfo *&TemplateArgs) { 1741 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1742 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1743 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1744 1745 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1746 Id.TemplateId->NumArgs); 1747 translateTemplateArguments(TemplateArgsPtr, Buffer); 1748 1749 TemplateName TName = Id.TemplateId->Template.get(); 1750 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1751 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1752 TemplateArgs = &Buffer; 1753 } else { 1754 NameInfo = GetNameFromUnqualifiedId(Id); 1755 TemplateArgs = nullptr; 1756 } 1757 } 1758 1759 static void emitEmptyLookupTypoDiagnostic( 1760 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1761 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1762 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1763 DeclContext *Ctx = 1764 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1765 if (!TC) { 1766 // Emit a special diagnostic for failed member lookups. 1767 // FIXME: computing the declaration context might fail here (?) 1768 if (Ctx) 1769 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1770 << SS.getRange(); 1771 else 1772 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1773 return; 1774 } 1775 1776 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1777 bool DroppedSpecifier = 1778 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1779 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1780 ? diag::note_implicit_param_decl 1781 : diag::note_previous_decl; 1782 if (!Ctx) 1783 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1784 SemaRef.PDiag(NoteID)); 1785 else 1786 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1787 << Typo << Ctx << DroppedSpecifier 1788 << SS.getRange(), 1789 SemaRef.PDiag(NoteID)); 1790 } 1791 1792 /// Diagnose an empty lookup. 1793 /// 1794 /// \return false if new lookup candidates were found 1795 bool 1796 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1797 std::unique_ptr<CorrectionCandidateCallback> CCC, 1798 TemplateArgumentListInfo *ExplicitTemplateArgs, 1799 ArrayRef<Expr *> Args, TypoExpr **Out) { 1800 DeclarationName Name = R.getLookupName(); 1801 1802 unsigned diagnostic = diag::err_undeclared_var_use; 1803 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1804 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1805 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1806 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1807 diagnostic = diag::err_undeclared_use; 1808 diagnostic_suggest = diag::err_undeclared_use_suggest; 1809 } 1810 1811 // If the original lookup was an unqualified lookup, fake an 1812 // unqualified lookup. This is useful when (for example) the 1813 // original lookup would not have found something because it was a 1814 // dependent name. 1815 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1816 while (DC) { 1817 if (isa<CXXRecordDecl>(DC)) { 1818 LookupQualifiedName(R, DC); 1819 1820 if (!R.empty()) { 1821 // Don't give errors about ambiguities in this lookup. 1822 R.suppressDiagnostics(); 1823 1824 // During a default argument instantiation the CurContext points 1825 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1826 // function parameter list, hence add an explicit check. 1827 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1828 ActiveTemplateInstantiations.back().Kind == 1829 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1830 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1831 bool isInstance = CurMethod && 1832 CurMethod->isInstance() && 1833 DC == CurMethod->getParent() && !isDefaultArgument; 1834 1835 // Give a code modification hint to insert 'this->'. 1836 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1837 // Actually quite difficult! 1838 if (getLangOpts().MSVCCompat) 1839 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1840 if (isInstance) { 1841 Diag(R.getNameLoc(), diagnostic) << Name 1842 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1843 CheckCXXThisCapture(R.getNameLoc()); 1844 } else { 1845 Diag(R.getNameLoc(), diagnostic) << Name; 1846 } 1847 1848 // Do we really want to note all of these? 1849 for (NamedDecl *D : R) 1850 Diag(D->getLocation(), diag::note_dependent_var_use); 1851 1852 // Return true if we are inside a default argument instantiation 1853 // and the found name refers to an instance member function, otherwise 1854 // the function calling DiagnoseEmptyLookup will try to create an 1855 // implicit member call and this is wrong for default argument. 1856 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1857 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1858 return true; 1859 } 1860 1861 // Tell the callee to try to recover. 1862 return false; 1863 } 1864 1865 R.clear(); 1866 } 1867 1868 // In Microsoft mode, if we are performing lookup from within a friend 1869 // function definition declared at class scope then we must set 1870 // DC to the lexical parent to be able to search into the parent 1871 // class. 1872 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1873 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1874 DC->getLexicalParent()->isRecord()) 1875 DC = DC->getLexicalParent(); 1876 else 1877 DC = DC->getParent(); 1878 } 1879 1880 // We didn't find anything, so try to correct for a typo. 1881 TypoCorrection Corrected; 1882 if (S && Out) { 1883 SourceLocation TypoLoc = R.getNameLoc(); 1884 assert(!ExplicitTemplateArgs && 1885 "Diagnosing an empty lookup with explicit template args!"); 1886 *Out = CorrectTypoDelayed( 1887 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1888 [=](const TypoCorrection &TC) { 1889 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1890 diagnostic, diagnostic_suggest); 1891 }, 1892 nullptr, CTK_ErrorRecovery); 1893 if (*Out) 1894 return true; 1895 } else if (S && (Corrected = 1896 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1897 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1898 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1899 bool DroppedSpecifier = 1900 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1901 R.setLookupName(Corrected.getCorrection()); 1902 1903 bool AcceptableWithRecovery = false; 1904 bool AcceptableWithoutRecovery = false; 1905 NamedDecl *ND = Corrected.getFoundDecl(); 1906 if (ND) { 1907 if (Corrected.isOverloaded()) { 1908 OverloadCandidateSet OCS(R.getNameLoc(), 1909 OverloadCandidateSet::CSK_Normal); 1910 OverloadCandidateSet::iterator Best; 1911 for (NamedDecl *CD : Corrected) { 1912 if (FunctionTemplateDecl *FTD = 1913 dyn_cast<FunctionTemplateDecl>(CD)) 1914 AddTemplateOverloadCandidate( 1915 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1916 Args, OCS); 1917 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1918 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1919 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1920 Args, OCS); 1921 } 1922 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1923 case OR_Success: 1924 ND = Best->FoundDecl; 1925 Corrected.setCorrectionDecl(ND); 1926 break; 1927 default: 1928 // FIXME: Arbitrarily pick the first declaration for the note. 1929 Corrected.setCorrectionDecl(ND); 1930 break; 1931 } 1932 } 1933 R.addDecl(ND); 1934 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1935 CXXRecordDecl *Record = nullptr; 1936 if (Corrected.getCorrectionSpecifier()) { 1937 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1938 Record = Ty->getAsCXXRecordDecl(); 1939 } 1940 if (!Record) 1941 Record = cast<CXXRecordDecl>( 1942 ND->getDeclContext()->getRedeclContext()); 1943 R.setNamingClass(Record); 1944 } 1945 1946 auto *UnderlyingND = ND->getUnderlyingDecl(); 1947 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 1948 isa<FunctionTemplateDecl>(UnderlyingND); 1949 // FIXME: If we ended up with a typo for a type name or 1950 // Objective-C class name, we're in trouble because the parser 1951 // is in the wrong place to recover. Suggest the typo 1952 // correction, but don't make it a fix-it since we're not going 1953 // to recover well anyway. 1954 AcceptableWithoutRecovery = 1955 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 1956 } else { 1957 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1958 // because we aren't able to recover. 1959 AcceptableWithoutRecovery = true; 1960 } 1961 1962 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1963 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 1964 ? diag::note_implicit_param_decl 1965 : diag::note_previous_decl; 1966 if (SS.isEmpty()) 1967 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1968 PDiag(NoteID), AcceptableWithRecovery); 1969 else 1970 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1971 << Name << computeDeclContext(SS, false) 1972 << DroppedSpecifier << SS.getRange(), 1973 PDiag(NoteID), AcceptableWithRecovery); 1974 1975 // Tell the callee whether to try to recover. 1976 return !AcceptableWithRecovery; 1977 } 1978 } 1979 R.clear(); 1980 1981 // Emit a special diagnostic for failed member lookups. 1982 // FIXME: computing the declaration context might fail here (?) 1983 if (!SS.isEmpty()) { 1984 Diag(R.getNameLoc(), diag::err_no_member) 1985 << Name << computeDeclContext(SS, false) 1986 << SS.getRange(); 1987 return true; 1988 } 1989 1990 // Give up, we can't recover. 1991 Diag(R.getNameLoc(), diagnostic) << Name; 1992 return true; 1993 } 1994 1995 /// In Microsoft mode, if we are inside a template class whose parent class has 1996 /// dependent base classes, and we can't resolve an unqualified identifier, then 1997 /// assume the identifier is a member of a dependent base class. We can only 1998 /// recover successfully in static methods, instance methods, and other contexts 1999 /// where 'this' is available. This doesn't precisely match MSVC's 2000 /// instantiation model, but it's close enough. 2001 static Expr * 2002 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2003 DeclarationNameInfo &NameInfo, 2004 SourceLocation TemplateKWLoc, 2005 const TemplateArgumentListInfo *TemplateArgs) { 2006 // Only try to recover from lookup into dependent bases in static methods or 2007 // contexts where 'this' is available. 2008 QualType ThisType = S.getCurrentThisType(); 2009 const CXXRecordDecl *RD = nullptr; 2010 if (!ThisType.isNull()) 2011 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2012 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2013 RD = MD->getParent(); 2014 if (!RD || !RD->hasAnyDependentBases()) 2015 return nullptr; 2016 2017 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2018 // is available, suggest inserting 'this->' as a fixit. 2019 SourceLocation Loc = NameInfo.getLoc(); 2020 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2021 DB << NameInfo.getName() << RD; 2022 2023 if (!ThisType.isNull()) { 2024 DB << FixItHint::CreateInsertion(Loc, "this->"); 2025 return CXXDependentScopeMemberExpr::Create( 2026 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2027 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2028 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2029 } 2030 2031 // Synthesize a fake NNS that points to the derived class. This will 2032 // perform name lookup during template instantiation. 2033 CXXScopeSpec SS; 2034 auto *NNS = 2035 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2036 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2037 return DependentScopeDeclRefExpr::Create( 2038 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2039 TemplateArgs); 2040 } 2041 2042 ExprResult 2043 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2044 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2045 bool HasTrailingLParen, bool IsAddressOfOperand, 2046 std::unique_ptr<CorrectionCandidateCallback> CCC, 2047 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2048 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2049 "cannot be direct & operand and have a trailing lparen"); 2050 if (SS.isInvalid()) 2051 return ExprError(); 2052 2053 TemplateArgumentListInfo TemplateArgsBuffer; 2054 2055 // Decompose the UnqualifiedId into the following data. 2056 DeclarationNameInfo NameInfo; 2057 const TemplateArgumentListInfo *TemplateArgs; 2058 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2059 2060 DeclarationName Name = NameInfo.getName(); 2061 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2062 SourceLocation NameLoc = NameInfo.getLoc(); 2063 2064 // C++ [temp.dep.expr]p3: 2065 // An id-expression is type-dependent if it contains: 2066 // -- an identifier that was declared with a dependent type, 2067 // (note: handled after lookup) 2068 // -- a template-id that is dependent, 2069 // (note: handled in BuildTemplateIdExpr) 2070 // -- a conversion-function-id that specifies a dependent type, 2071 // -- a nested-name-specifier that contains a class-name that 2072 // names a dependent type. 2073 // Determine whether this is a member of an unknown specialization; 2074 // we need to handle these differently. 2075 bool DependentID = false; 2076 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2077 Name.getCXXNameType()->isDependentType()) { 2078 DependentID = true; 2079 } else if (SS.isSet()) { 2080 if (DeclContext *DC = computeDeclContext(SS, false)) { 2081 if (RequireCompleteDeclContext(SS, DC)) 2082 return ExprError(); 2083 } else { 2084 DependentID = true; 2085 } 2086 } 2087 2088 if (DependentID) 2089 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2090 IsAddressOfOperand, TemplateArgs); 2091 2092 // Perform the required lookup. 2093 LookupResult R(*this, NameInfo, 2094 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2095 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2096 if (TemplateArgs) { 2097 // Lookup the template name again to correctly establish the context in 2098 // which it was found. This is really unfortunate as we already did the 2099 // lookup to determine that it was a template name in the first place. If 2100 // this becomes a performance hit, we can work harder to preserve those 2101 // results until we get here but it's likely not worth it. 2102 bool MemberOfUnknownSpecialization; 2103 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2104 MemberOfUnknownSpecialization); 2105 2106 if (MemberOfUnknownSpecialization || 2107 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2108 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2109 IsAddressOfOperand, TemplateArgs); 2110 } else { 2111 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2112 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2113 2114 // If the result might be in a dependent base class, this is a dependent 2115 // id-expression. 2116 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2117 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2118 IsAddressOfOperand, TemplateArgs); 2119 2120 // If this reference is in an Objective-C method, then we need to do 2121 // some special Objective-C lookup, too. 2122 if (IvarLookupFollowUp) { 2123 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2124 if (E.isInvalid()) 2125 return ExprError(); 2126 2127 if (Expr *Ex = E.getAs<Expr>()) 2128 return Ex; 2129 } 2130 } 2131 2132 if (R.isAmbiguous()) 2133 return ExprError(); 2134 2135 // This could be an implicitly declared function reference (legal in C90, 2136 // extension in C99, forbidden in C++). 2137 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2138 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2139 if (D) R.addDecl(D); 2140 } 2141 2142 // Determine whether this name might be a candidate for 2143 // argument-dependent lookup. 2144 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2145 2146 if (R.empty() && !ADL) { 2147 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2148 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2149 TemplateKWLoc, TemplateArgs)) 2150 return E; 2151 } 2152 2153 // Don't diagnose an empty lookup for inline assembly. 2154 if (IsInlineAsmIdentifier) 2155 return ExprError(); 2156 2157 // If this name wasn't predeclared and if this is not a function 2158 // call, diagnose the problem. 2159 TypoExpr *TE = nullptr; 2160 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2161 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2162 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2163 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2164 "Typo correction callback misconfigured"); 2165 if (CCC) { 2166 // Make sure the callback knows what the typo being diagnosed is. 2167 CCC->setTypoName(II); 2168 if (SS.isValid()) 2169 CCC->setTypoNNS(SS.getScopeRep()); 2170 } 2171 if (DiagnoseEmptyLookup(S, SS, R, 2172 CCC ? std::move(CCC) : std::move(DefaultValidator), 2173 nullptr, None, &TE)) { 2174 if (TE && KeywordReplacement) { 2175 auto &State = getTypoExprState(TE); 2176 auto BestTC = State.Consumer->getNextCorrection(); 2177 if (BestTC.isKeyword()) { 2178 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2179 if (State.DiagHandler) 2180 State.DiagHandler(BestTC); 2181 KeywordReplacement->startToken(); 2182 KeywordReplacement->setKind(II->getTokenID()); 2183 KeywordReplacement->setIdentifierInfo(II); 2184 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2185 // Clean up the state associated with the TypoExpr, since it has 2186 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2187 clearDelayedTypo(TE); 2188 // Signal that a correction to a keyword was performed by returning a 2189 // valid-but-null ExprResult. 2190 return (Expr*)nullptr; 2191 } 2192 State.Consumer->resetCorrectionStream(); 2193 } 2194 return TE ? TE : ExprError(); 2195 } 2196 2197 assert(!R.empty() && 2198 "DiagnoseEmptyLookup returned false but added no results"); 2199 2200 // If we found an Objective-C instance variable, let 2201 // LookupInObjCMethod build the appropriate expression to 2202 // reference the ivar. 2203 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2204 R.clear(); 2205 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2206 // In a hopelessly buggy code, Objective-C instance variable 2207 // lookup fails and no expression will be built to reference it. 2208 if (!E.isInvalid() && !E.get()) 2209 return ExprError(); 2210 return E; 2211 } 2212 } 2213 2214 // This is guaranteed from this point on. 2215 assert(!R.empty() || ADL); 2216 2217 // Check whether this might be a C++ implicit instance member access. 2218 // C++ [class.mfct.non-static]p3: 2219 // When an id-expression that is not part of a class member access 2220 // syntax and not used to form a pointer to member is used in the 2221 // body of a non-static member function of class X, if name lookup 2222 // resolves the name in the id-expression to a non-static non-type 2223 // member of some class C, the id-expression is transformed into a 2224 // class member access expression using (*this) as the 2225 // postfix-expression to the left of the . operator. 2226 // 2227 // But we don't actually need to do this for '&' operands if R 2228 // resolved to a function or overloaded function set, because the 2229 // expression is ill-formed if it actually works out to be a 2230 // non-static member function: 2231 // 2232 // C++ [expr.ref]p4: 2233 // Otherwise, if E1.E2 refers to a non-static member function. . . 2234 // [t]he expression can be used only as the left-hand operand of a 2235 // member function call. 2236 // 2237 // There are other safeguards against such uses, but it's important 2238 // to get this right here so that we don't end up making a 2239 // spuriously dependent expression if we're inside a dependent 2240 // instance method. 2241 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2242 bool MightBeImplicitMember; 2243 if (!IsAddressOfOperand) 2244 MightBeImplicitMember = true; 2245 else if (!SS.isEmpty()) 2246 MightBeImplicitMember = false; 2247 else if (R.isOverloadedResult()) 2248 MightBeImplicitMember = false; 2249 else if (R.isUnresolvableResult()) 2250 MightBeImplicitMember = true; 2251 else 2252 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2253 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2254 isa<MSPropertyDecl>(R.getFoundDecl()); 2255 2256 if (MightBeImplicitMember) 2257 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2258 R, TemplateArgs, S); 2259 } 2260 2261 if (TemplateArgs || TemplateKWLoc.isValid()) { 2262 2263 // In C++1y, if this is a variable template id, then check it 2264 // in BuildTemplateIdExpr(). 2265 // The single lookup result must be a variable template declaration. 2266 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2267 Id.TemplateId->Kind == TNK_Var_template) { 2268 assert(R.getAsSingle<VarTemplateDecl>() && 2269 "There should only be one declaration found."); 2270 } 2271 2272 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2273 } 2274 2275 return BuildDeclarationNameExpr(SS, R, ADL); 2276 } 2277 2278 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2279 /// declaration name, generally during template instantiation. 2280 /// There's a large number of things which don't need to be done along 2281 /// this path. 2282 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2283 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2284 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2285 DeclContext *DC = computeDeclContext(SS, false); 2286 if (!DC) 2287 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2288 NameInfo, /*TemplateArgs=*/nullptr); 2289 2290 if (RequireCompleteDeclContext(SS, DC)) 2291 return ExprError(); 2292 2293 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2294 LookupQualifiedName(R, DC); 2295 2296 if (R.isAmbiguous()) 2297 return ExprError(); 2298 2299 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2300 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2301 NameInfo, /*TemplateArgs=*/nullptr); 2302 2303 if (R.empty()) { 2304 Diag(NameInfo.getLoc(), diag::err_no_member) 2305 << NameInfo.getName() << DC << SS.getRange(); 2306 return ExprError(); 2307 } 2308 2309 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2310 // Diagnose a missing typename if this resolved unambiguously to a type in 2311 // a dependent context. If we can recover with a type, downgrade this to 2312 // a warning in Microsoft compatibility mode. 2313 unsigned DiagID = diag::err_typename_missing; 2314 if (RecoveryTSI && getLangOpts().MSVCCompat) 2315 DiagID = diag::ext_typename_missing; 2316 SourceLocation Loc = SS.getBeginLoc(); 2317 auto D = Diag(Loc, DiagID); 2318 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2319 << SourceRange(Loc, NameInfo.getEndLoc()); 2320 2321 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2322 // context. 2323 if (!RecoveryTSI) 2324 return ExprError(); 2325 2326 // Only issue the fixit if we're prepared to recover. 2327 D << FixItHint::CreateInsertion(Loc, "typename "); 2328 2329 // Recover by pretending this was an elaborated type. 2330 QualType Ty = Context.getTypeDeclType(TD); 2331 TypeLocBuilder TLB; 2332 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2333 2334 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2335 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2336 QTL.setElaboratedKeywordLoc(SourceLocation()); 2337 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2338 2339 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2340 2341 return ExprEmpty(); 2342 } 2343 2344 // Defend against this resolving to an implicit member access. We usually 2345 // won't get here if this might be a legitimate a class member (we end up in 2346 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2347 // a pointer-to-member or in an unevaluated context in C++11. 2348 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2349 return BuildPossibleImplicitMemberExpr(SS, 2350 /*TemplateKWLoc=*/SourceLocation(), 2351 R, /*TemplateArgs=*/nullptr, S); 2352 2353 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2354 } 2355 2356 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2357 /// detected that we're currently inside an ObjC method. Perform some 2358 /// additional lookup. 2359 /// 2360 /// Ideally, most of this would be done by lookup, but there's 2361 /// actually quite a lot of extra work involved. 2362 /// 2363 /// Returns a null sentinel to indicate trivial success. 2364 ExprResult 2365 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2366 IdentifierInfo *II, bool AllowBuiltinCreation) { 2367 SourceLocation Loc = Lookup.getNameLoc(); 2368 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2369 2370 // Check for error condition which is already reported. 2371 if (!CurMethod) 2372 return ExprError(); 2373 2374 // There are two cases to handle here. 1) scoped lookup could have failed, 2375 // in which case we should look for an ivar. 2) scoped lookup could have 2376 // found a decl, but that decl is outside the current instance method (i.e. 2377 // a global variable). In these two cases, we do a lookup for an ivar with 2378 // this name, if the lookup sucedes, we replace it our current decl. 2379 2380 // If we're in a class method, we don't normally want to look for 2381 // ivars. But if we don't find anything else, and there's an 2382 // ivar, that's an error. 2383 bool IsClassMethod = CurMethod->isClassMethod(); 2384 2385 bool LookForIvars; 2386 if (Lookup.empty()) 2387 LookForIvars = true; 2388 else if (IsClassMethod) 2389 LookForIvars = false; 2390 else 2391 LookForIvars = (Lookup.isSingleResult() && 2392 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2393 ObjCInterfaceDecl *IFace = nullptr; 2394 if (LookForIvars) { 2395 IFace = CurMethod->getClassInterface(); 2396 ObjCInterfaceDecl *ClassDeclared; 2397 ObjCIvarDecl *IV = nullptr; 2398 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2399 // Diagnose using an ivar in a class method. 2400 if (IsClassMethod) 2401 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2402 << IV->getDeclName()); 2403 2404 // If we're referencing an invalid decl, just return this as a silent 2405 // error node. The error diagnostic was already emitted on the decl. 2406 if (IV->isInvalidDecl()) 2407 return ExprError(); 2408 2409 // Check if referencing a field with __attribute__((deprecated)). 2410 if (DiagnoseUseOfDecl(IV, Loc)) 2411 return ExprError(); 2412 2413 // Diagnose the use of an ivar outside of the declaring class. 2414 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2415 !declaresSameEntity(ClassDeclared, IFace) && 2416 !getLangOpts().DebuggerSupport) 2417 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2418 2419 // FIXME: This should use a new expr for a direct reference, don't 2420 // turn this into Self->ivar, just return a BareIVarExpr or something. 2421 IdentifierInfo &II = Context.Idents.get("self"); 2422 UnqualifiedId SelfName; 2423 SelfName.setIdentifier(&II, SourceLocation()); 2424 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2425 CXXScopeSpec SelfScopeSpec; 2426 SourceLocation TemplateKWLoc; 2427 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2428 SelfName, false, false); 2429 if (SelfExpr.isInvalid()) 2430 return ExprError(); 2431 2432 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2433 if (SelfExpr.isInvalid()) 2434 return ExprError(); 2435 2436 MarkAnyDeclReferenced(Loc, IV, true); 2437 2438 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2439 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2440 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2441 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2442 2443 ObjCIvarRefExpr *Result = new (Context) 2444 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2445 IV->getLocation(), SelfExpr.get(), true, true); 2446 2447 if (getLangOpts().ObjCAutoRefCount) { 2448 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2449 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2450 recordUseOfEvaluatedWeak(Result); 2451 } 2452 if (CurContext->isClosure()) 2453 Diag(Loc, diag::warn_implicitly_retains_self) 2454 << FixItHint::CreateInsertion(Loc, "self->"); 2455 } 2456 2457 return Result; 2458 } 2459 } else if (CurMethod->isInstanceMethod()) { 2460 // We should warn if a local variable hides an ivar. 2461 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2462 ObjCInterfaceDecl *ClassDeclared; 2463 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2464 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2465 declaresSameEntity(IFace, ClassDeclared)) 2466 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2467 } 2468 } 2469 } else if (Lookup.isSingleResult() && 2470 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2471 // If accessing a stand-alone ivar in a class method, this is an error. 2472 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2473 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2474 << IV->getDeclName()); 2475 } 2476 2477 if (Lookup.empty() && II && AllowBuiltinCreation) { 2478 // FIXME. Consolidate this with similar code in LookupName. 2479 if (unsigned BuiltinID = II->getBuiltinID()) { 2480 if (!(getLangOpts().CPlusPlus && 2481 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2482 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2483 S, Lookup.isForRedeclaration(), 2484 Lookup.getNameLoc()); 2485 if (D) Lookup.addDecl(D); 2486 } 2487 } 2488 } 2489 // Sentinel value saying that we didn't do anything special. 2490 return ExprResult((Expr *)nullptr); 2491 } 2492 2493 /// \brief Cast a base object to a member's actual type. 2494 /// 2495 /// Logically this happens in three phases: 2496 /// 2497 /// * First we cast from the base type to the naming class. 2498 /// The naming class is the class into which we were looking 2499 /// when we found the member; it's the qualifier type if a 2500 /// qualifier was provided, and otherwise it's the base type. 2501 /// 2502 /// * Next we cast from the naming class to the declaring class. 2503 /// If the member we found was brought into a class's scope by 2504 /// a using declaration, this is that class; otherwise it's 2505 /// the class declaring the member. 2506 /// 2507 /// * Finally we cast from the declaring class to the "true" 2508 /// declaring class of the member. This conversion does not 2509 /// obey access control. 2510 ExprResult 2511 Sema::PerformObjectMemberConversion(Expr *From, 2512 NestedNameSpecifier *Qualifier, 2513 NamedDecl *FoundDecl, 2514 NamedDecl *Member) { 2515 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2516 if (!RD) 2517 return From; 2518 2519 QualType DestRecordType; 2520 QualType DestType; 2521 QualType FromRecordType; 2522 QualType FromType = From->getType(); 2523 bool PointerConversions = false; 2524 if (isa<FieldDecl>(Member)) { 2525 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2526 2527 if (FromType->getAs<PointerType>()) { 2528 DestType = Context.getPointerType(DestRecordType); 2529 FromRecordType = FromType->getPointeeType(); 2530 PointerConversions = true; 2531 } else { 2532 DestType = DestRecordType; 2533 FromRecordType = FromType; 2534 } 2535 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2536 if (Method->isStatic()) 2537 return From; 2538 2539 DestType = Method->getThisType(Context); 2540 DestRecordType = DestType->getPointeeType(); 2541 2542 if (FromType->getAs<PointerType>()) { 2543 FromRecordType = FromType->getPointeeType(); 2544 PointerConversions = true; 2545 } else { 2546 FromRecordType = FromType; 2547 DestType = DestRecordType; 2548 } 2549 } else { 2550 // No conversion necessary. 2551 return From; 2552 } 2553 2554 if (DestType->isDependentType() || FromType->isDependentType()) 2555 return From; 2556 2557 // If the unqualified types are the same, no conversion is necessary. 2558 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2559 return From; 2560 2561 SourceRange FromRange = From->getSourceRange(); 2562 SourceLocation FromLoc = FromRange.getBegin(); 2563 2564 ExprValueKind VK = From->getValueKind(); 2565 2566 // C++ [class.member.lookup]p8: 2567 // [...] Ambiguities can often be resolved by qualifying a name with its 2568 // class name. 2569 // 2570 // If the member was a qualified name and the qualified referred to a 2571 // specific base subobject type, we'll cast to that intermediate type 2572 // first and then to the object in which the member is declared. That allows 2573 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2574 // 2575 // class Base { public: int x; }; 2576 // class Derived1 : public Base { }; 2577 // class Derived2 : public Base { }; 2578 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2579 // 2580 // void VeryDerived::f() { 2581 // x = 17; // error: ambiguous base subobjects 2582 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2583 // } 2584 if (Qualifier && Qualifier->getAsType()) { 2585 QualType QType = QualType(Qualifier->getAsType(), 0); 2586 assert(QType->isRecordType() && "lookup done with non-record type"); 2587 2588 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2589 2590 // In C++98, the qualifier type doesn't actually have to be a base 2591 // type of the object type, in which case we just ignore it. 2592 // Otherwise build the appropriate casts. 2593 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2594 CXXCastPath BasePath; 2595 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2596 FromLoc, FromRange, &BasePath)) 2597 return ExprError(); 2598 2599 if (PointerConversions) 2600 QType = Context.getPointerType(QType); 2601 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2602 VK, &BasePath).get(); 2603 2604 FromType = QType; 2605 FromRecordType = QRecordType; 2606 2607 // If the qualifier type was the same as the destination type, 2608 // we're done. 2609 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2610 return From; 2611 } 2612 } 2613 2614 bool IgnoreAccess = false; 2615 2616 // If we actually found the member through a using declaration, cast 2617 // down to the using declaration's type. 2618 // 2619 // Pointer equality is fine here because only one declaration of a 2620 // class ever has member declarations. 2621 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2622 assert(isa<UsingShadowDecl>(FoundDecl)); 2623 QualType URecordType = Context.getTypeDeclType( 2624 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2625 2626 // We only need to do this if the naming-class to declaring-class 2627 // conversion is non-trivial. 2628 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2629 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2630 CXXCastPath BasePath; 2631 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2632 FromLoc, FromRange, &BasePath)) 2633 return ExprError(); 2634 2635 QualType UType = URecordType; 2636 if (PointerConversions) 2637 UType = Context.getPointerType(UType); 2638 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2639 VK, &BasePath).get(); 2640 FromType = UType; 2641 FromRecordType = URecordType; 2642 } 2643 2644 // We don't do access control for the conversion from the 2645 // declaring class to the true declaring class. 2646 IgnoreAccess = true; 2647 } 2648 2649 CXXCastPath BasePath; 2650 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2651 FromLoc, FromRange, &BasePath, 2652 IgnoreAccess)) 2653 return ExprError(); 2654 2655 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2656 VK, &BasePath); 2657 } 2658 2659 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2660 const LookupResult &R, 2661 bool HasTrailingLParen) { 2662 // Only when used directly as the postfix-expression of a call. 2663 if (!HasTrailingLParen) 2664 return false; 2665 2666 // Never if a scope specifier was provided. 2667 if (SS.isSet()) 2668 return false; 2669 2670 // Only in C++ or ObjC++. 2671 if (!getLangOpts().CPlusPlus) 2672 return false; 2673 2674 // Turn off ADL when we find certain kinds of declarations during 2675 // normal lookup: 2676 for (NamedDecl *D : R) { 2677 // C++0x [basic.lookup.argdep]p3: 2678 // -- a declaration of a class member 2679 // Since using decls preserve this property, we check this on the 2680 // original decl. 2681 if (D->isCXXClassMember()) 2682 return false; 2683 2684 // C++0x [basic.lookup.argdep]p3: 2685 // -- a block-scope function declaration that is not a 2686 // using-declaration 2687 // NOTE: we also trigger this for function templates (in fact, we 2688 // don't check the decl type at all, since all other decl types 2689 // turn off ADL anyway). 2690 if (isa<UsingShadowDecl>(D)) 2691 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2692 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2693 return false; 2694 2695 // C++0x [basic.lookup.argdep]p3: 2696 // -- a declaration that is neither a function or a function 2697 // template 2698 // And also for builtin functions. 2699 if (isa<FunctionDecl>(D)) { 2700 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2701 2702 // But also builtin functions. 2703 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2704 return false; 2705 } else if (!isa<FunctionTemplateDecl>(D)) 2706 return false; 2707 } 2708 2709 return true; 2710 } 2711 2712 2713 /// Diagnoses obvious problems with the use of the given declaration 2714 /// as an expression. This is only actually called for lookups that 2715 /// were not overloaded, and it doesn't promise that the declaration 2716 /// will in fact be used. 2717 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2718 if (isa<TypedefNameDecl>(D)) { 2719 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2720 return true; 2721 } 2722 2723 if (isa<ObjCInterfaceDecl>(D)) { 2724 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2725 return true; 2726 } 2727 2728 if (isa<NamespaceDecl>(D)) { 2729 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2730 return true; 2731 } 2732 2733 return false; 2734 } 2735 2736 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2737 LookupResult &R, bool NeedsADL, 2738 bool AcceptInvalidDecl) { 2739 // If this is a single, fully-resolved result and we don't need ADL, 2740 // just build an ordinary singleton decl ref. 2741 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2742 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2743 R.getRepresentativeDecl(), nullptr, 2744 AcceptInvalidDecl); 2745 2746 // We only need to check the declaration if there's exactly one 2747 // result, because in the overloaded case the results can only be 2748 // functions and function templates. 2749 if (R.isSingleResult() && 2750 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2751 return ExprError(); 2752 2753 // Otherwise, just build an unresolved lookup expression. Suppress 2754 // any lookup-related diagnostics; we'll hash these out later, when 2755 // we've picked a target. 2756 R.suppressDiagnostics(); 2757 2758 UnresolvedLookupExpr *ULE 2759 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2760 SS.getWithLocInContext(Context), 2761 R.getLookupNameInfo(), 2762 NeedsADL, R.isOverloadedResult(), 2763 R.begin(), R.end()); 2764 2765 return ULE; 2766 } 2767 2768 /// \brief Complete semantic analysis for a reference to the given declaration. 2769 ExprResult Sema::BuildDeclarationNameExpr( 2770 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2771 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2772 bool AcceptInvalidDecl) { 2773 assert(D && "Cannot refer to a NULL declaration"); 2774 assert(!isa<FunctionTemplateDecl>(D) && 2775 "Cannot refer unambiguously to a function template"); 2776 2777 SourceLocation Loc = NameInfo.getLoc(); 2778 if (CheckDeclInExpr(*this, Loc, D)) 2779 return ExprError(); 2780 2781 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2782 // Specifically diagnose references to class templates that are missing 2783 // a template argument list. 2784 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2785 << Template << SS.getRange(); 2786 Diag(Template->getLocation(), diag::note_template_decl_here); 2787 return ExprError(); 2788 } 2789 2790 // Make sure that we're referring to a value. 2791 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2792 if (!VD) { 2793 Diag(Loc, diag::err_ref_non_value) 2794 << D << SS.getRange(); 2795 Diag(D->getLocation(), diag::note_declared_at); 2796 return ExprError(); 2797 } 2798 2799 // Check whether this declaration can be used. Note that we suppress 2800 // this check when we're going to perform argument-dependent lookup 2801 // on this function name, because this might not be the function 2802 // that overload resolution actually selects. 2803 if (DiagnoseUseOfDecl(VD, Loc)) 2804 return ExprError(); 2805 2806 // Only create DeclRefExpr's for valid Decl's. 2807 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2808 return ExprError(); 2809 2810 // Handle members of anonymous structs and unions. If we got here, 2811 // and the reference is to a class member indirect field, then this 2812 // must be the subject of a pointer-to-member expression. 2813 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2814 if (!indirectField->isCXXClassMember()) 2815 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2816 indirectField); 2817 2818 { 2819 QualType type = VD->getType(); 2820 ExprValueKind valueKind = VK_RValue; 2821 2822 switch (D->getKind()) { 2823 // Ignore all the non-ValueDecl kinds. 2824 #define ABSTRACT_DECL(kind) 2825 #define VALUE(type, base) 2826 #define DECL(type, base) \ 2827 case Decl::type: 2828 #include "clang/AST/DeclNodes.inc" 2829 llvm_unreachable("invalid value decl kind"); 2830 2831 // These shouldn't make it here. 2832 case Decl::ObjCAtDefsField: 2833 case Decl::ObjCIvar: 2834 llvm_unreachable("forming non-member reference to ivar?"); 2835 2836 // Enum constants are always r-values and never references. 2837 // Unresolved using declarations are dependent. 2838 case Decl::EnumConstant: 2839 case Decl::UnresolvedUsingValue: 2840 valueKind = VK_RValue; 2841 break; 2842 2843 // Fields and indirect fields that got here must be for 2844 // pointer-to-member expressions; we just call them l-values for 2845 // internal consistency, because this subexpression doesn't really 2846 // exist in the high-level semantics. 2847 case Decl::Field: 2848 case Decl::IndirectField: 2849 assert(getLangOpts().CPlusPlus && 2850 "building reference to field in C?"); 2851 2852 // These can't have reference type in well-formed programs, but 2853 // for internal consistency we do this anyway. 2854 type = type.getNonReferenceType(); 2855 valueKind = VK_LValue; 2856 break; 2857 2858 // Non-type template parameters are either l-values or r-values 2859 // depending on the type. 2860 case Decl::NonTypeTemplateParm: { 2861 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2862 type = reftype->getPointeeType(); 2863 valueKind = VK_LValue; // even if the parameter is an r-value reference 2864 break; 2865 } 2866 2867 // For non-references, we need to strip qualifiers just in case 2868 // the template parameter was declared as 'const int' or whatever. 2869 valueKind = VK_RValue; 2870 type = type.getUnqualifiedType(); 2871 break; 2872 } 2873 2874 case Decl::Var: 2875 case Decl::VarTemplateSpecialization: 2876 case Decl::VarTemplatePartialSpecialization: 2877 // In C, "extern void blah;" is valid and is an r-value. 2878 if (!getLangOpts().CPlusPlus && 2879 !type.hasQualifiers() && 2880 type->isVoidType()) { 2881 valueKind = VK_RValue; 2882 break; 2883 } 2884 // fallthrough 2885 2886 case Decl::ImplicitParam: 2887 case Decl::ParmVar: { 2888 // These are always l-values. 2889 valueKind = VK_LValue; 2890 type = type.getNonReferenceType(); 2891 2892 // FIXME: Does the addition of const really only apply in 2893 // potentially-evaluated contexts? Since the variable isn't actually 2894 // captured in an unevaluated context, it seems that the answer is no. 2895 if (!isUnevaluatedContext()) { 2896 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2897 if (!CapturedType.isNull()) 2898 type = CapturedType; 2899 } 2900 2901 break; 2902 } 2903 2904 case Decl::Function: { 2905 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2906 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2907 type = Context.BuiltinFnTy; 2908 valueKind = VK_RValue; 2909 break; 2910 } 2911 } 2912 2913 const FunctionType *fty = type->castAs<FunctionType>(); 2914 2915 // If we're referring to a function with an __unknown_anytype 2916 // result type, make the entire expression __unknown_anytype. 2917 if (fty->getReturnType() == Context.UnknownAnyTy) { 2918 type = Context.UnknownAnyTy; 2919 valueKind = VK_RValue; 2920 break; 2921 } 2922 2923 // Functions are l-values in C++. 2924 if (getLangOpts().CPlusPlus) { 2925 valueKind = VK_LValue; 2926 break; 2927 } 2928 2929 // C99 DR 316 says that, if a function type comes from a 2930 // function definition (without a prototype), that type is only 2931 // used for checking compatibility. Therefore, when referencing 2932 // the function, we pretend that we don't have the full function 2933 // type. 2934 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2935 isa<FunctionProtoType>(fty)) 2936 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2937 fty->getExtInfo()); 2938 2939 // Functions are r-values in C. 2940 valueKind = VK_RValue; 2941 break; 2942 } 2943 2944 case Decl::MSProperty: 2945 valueKind = VK_LValue; 2946 break; 2947 2948 case Decl::CXXMethod: 2949 // If we're referring to a method with an __unknown_anytype 2950 // result type, make the entire expression __unknown_anytype. 2951 // This should only be possible with a type written directly. 2952 if (const FunctionProtoType *proto 2953 = dyn_cast<FunctionProtoType>(VD->getType())) 2954 if (proto->getReturnType() == Context.UnknownAnyTy) { 2955 type = Context.UnknownAnyTy; 2956 valueKind = VK_RValue; 2957 break; 2958 } 2959 2960 // C++ methods are l-values if static, r-values if non-static. 2961 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2962 valueKind = VK_LValue; 2963 break; 2964 } 2965 // fallthrough 2966 2967 case Decl::CXXConversion: 2968 case Decl::CXXDestructor: 2969 case Decl::CXXConstructor: 2970 valueKind = VK_RValue; 2971 break; 2972 } 2973 2974 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2975 TemplateArgs); 2976 } 2977 } 2978 2979 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 2980 SmallString<32> &Target) { 2981 Target.resize(CharByteWidth * (Source.size() + 1)); 2982 char *ResultPtr = &Target[0]; 2983 const UTF8 *ErrorPtr; 2984 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 2985 (void)success; 2986 assert(success); 2987 Target.resize(ResultPtr - &Target[0]); 2988 } 2989 2990 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 2991 PredefinedExpr::IdentType IT) { 2992 // Pick the current block, lambda, captured statement or function. 2993 Decl *currentDecl = nullptr; 2994 if (const BlockScopeInfo *BSI = getCurBlock()) 2995 currentDecl = BSI->TheDecl; 2996 else if (const LambdaScopeInfo *LSI = getCurLambda()) 2997 currentDecl = LSI->CallOperator; 2998 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 2999 currentDecl = CSI->TheCapturedDecl; 3000 else 3001 currentDecl = getCurFunctionOrMethodDecl(); 3002 3003 if (!currentDecl) { 3004 Diag(Loc, diag::ext_predef_outside_function); 3005 currentDecl = Context.getTranslationUnitDecl(); 3006 } 3007 3008 QualType ResTy; 3009 StringLiteral *SL = nullptr; 3010 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3011 ResTy = Context.DependentTy; 3012 else { 3013 // Pre-defined identifiers are of type char[x], where x is the length of 3014 // the string. 3015 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3016 unsigned Length = Str.length(); 3017 3018 llvm::APInt LengthI(32, Length + 1); 3019 if (IT == PredefinedExpr::LFunction) { 3020 ResTy = Context.WideCharTy.withConst(); 3021 SmallString<32> RawChars; 3022 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3023 Str, RawChars); 3024 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3025 /*IndexTypeQuals*/ 0); 3026 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3027 /*Pascal*/ false, ResTy, Loc); 3028 } else { 3029 ResTy = Context.CharTy.withConst(); 3030 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3031 /*IndexTypeQuals*/ 0); 3032 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3033 /*Pascal*/ false, ResTy, Loc); 3034 } 3035 } 3036 3037 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3038 } 3039 3040 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3041 PredefinedExpr::IdentType IT; 3042 3043 switch (Kind) { 3044 default: llvm_unreachable("Unknown simple primary expr!"); 3045 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3046 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3047 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3048 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3049 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3050 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3051 } 3052 3053 return BuildPredefinedExpr(Loc, IT); 3054 } 3055 3056 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3057 SmallString<16> CharBuffer; 3058 bool Invalid = false; 3059 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3060 if (Invalid) 3061 return ExprError(); 3062 3063 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3064 PP, Tok.getKind()); 3065 if (Literal.hadError()) 3066 return ExprError(); 3067 3068 QualType Ty; 3069 if (Literal.isWide()) 3070 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3071 else if (Literal.isUTF16()) 3072 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3073 else if (Literal.isUTF32()) 3074 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3075 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3076 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3077 else 3078 Ty = Context.CharTy; // 'x' -> char in C++ 3079 3080 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3081 if (Literal.isWide()) 3082 Kind = CharacterLiteral::Wide; 3083 else if (Literal.isUTF16()) 3084 Kind = CharacterLiteral::UTF16; 3085 else if (Literal.isUTF32()) 3086 Kind = CharacterLiteral::UTF32; 3087 else if (Literal.isUTF8()) 3088 Kind = CharacterLiteral::UTF8; 3089 3090 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3091 Tok.getLocation()); 3092 3093 if (Literal.getUDSuffix().empty()) 3094 return Lit; 3095 3096 // We're building a user-defined literal. 3097 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3098 SourceLocation UDSuffixLoc = 3099 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3100 3101 // Make sure we're allowed user-defined literals here. 3102 if (!UDLScope) 3103 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3104 3105 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3106 // operator "" X (ch) 3107 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3108 Lit, Tok.getLocation()); 3109 } 3110 3111 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3112 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3113 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3114 Context.IntTy, Loc); 3115 } 3116 3117 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3118 QualType Ty, SourceLocation Loc) { 3119 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3120 3121 using llvm::APFloat; 3122 APFloat Val(Format); 3123 3124 APFloat::opStatus result = Literal.GetFloatValue(Val); 3125 3126 // Overflow is always an error, but underflow is only an error if 3127 // we underflowed to zero (APFloat reports denormals as underflow). 3128 if ((result & APFloat::opOverflow) || 3129 ((result & APFloat::opUnderflow) && Val.isZero())) { 3130 unsigned diagnostic; 3131 SmallString<20> buffer; 3132 if (result & APFloat::opOverflow) { 3133 diagnostic = diag::warn_float_overflow; 3134 APFloat::getLargest(Format).toString(buffer); 3135 } else { 3136 diagnostic = diag::warn_float_underflow; 3137 APFloat::getSmallest(Format).toString(buffer); 3138 } 3139 3140 S.Diag(Loc, diagnostic) 3141 << Ty 3142 << StringRef(buffer.data(), buffer.size()); 3143 } 3144 3145 bool isExact = (result == APFloat::opOK); 3146 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3147 } 3148 3149 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3150 assert(E && "Invalid expression"); 3151 3152 if (E->isValueDependent()) 3153 return false; 3154 3155 QualType QT = E->getType(); 3156 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3157 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3158 return true; 3159 } 3160 3161 llvm::APSInt ValueAPS; 3162 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3163 3164 if (R.isInvalid()) 3165 return true; 3166 3167 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3168 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3169 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3170 << ValueAPS.toString(10) << ValueIsPositive; 3171 return true; 3172 } 3173 3174 return false; 3175 } 3176 3177 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3178 // Fast path for a single digit (which is quite common). A single digit 3179 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3180 if (Tok.getLength() == 1) { 3181 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3182 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3183 } 3184 3185 SmallString<128> SpellingBuffer; 3186 // NumericLiteralParser wants to overread by one character. Add padding to 3187 // the buffer in case the token is copied to the buffer. If getSpelling() 3188 // returns a StringRef to the memory buffer, it should have a null char at 3189 // the EOF, so it is also safe. 3190 SpellingBuffer.resize(Tok.getLength() + 1); 3191 3192 // Get the spelling of the token, which eliminates trigraphs, etc. 3193 bool Invalid = false; 3194 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3195 if (Invalid) 3196 return ExprError(); 3197 3198 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3199 if (Literal.hadError) 3200 return ExprError(); 3201 3202 if (Literal.hasUDSuffix()) { 3203 // We're building a user-defined literal. 3204 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3205 SourceLocation UDSuffixLoc = 3206 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3207 3208 // Make sure we're allowed user-defined literals here. 3209 if (!UDLScope) 3210 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3211 3212 QualType CookedTy; 3213 if (Literal.isFloatingLiteral()) { 3214 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3215 // long double, the literal is treated as a call of the form 3216 // operator "" X (f L) 3217 CookedTy = Context.LongDoubleTy; 3218 } else { 3219 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3220 // unsigned long long, the literal is treated as a call of the form 3221 // operator "" X (n ULL) 3222 CookedTy = Context.UnsignedLongLongTy; 3223 } 3224 3225 DeclarationName OpName = 3226 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3227 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3228 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3229 3230 SourceLocation TokLoc = Tok.getLocation(); 3231 3232 // Perform literal operator lookup to determine if we're building a raw 3233 // literal or a cooked one. 3234 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3235 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3236 /*AllowRaw*/true, /*AllowTemplate*/true, 3237 /*AllowStringTemplate*/false)) { 3238 case LOLR_Error: 3239 return ExprError(); 3240 3241 case LOLR_Cooked: { 3242 Expr *Lit; 3243 if (Literal.isFloatingLiteral()) { 3244 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3245 } else { 3246 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3247 if (Literal.GetIntegerValue(ResultVal)) 3248 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3249 << /* Unsigned */ 1; 3250 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3251 Tok.getLocation()); 3252 } 3253 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3254 } 3255 3256 case LOLR_Raw: { 3257 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3258 // literal is treated as a call of the form 3259 // operator "" X ("n") 3260 unsigned Length = Literal.getUDSuffixOffset(); 3261 QualType StrTy = Context.getConstantArrayType( 3262 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3263 ArrayType::Normal, 0); 3264 Expr *Lit = StringLiteral::Create( 3265 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3266 /*Pascal*/false, StrTy, &TokLoc, 1); 3267 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3268 } 3269 3270 case LOLR_Template: { 3271 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3272 // template), L is treated as a call fo the form 3273 // operator "" X <'c1', 'c2', ... 'ck'>() 3274 // where n is the source character sequence c1 c2 ... ck. 3275 TemplateArgumentListInfo ExplicitArgs; 3276 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3277 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3278 llvm::APSInt Value(CharBits, CharIsUnsigned); 3279 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3280 Value = TokSpelling[I]; 3281 TemplateArgument Arg(Context, Value, Context.CharTy); 3282 TemplateArgumentLocInfo ArgInfo; 3283 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3284 } 3285 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3286 &ExplicitArgs); 3287 } 3288 case LOLR_StringTemplate: 3289 llvm_unreachable("unexpected literal operator lookup result"); 3290 } 3291 } 3292 3293 Expr *Res; 3294 3295 if (Literal.isFloatingLiteral()) { 3296 QualType Ty; 3297 if (Literal.isFloat) 3298 Ty = Context.FloatTy; 3299 else if (!Literal.isLong) 3300 Ty = Context.DoubleTy; 3301 else 3302 Ty = Context.LongDoubleTy; 3303 3304 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3305 3306 if (Ty == Context.DoubleTy) { 3307 if (getLangOpts().SinglePrecisionConstants) { 3308 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3309 } else if (getLangOpts().OpenCL && 3310 !((getLangOpts().OpenCLVersion >= 120) || 3311 getOpenCLOptions().cl_khr_fp64)) { 3312 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3313 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3314 } 3315 } 3316 } else if (!Literal.isIntegerLiteral()) { 3317 return ExprError(); 3318 } else { 3319 QualType Ty; 3320 3321 // 'long long' is a C99 or C++11 feature. 3322 if (!getLangOpts().C99 && Literal.isLongLong) { 3323 if (getLangOpts().CPlusPlus) 3324 Diag(Tok.getLocation(), 3325 getLangOpts().CPlusPlus11 ? 3326 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3327 else 3328 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3329 } 3330 3331 // Get the value in the widest-possible width. 3332 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3333 llvm::APInt ResultVal(MaxWidth, 0); 3334 3335 if (Literal.GetIntegerValue(ResultVal)) { 3336 // If this value didn't fit into uintmax_t, error and force to ull. 3337 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3338 << /* Unsigned */ 1; 3339 Ty = Context.UnsignedLongLongTy; 3340 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3341 "long long is not intmax_t?"); 3342 } else { 3343 // If this value fits into a ULL, try to figure out what else it fits into 3344 // according to the rules of C99 6.4.4.1p5. 3345 3346 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3347 // be an unsigned int. 3348 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3349 3350 // Check from smallest to largest, picking the smallest type we can. 3351 unsigned Width = 0; 3352 3353 // Microsoft specific integer suffixes are explicitly sized. 3354 if (Literal.MicrosoftInteger) { 3355 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3356 Width = 8; 3357 Ty = Context.CharTy; 3358 } else { 3359 Width = Literal.MicrosoftInteger; 3360 Ty = Context.getIntTypeForBitwidth(Width, 3361 /*Signed=*/!Literal.isUnsigned); 3362 } 3363 } 3364 3365 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3366 // Are int/unsigned possibilities? 3367 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3368 3369 // Does it fit in a unsigned int? 3370 if (ResultVal.isIntN(IntSize)) { 3371 // Does it fit in a signed int? 3372 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3373 Ty = Context.IntTy; 3374 else if (AllowUnsigned) 3375 Ty = Context.UnsignedIntTy; 3376 Width = IntSize; 3377 } 3378 } 3379 3380 // Are long/unsigned long possibilities? 3381 if (Ty.isNull() && !Literal.isLongLong) { 3382 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3383 3384 // Does it fit in a unsigned long? 3385 if (ResultVal.isIntN(LongSize)) { 3386 // Does it fit in a signed long? 3387 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3388 Ty = Context.LongTy; 3389 else if (AllowUnsigned) 3390 Ty = Context.UnsignedLongTy; 3391 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3392 // is compatible. 3393 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3394 const unsigned LongLongSize = 3395 Context.getTargetInfo().getLongLongWidth(); 3396 Diag(Tok.getLocation(), 3397 getLangOpts().CPlusPlus 3398 ? Literal.isLong 3399 ? diag::warn_old_implicitly_unsigned_long_cxx 3400 : /*C++98 UB*/ diag:: 3401 ext_old_implicitly_unsigned_long_cxx 3402 : diag::warn_old_implicitly_unsigned_long) 3403 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3404 : /*will be ill-formed*/ 1); 3405 Ty = Context.UnsignedLongTy; 3406 } 3407 Width = LongSize; 3408 } 3409 } 3410 3411 // Check long long if needed. 3412 if (Ty.isNull()) { 3413 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3414 3415 // Does it fit in a unsigned long long? 3416 if (ResultVal.isIntN(LongLongSize)) { 3417 // Does it fit in a signed long long? 3418 // To be compatible with MSVC, hex integer literals ending with the 3419 // LL or i64 suffix are always signed in Microsoft mode. 3420 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3421 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3422 Ty = Context.LongLongTy; 3423 else if (AllowUnsigned) 3424 Ty = Context.UnsignedLongLongTy; 3425 Width = LongLongSize; 3426 } 3427 } 3428 3429 // If we still couldn't decide a type, we probably have something that 3430 // does not fit in a signed long long, but has no U suffix. 3431 if (Ty.isNull()) { 3432 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3433 Ty = Context.UnsignedLongLongTy; 3434 Width = Context.getTargetInfo().getLongLongWidth(); 3435 } 3436 3437 if (ResultVal.getBitWidth() != Width) 3438 ResultVal = ResultVal.trunc(Width); 3439 } 3440 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3441 } 3442 3443 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3444 if (Literal.isImaginary) 3445 Res = new (Context) ImaginaryLiteral(Res, 3446 Context.getComplexType(Res->getType())); 3447 3448 return Res; 3449 } 3450 3451 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3452 assert(E && "ActOnParenExpr() missing expr"); 3453 return new (Context) ParenExpr(L, R, E); 3454 } 3455 3456 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3457 SourceLocation Loc, 3458 SourceRange ArgRange) { 3459 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3460 // scalar or vector data type argument..." 3461 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3462 // type (C99 6.2.5p18) or void. 3463 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3464 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3465 << T << ArgRange; 3466 return true; 3467 } 3468 3469 assert((T->isVoidType() || !T->isIncompleteType()) && 3470 "Scalar types should always be complete"); 3471 return false; 3472 } 3473 3474 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3475 SourceLocation Loc, 3476 SourceRange ArgRange, 3477 UnaryExprOrTypeTrait TraitKind) { 3478 // Invalid types must be hard errors for SFINAE in C++. 3479 if (S.LangOpts.CPlusPlus) 3480 return true; 3481 3482 // C99 6.5.3.4p1: 3483 if (T->isFunctionType() && 3484 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3485 // sizeof(function)/alignof(function) is allowed as an extension. 3486 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3487 << TraitKind << ArgRange; 3488 return false; 3489 } 3490 3491 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3492 // this is an error (OpenCL v1.1 s6.3.k) 3493 if (T->isVoidType()) { 3494 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3495 : diag::ext_sizeof_alignof_void_type; 3496 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3497 return false; 3498 } 3499 3500 return true; 3501 } 3502 3503 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3504 SourceLocation Loc, 3505 SourceRange ArgRange, 3506 UnaryExprOrTypeTrait TraitKind) { 3507 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3508 // runtime doesn't allow it. 3509 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3510 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3511 << T << (TraitKind == UETT_SizeOf) 3512 << ArgRange; 3513 return true; 3514 } 3515 3516 return false; 3517 } 3518 3519 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3520 /// pointer type is equal to T) and emit a warning if it is. 3521 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3522 Expr *E) { 3523 // Don't warn if the operation changed the type. 3524 if (T != E->getType()) 3525 return; 3526 3527 // Now look for array decays. 3528 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3529 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3530 return; 3531 3532 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3533 << ICE->getType() 3534 << ICE->getSubExpr()->getType(); 3535 } 3536 3537 /// \brief Check the constraints on expression operands to unary type expression 3538 /// and type traits. 3539 /// 3540 /// Completes any types necessary and validates the constraints on the operand 3541 /// expression. The logic mostly mirrors the type-based overload, but may modify 3542 /// the expression as it completes the type for that expression through template 3543 /// instantiation, etc. 3544 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3545 UnaryExprOrTypeTrait ExprKind) { 3546 QualType ExprTy = E->getType(); 3547 assert(!ExprTy->isReferenceType()); 3548 3549 if (ExprKind == UETT_VecStep) 3550 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3551 E->getSourceRange()); 3552 3553 // Whitelist some types as extensions 3554 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3555 E->getSourceRange(), ExprKind)) 3556 return false; 3557 3558 // 'alignof' applied to an expression only requires the base element type of 3559 // the expression to be complete. 'sizeof' requires the expression's type to 3560 // be complete (and will attempt to complete it if it's an array of unknown 3561 // bound). 3562 if (ExprKind == UETT_AlignOf) { 3563 if (RequireCompleteType(E->getExprLoc(), 3564 Context.getBaseElementType(E->getType()), 3565 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3566 E->getSourceRange())) 3567 return true; 3568 } else { 3569 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3570 ExprKind, E->getSourceRange())) 3571 return true; 3572 } 3573 3574 // Completing the expression's type may have changed it. 3575 ExprTy = E->getType(); 3576 assert(!ExprTy->isReferenceType()); 3577 3578 if (ExprTy->isFunctionType()) { 3579 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3580 << ExprKind << E->getSourceRange(); 3581 return true; 3582 } 3583 3584 // The operand for sizeof and alignof is in an unevaluated expression context, 3585 // so side effects could result in unintended consequences. 3586 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3587 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false)) 3588 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3589 3590 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3591 E->getSourceRange(), ExprKind)) 3592 return true; 3593 3594 if (ExprKind == UETT_SizeOf) { 3595 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3596 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3597 QualType OType = PVD->getOriginalType(); 3598 QualType Type = PVD->getType(); 3599 if (Type->isPointerType() && OType->isArrayType()) { 3600 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3601 << Type << OType; 3602 Diag(PVD->getLocation(), diag::note_declared_at); 3603 } 3604 } 3605 } 3606 3607 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3608 // decays into a pointer and returns an unintended result. This is most 3609 // likely a typo for "sizeof(array) op x". 3610 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3611 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3612 BO->getLHS()); 3613 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3614 BO->getRHS()); 3615 } 3616 } 3617 3618 return false; 3619 } 3620 3621 /// \brief Check the constraints on operands to unary expression and type 3622 /// traits. 3623 /// 3624 /// This will complete any types necessary, and validate the various constraints 3625 /// on those operands. 3626 /// 3627 /// The UsualUnaryConversions() function is *not* called by this routine. 3628 /// C99 6.3.2.1p[2-4] all state: 3629 /// Except when it is the operand of the sizeof operator ... 3630 /// 3631 /// C++ [expr.sizeof]p4 3632 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3633 /// standard conversions are not applied to the operand of sizeof. 3634 /// 3635 /// This policy is followed for all of the unary trait expressions. 3636 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3637 SourceLocation OpLoc, 3638 SourceRange ExprRange, 3639 UnaryExprOrTypeTrait ExprKind) { 3640 if (ExprType->isDependentType()) 3641 return false; 3642 3643 // C++ [expr.sizeof]p2: 3644 // When applied to a reference or a reference type, the result 3645 // is the size of the referenced type. 3646 // C++11 [expr.alignof]p3: 3647 // When alignof is applied to a reference type, the result 3648 // shall be the alignment of the referenced type. 3649 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3650 ExprType = Ref->getPointeeType(); 3651 3652 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3653 // When alignof or _Alignof is applied to an array type, the result 3654 // is the alignment of the element type. 3655 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3656 ExprType = Context.getBaseElementType(ExprType); 3657 3658 if (ExprKind == UETT_VecStep) 3659 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3660 3661 // Whitelist some types as extensions 3662 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3663 ExprKind)) 3664 return false; 3665 3666 if (RequireCompleteType(OpLoc, ExprType, 3667 diag::err_sizeof_alignof_incomplete_type, 3668 ExprKind, ExprRange)) 3669 return true; 3670 3671 if (ExprType->isFunctionType()) { 3672 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3673 << ExprKind << ExprRange; 3674 return true; 3675 } 3676 3677 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3678 ExprKind)) 3679 return true; 3680 3681 return false; 3682 } 3683 3684 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3685 E = E->IgnoreParens(); 3686 3687 // Cannot know anything else if the expression is dependent. 3688 if (E->isTypeDependent()) 3689 return false; 3690 3691 if (E->getObjectKind() == OK_BitField) { 3692 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3693 << 1 << E->getSourceRange(); 3694 return true; 3695 } 3696 3697 ValueDecl *D = nullptr; 3698 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3699 D = DRE->getDecl(); 3700 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3701 D = ME->getMemberDecl(); 3702 } 3703 3704 // If it's a field, require the containing struct to have a 3705 // complete definition so that we can compute the layout. 3706 // 3707 // This can happen in C++11 onwards, either by naming the member 3708 // in a way that is not transformed into a member access expression 3709 // (in an unevaluated operand, for instance), or by naming the member 3710 // in a trailing-return-type. 3711 // 3712 // For the record, since __alignof__ on expressions is a GCC 3713 // extension, GCC seems to permit this but always gives the 3714 // nonsensical answer 0. 3715 // 3716 // We don't really need the layout here --- we could instead just 3717 // directly check for all the appropriate alignment-lowing 3718 // attributes --- but that would require duplicating a lot of 3719 // logic that just isn't worth duplicating for such a marginal 3720 // use-case. 3721 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3722 // Fast path this check, since we at least know the record has a 3723 // definition if we can find a member of it. 3724 if (!FD->getParent()->isCompleteDefinition()) { 3725 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3726 << E->getSourceRange(); 3727 return true; 3728 } 3729 3730 // Otherwise, if it's a field, and the field doesn't have 3731 // reference type, then it must have a complete type (or be a 3732 // flexible array member, which we explicitly want to 3733 // white-list anyway), which makes the following checks trivial. 3734 if (!FD->getType()->isReferenceType()) 3735 return false; 3736 } 3737 3738 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3739 } 3740 3741 bool Sema::CheckVecStepExpr(Expr *E) { 3742 E = E->IgnoreParens(); 3743 3744 // Cannot know anything else if the expression is dependent. 3745 if (E->isTypeDependent()) 3746 return false; 3747 3748 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3749 } 3750 3751 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3752 CapturingScopeInfo *CSI) { 3753 assert(T->isVariablyModifiedType()); 3754 assert(CSI != nullptr); 3755 3756 // We're going to walk down into the type and look for VLA expressions. 3757 do { 3758 const Type *Ty = T.getTypePtr(); 3759 switch (Ty->getTypeClass()) { 3760 #define TYPE(Class, Base) 3761 #define ABSTRACT_TYPE(Class, Base) 3762 #define NON_CANONICAL_TYPE(Class, Base) 3763 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3764 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3765 #include "clang/AST/TypeNodes.def" 3766 T = QualType(); 3767 break; 3768 // These types are never variably-modified. 3769 case Type::Builtin: 3770 case Type::Complex: 3771 case Type::Vector: 3772 case Type::ExtVector: 3773 case Type::Record: 3774 case Type::Enum: 3775 case Type::Elaborated: 3776 case Type::TemplateSpecialization: 3777 case Type::ObjCObject: 3778 case Type::ObjCInterface: 3779 case Type::ObjCObjectPointer: 3780 case Type::Pipe: 3781 llvm_unreachable("type class is never variably-modified!"); 3782 case Type::Adjusted: 3783 T = cast<AdjustedType>(Ty)->getOriginalType(); 3784 break; 3785 case Type::Decayed: 3786 T = cast<DecayedType>(Ty)->getPointeeType(); 3787 break; 3788 case Type::Pointer: 3789 T = cast<PointerType>(Ty)->getPointeeType(); 3790 break; 3791 case Type::BlockPointer: 3792 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3793 break; 3794 case Type::LValueReference: 3795 case Type::RValueReference: 3796 T = cast<ReferenceType>(Ty)->getPointeeType(); 3797 break; 3798 case Type::MemberPointer: 3799 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3800 break; 3801 case Type::ConstantArray: 3802 case Type::IncompleteArray: 3803 // Losing element qualification here is fine. 3804 T = cast<ArrayType>(Ty)->getElementType(); 3805 break; 3806 case Type::VariableArray: { 3807 // Losing element qualification here is fine. 3808 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3809 3810 // Unknown size indication requires no size computation. 3811 // Otherwise, evaluate and record it. 3812 if (auto Size = VAT->getSizeExpr()) { 3813 if (!CSI->isVLATypeCaptured(VAT)) { 3814 RecordDecl *CapRecord = nullptr; 3815 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3816 CapRecord = LSI->Lambda; 3817 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3818 CapRecord = CRSI->TheRecordDecl; 3819 } 3820 if (CapRecord) { 3821 auto ExprLoc = Size->getExprLoc(); 3822 auto SizeType = Context.getSizeType(); 3823 // Build the non-static data member. 3824 auto Field = 3825 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3826 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3827 /*BW*/ nullptr, /*Mutable*/ false, 3828 /*InitStyle*/ ICIS_NoInit); 3829 Field->setImplicit(true); 3830 Field->setAccess(AS_private); 3831 Field->setCapturedVLAType(VAT); 3832 CapRecord->addDecl(Field); 3833 3834 CSI->addVLATypeCapture(ExprLoc, SizeType); 3835 } 3836 } 3837 } 3838 T = VAT->getElementType(); 3839 break; 3840 } 3841 case Type::FunctionProto: 3842 case Type::FunctionNoProto: 3843 T = cast<FunctionType>(Ty)->getReturnType(); 3844 break; 3845 case Type::Paren: 3846 case Type::TypeOf: 3847 case Type::UnaryTransform: 3848 case Type::Attributed: 3849 case Type::SubstTemplateTypeParm: 3850 case Type::PackExpansion: 3851 // Keep walking after single level desugaring. 3852 T = T.getSingleStepDesugaredType(Context); 3853 break; 3854 case Type::Typedef: 3855 T = cast<TypedefType>(Ty)->desugar(); 3856 break; 3857 case Type::Decltype: 3858 T = cast<DecltypeType>(Ty)->desugar(); 3859 break; 3860 case Type::Auto: 3861 T = cast<AutoType>(Ty)->getDeducedType(); 3862 break; 3863 case Type::TypeOfExpr: 3864 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3865 break; 3866 case Type::Atomic: 3867 T = cast<AtomicType>(Ty)->getValueType(); 3868 break; 3869 } 3870 } while (!T.isNull() && T->isVariablyModifiedType()); 3871 } 3872 3873 /// \brief Build a sizeof or alignof expression given a type operand. 3874 ExprResult 3875 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3876 SourceLocation OpLoc, 3877 UnaryExprOrTypeTrait ExprKind, 3878 SourceRange R) { 3879 if (!TInfo) 3880 return ExprError(); 3881 3882 QualType T = TInfo->getType(); 3883 3884 if (!T->isDependentType() && 3885 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3886 return ExprError(); 3887 3888 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3889 if (auto *TT = T->getAs<TypedefType>()) { 3890 for (auto I = FunctionScopes.rbegin(), 3891 E = std::prev(FunctionScopes.rend()); 3892 I != E; ++I) { 3893 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 3894 if (CSI == nullptr) 3895 break; 3896 DeclContext *DC = nullptr; 3897 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 3898 DC = LSI->CallOperator; 3899 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 3900 DC = CRSI->TheCapturedDecl; 3901 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 3902 DC = BSI->TheDecl; 3903 if (DC) { 3904 if (DC->containsDecl(TT->getDecl())) 3905 break; 3906 captureVariablyModifiedType(Context, T, CSI); 3907 } 3908 } 3909 } 3910 } 3911 3912 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3913 return new (Context) UnaryExprOrTypeTraitExpr( 3914 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3915 } 3916 3917 /// \brief Build a sizeof or alignof expression given an expression 3918 /// operand. 3919 ExprResult 3920 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3921 UnaryExprOrTypeTrait ExprKind) { 3922 ExprResult PE = CheckPlaceholderExpr(E); 3923 if (PE.isInvalid()) 3924 return ExprError(); 3925 3926 E = PE.get(); 3927 3928 // Verify that the operand is valid. 3929 bool isInvalid = false; 3930 if (E->isTypeDependent()) { 3931 // Delay type-checking for type-dependent expressions. 3932 } else if (ExprKind == UETT_AlignOf) { 3933 isInvalid = CheckAlignOfExpr(*this, E); 3934 } else if (ExprKind == UETT_VecStep) { 3935 isInvalid = CheckVecStepExpr(E); 3936 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 3937 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 3938 isInvalid = true; 3939 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3940 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 3941 isInvalid = true; 3942 } else { 3943 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3944 } 3945 3946 if (isInvalid) 3947 return ExprError(); 3948 3949 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3950 PE = TransformToPotentiallyEvaluated(E); 3951 if (PE.isInvalid()) return ExprError(); 3952 E = PE.get(); 3953 } 3954 3955 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3956 return new (Context) UnaryExprOrTypeTraitExpr( 3957 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 3958 } 3959 3960 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3961 /// expr and the same for @c alignof and @c __alignof 3962 /// Note that the ArgRange is invalid if isType is false. 3963 ExprResult 3964 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3965 UnaryExprOrTypeTrait ExprKind, bool IsType, 3966 void *TyOrEx, SourceRange ArgRange) { 3967 // If error parsing type, ignore. 3968 if (!TyOrEx) return ExprError(); 3969 3970 if (IsType) { 3971 TypeSourceInfo *TInfo; 3972 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3973 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3974 } 3975 3976 Expr *ArgEx = (Expr *)TyOrEx; 3977 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3978 return Result; 3979 } 3980 3981 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3982 bool IsReal) { 3983 if (V.get()->isTypeDependent()) 3984 return S.Context.DependentTy; 3985 3986 // _Real and _Imag are only l-values for normal l-values. 3987 if (V.get()->getObjectKind() != OK_Ordinary) { 3988 V = S.DefaultLvalueConversion(V.get()); 3989 if (V.isInvalid()) 3990 return QualType(); 3991 } 3992 3993 // These operators return the element type of a complex type. 3994 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3995 return CT->getElementType(); 3996 3997 // Otherwise they pass through real integer and floating point types here. 3998 if (V.get()->getType()->isArithmeticType()) 3999 return V.get()->getType(); 4000 4001 // Test for placeholders. 4002 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4003 if (PR.isInvalid()) return QualType(); 4004 if (PR.get() != V.get()) { 4005 V = PR; 4006 return CheckRealImagOperand(S, V, Loc, IsReal); 4007 } 4008 4009 // Reject anything else. 4010 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4011 << (IsReal ? "__real" : "__imag"); 4012 return QualType(); 4013 } 4014 4015 4016 4017 ExprResult 4018 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4019 tok::TokenKind Kind, Expr *Input) { 4020 UnaryOperatorKind Opc; 4021 switch (Kind) { 4022 default: llvm_unreachable("Unknown unary op!"); 4023 case tok::plusplus: Opc = UO_PostInc; break; 4024 case tok::minusminus: Opc = UO_PostDec; break; 4025 } 4026 4027 // Since this might is a postfix expression, get rid of ParenListExprs. 4028 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4029 if (Result.isInvalid()) return ExprError(); 4030 Input = Result.get(); 4031 4032 return BuildUnaryOp(S, OpLoc, Opc, Input); 4033 } 4034 4035 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 4036 /// 4037 /// \return true on error 4038 static bool checkArithmeticOnObjCPointer(Sema &S, 4039 SourceLocation opLoc, 4040 Expr *op) { 4041 assert(op->getType()->isObjCObjectPointerType()); 4042 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4043 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4044 return false; 4045 4046 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4047 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4048 << op->getSourceRange(); 4049 return true; 4050 } 4051 4052 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4053 auto *BaseNoParens = Base->IgnoreParens(); 4054 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4055 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4056 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4057 } 4058 4059 ExprResult 4060 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4061 Expr *idx, SourceLocation rbLoc) { 4062 if (base && !base->getType().isNull() && 4063 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4064 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4065 /*Length=*/nullptr, rbLoc); 4066 4067 // Since this might be a postfix expression, get rid of ParenListExprs. 4068 if (isa<ParenListExpr>(base)) { 4069 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4070 if (result.isInvalid()) return ExprError(); 4071 base = result.get(); 4072 } 4073 4074 // Handle any non-overload placeholder types in the base and index 4075 // expressions. We can't handle overloads here because the other 4076 // operand might be an overloadable type, in which case the overload 4077 // resolution for the operator overload should get the first crack 4078 // at the overload. 4079 bool IsMSPropertySubscript = false; 4080 if (base->getType()->isNonOverloadPlaceholderType()) { 4081 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4082 if (!IsMSPropertySubscript) { 4083 ExprResult result = CheckPlaceholderExpr(base); 4084 if (result.isInvalid()) 4085 return ExprError(); 4086 base = result.get(); 4087 } 4088 } 4089 if (idx->getType()->isNonOverloadPlaceholderType()) { 4090 ExprResult result = CheckPlaceholderExpr(idx); 4091 if (result.isInvalid()) return ExprError(); 4092 idx = result.get(); 4093 } 4094 4095 // Build an unanalyzed expression if either operand is type-dependent. 4096 if (getLangOpts().CPlusPlus && 4097 (base->isTypeDependent() || idx->isTypeDependent())) { 4098 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4099 VK_LValue, OK_Ordinary, rbLoc); 4100 } 4101 4102 // MSDN, property (C++) 4103 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4104 // This attribute can also be used in the declaration of an empty array in a 4105 // class or structure definition. For example: 4106 // __declspec(property(get=GetX, put=PutX)) int x[]; 4107 // The above statement indicates that x[] can be used with one or more array 4108 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4109 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4110 if (IsMSPropertySubscript) { 4111 // Build MS property subscript expression if base is MS property reference 4112 // or MS property subscript. 4113 return new (Context) MSPropertySubscriptExpr( 4114 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4115 } 4116 4117 // Use C++ overloaded-operator rules if either operand has record 4118 // type. The spec says to do this if either type is *overloadable*, 4119 // but enum types can't declare subscript operators or conversion 4120 // operators, so there's nothing interesting for overload resolution 4121 // to do if there aren't any record types involved. 4122 // 4123 // ObjC pointers have their own subscripting logic that is not tied 4124 // to overload resolution and so should not take this path. 4125 if (getLangOpts().CPlusPlus && 4126 (base->getType()->isRecordType() || 4127 (!base->getType()->isObjCObjectPointerType() && 4128 idx->getType()->isRecordType()))) { 4129 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4130 } 4131 4132 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4133 } 4134 4135 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4136 Expr *LowerBound, 4137 SourceLocation ColonLoc, Expr *Length, 4138 SourceLocation RBLoc) { 4139 if (Base->getType()->isPlaceholderType() && 4140 !Base->getType()->isSpecificPlaceholderType( 4141 BuiltinType::OMPArraySection)) { 4142 ExprResult Result = CheckPlaceholderExpr(Base); 4143 if (Result.isInvalid()) 4144 return ExprError(); 4145 Base = Result.get(); 4146 } 4147 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4148 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4149 if (Result.isInvalid()) 4150 return ExprError(); 4151 LowerBound = Result.get(); 4152 } 4153 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4154 ExprResult Result = CheckPlaceholderExpr(Length); 4155 if (Result.isInvalid()) 4156 return ExprError(); 4157 Length = Result.get(); 4158 } 4159 4160 // Build an unanalyzed expression if either operand is type-dependent. 4161 if (Base->isTypeDependent() || 4162 (LowerBound && 4163 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4164 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4165 return new (Context) 4166 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4167 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4168 } 4169 4170 // Perform default conversions. 4171 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4172 QualType ResultTy; 4173 if (OriginalTy->isAnyPointerType()) { 4174 ResultTy = OriginalTy->getPointeeType(); 4175 } else if (OriginalTy->isArrayType()) { 4176 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4177 } else { 4178 return ExprError( 4179 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4180 << Base->getSourceRange()); 4181 } 4182 // C99 6.5.2.1p1 4183 if (LowerBound) { 4184 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4185 LowerBound); 4186 if (Res.isInvalid()) 4187 return ExprError(Diag(LowerBound->getExprLoc(), 4188 diag::err_omp_typecheck_section_not_integer) 4189 << 0 << LowerBound->getSourceRange()); 4190 LowerBound = Res.get(); 4191 4192 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4193 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4194 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4195 << 0 << LowerBound->getSourceRange(); 4196 } 4197 if (Length) { 4198 auto Res = 4199 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4200 if (Res.isInvalid()) 4201 return ExprError(Diag(Length->getExprLoc(), 4202 diag::err_omp_typecheck_section_not_integer) 4203 << 1 << Length->getSourceRange()); 4204 Length = Res.get(); 4205 4206 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4207 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4208 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4209 << 1 << Length->getSourceRange(); 4210 } 4211 4212 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4213 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4214 // type. Note that functions are not objects, and that (in C99 parlance) 4215 // incomplete types are not object types. 4216 if (ResultTy->isFunctionType()) { 4217 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4218 << ResultTy << Base->getSourceRange(); 4219 return ExprError(); 4220 } 4221 4222 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4223 diag::err_omp_section_incomplete_type, Base)) 4224 return ExprError(); 4225 4226 if (LowerBound) { 4227 llvm::APSInt LowerBoundValue; 4228 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4229 // OpenMP 4.0, [2.4 Array Sections] 4230 // The lower-bound and length must evaluate to non-negative integers. 4231 if (LowerBoundValue.isNegative()) { 4232 Diag(LowerBound->getExprLoc(), diag::err_omp_section_negative) 4233 << 0 << LowerBoundValue.toString(/*Radix=*/10, /*Signed=*/true) 4234 << LowerBound->getSourceRange(); 4235 return ExprError(); 4236 } 4237 } 4238 } 4239 4240 if (Length) { 4241 llvm::APSInt LengthValue; 4242 if (Length->EvaluateAsInt(LengthValue, Context)) { 4243 // OpenMP 4.0, [2.4 Array Sections] 4244 // The lower-bound and length must evaluate to non-negative integers. 4245 if (LengthValue.isNegative()) { 4246 Diag(Length->getExprLoc(), diag::err_omp_section_negative) 4247 << 1 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4248 << Length->getSourceRange(); 4249 return ExprError(); 4250 } 4251 } 4252 } else if (ColonLoc.isValid() && 4253 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4254 !OriginalTy->isVariableArrayType()))) { 4255 // OpenMP 4.0, [2.4 Array Sections] 4256 // When the size of the array dimension is not known, the length must be 4257 // specified explicitly. 4258 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4259 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4260 return ExprError(); 4261 } 4262 4263 return new (Context) 4264 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4265 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4266 } 4267 4268 ExprResult 4269 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4270 Expr *Idx, SourceLocation RLoc) { 4271 Expr *LHSExp = Base; 4272 Expr *RHSExp = Idx; 4273 4274 // Perform default conversions. 4275 if (!LHSExp->getType()->getAs<VectorType>()) { 4276 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4277 if (Result.isInvalid()) 4278 return ExprError(); 4279 LHSExp = Result.get(); 4280 } 4281 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4282 if (Result.isInvalid()) 4283 return ExprError(); 4284 RHSExp = Result.get(); 4285 4286 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4287 ExprValueKind VK = VK_LValue; 4288 ExprObjectKind OK = OK_Ordinary; 4289 4290 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4291 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4292 // in the subscript position. As a result, we need to derive the array base 4293 // and index from the expression types. 4294 Expr *BaseExpr, *IndexExpr; 4295 QualType ResultType; 4296 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4297 BaseExpr = LHSExp; 4298 IndexExpr = RHSExp; 4299 ResultType = Context.DependentTy; 4300 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4301 BaseExpr = LHSExp; 4302 IndexExpr = RHSExp; 4303 ResultType = PTy->getPointeeType(); 4304 } else if (const ObjCObjectPointerType *PTy = 4305 LHSTy->getAs<ObjCObjectPointerType>()) { 4306 BaseExpr = LHSExp; 4307 IndexExpr = RHSExp; 4308 4309 // Use custom logic if this should be the pseudo-object subscript 4310 // expression. 4311 if (!LangOpts.isSubscriptPointerArithmetic()) 4312 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4313 nullptr); 4314 4315 ResultType = PTy->getPointeeType(); 4316 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4317 // Handle the uncommon case of "123[Ptr]". 4318 BaseExpr = RHSExp; 4319 IndexExpr = LHSExp; 4320 ResultType = PTy->getPointeeType(); 4321 } else if (const ObjCObjectPointerType *PTy = 4322 RHSTy->getAs<ObjCObjectPointerType>()) { 4323 // Handle the uncommon case of "123[Ptr]". 4324 BaseExpr = RHSExp; 4325 IndexExpr = LHSExp; 4326 ResultType = PTy->getPointeeType(); 4327 if (!LangOpts.isSubscriptPointerArithmetic()) { 4328 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4329 << ResultType << BaseExpr->getSourceRange(); 4330 return ExprError(); 4331 } 4332 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4333 BaseExpr = LHSExp; // vectors: V[123] 4334 IndexExpr = RHSExp; 4335 VK = LHSExp->getValueKind(); 4336 if (VK != VK_RValue) 4337 OK = OK_VectorComponent; 4338 4339 // FIXME: need to deal with const... 4340 ResultType = VTy->getElementType(); 4341 } else if (LHSTy->isArrayType()) { 4342 // If we see an array that wasn't promoted by 4343 // DefaultFunctionArrayLvalueConversion, it must be an array that 4344 // wasn't promoted because of the C90 rule that doesn't 4345 // allow promoting non-lvalue arrays. Warn, then 4346 // force the promotion here. 4347 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4348 LHSExp->getSourceRange(); 4349 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4350 CK_ArrayToPointerDecay).get(); 4351 LHSTy = LHSExp->getType(); 4352 4353 BaseExpr = LHSExp; 4354 IndexExpr = RHSExp; 4355 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4356 } else if (RHSTy->isArrayType()) { 4357 // Same as previous, except for 123[f().a] case 4358 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4359 RHSExp->getSourceRange(); 4360 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4361 CK_ArrayToPointerDecay).get(); 4362 RHSTy = RHSExp->getType(); 4363 4364 BaseExpr = RHSExp; 4365 IndexExpr = LHSExp; 4366 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4367 } else { 4368 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4369 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4370 } 4371 // C99 6.5.2.1p1 4372 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4373 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4374 << IndexExpr->getSourceRange()); 4375 4376 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4377 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4378 && !IndexExpr->isTypeDependent()) 4379 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4380 4381 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4382 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4383 // type. Note that Functions are not objects, and that (in C99 parlance) 4384 // incomplete types are not object types. 4385 if (ResultType->isFunctionType()) { 4386 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4387 << ResultType << BaseExpr->getSourceRange(); 4388 return ExprError(); 4389 } 4390 4391 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4392 // GNU extension: subscripting on pointer to void 4393 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4394 << BaseExpr->getSourceRange(); 4395 4396 // C forbids expressions of unqualified void type from being l-values. 4397 // See IsCForbiddenLValueType. 4398 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4399 } else if (!ResultType->isDependentType() && 4400 RequireCompleteType(LLoc, ResultType, 4401 diag::err_subscript_incomplete_type, BaseExpr)) 4402 return ExprError(); 4403 4404 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4405 !ResultType.isCForbiddenLValueType()); 4406 4407 return new (Context) 4408 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4409 } 4410 4411 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4412 FunctionDecl *FD, 4413 ParmVarDecl *Param) { 4414 if (Param->hasUnparsedDefaultArg()) { 4415 Diag(CallLoc, 4416 diag::err_use_of_default_argument_to_function_declared_later) << 4417 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4418 Diag(UnparsedDefaultArgLocs[Param], 4419 diag::note_default_argument_declared_here); 4420 return ExprError(); 4421 } 4422 4423 if (Param->hasUninstantiatedDefaultArg()) { 4424 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4425 4426 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 4427 Param); 4428 4429 // Instantiate the expression. 4430 MultiLevelTemplateArgumentList MutiLevelArgList 4431 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4432 4433 InstantiatingTemplate Inst(*this, CallLoc, Param, 4434 MutiLevelArgList.getInnermost()); 4435 if (Inst.isInvalid()) 4436 return ExprError(); 4437 4438 ExprResult Result; 4439 { 4440 // C++ [dcl.fct.default]p5: 4441 // The names in the [default argument] expression are bound, and 4442 // the semantic constraints are checked, at the point where the 4443 // default argument expression appears. 4444 ContextRAII SavedContext(*this, FD); 4445 LocalInstantiationScope Local(*this); 4446 Result = SubstExpr(UninstExpr, MutiLevelArgList); 4447 } 4448 if (Result.isInvalid()) 4449 return ExprError(); 4450 4451 // Check the expression as an initializer for the parameter. 4452 InitializedEntity Entity 4453 = InitializedEntity::InitializeParameter(Context, Param); 4454 InitializationKind Kind 4455 = InitializationKind::CreateCopy(Param->getLocation(), 4456 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4457 Expr *ResultE = Result.getAs<Expr>(); 4458 4459 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4460 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4461 if (Result.isInvalid()) 4462 return ExprError(); 4463 4464 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4465 Param->getOuterLocStart()); 4466 if (Result.isInvalid()) 4467 return ExprError(); 4468 4469 // Remember the instantiated default argument. 4470 Param->setDefaultArg(Result.getAs<Expr>()); 4471 if (ASTMutationListener *L = getASTMutationListener()) { 4472 L->DefaultArgumentInstantiated(Param); 4473 } 4474 } 4475 4476 // If the default expression creates temporaries, we need to 4477 // push them to the current stack of expression temporaries so they'll 4478 // be properly destroyed. 4479 // FIXME: We should really be rebuilding the default argument with new 4480 // bound temporaries; see the comment in PR5810. 4481 // We don't need to do that with block decls, though, because 4482 // blocks in default argument expression can never capture anything. 4483 if (isa<ExprWithCleanups>(Param->getInit())) { 4484 // Set the "needs cleanups" bit regardless of whether there are 4485 // any explicit objects. 4486 ExprNeedsCleanups = true; 4487 4488 // Append all the objects to the cleanup list. Right now, this 4489 // should always be a no-op, because blocks in default argument 4490 // expressions should never be able to capture anything. 4491 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 4492 "default argument expression has capturing blocks?"); 4493 } 4494 4495 // We already type-checked the argument, so we know it works. 4496 // Just mark all of the declarations in this potentially-evaluated expression 4497 // as being "referenced". 4498 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4499 /*SkipLocalVariables=*/true); 4500 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4501 } 4502 4503 4504 Sema::VariadicCallType 4505 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4506 Expr *Fn) { 4507 if (Proto && Proto->isVariadic()) { 4508 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4509 return VariadicConstructor; 4510 else if (Fn && Fn->getType()->isBlockPointerType()) 4511 return VariadicBlock; 4512 else if (FDecl) { 4513 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4514 if (Method->isInstance()) 4515 return VariadicMethod; 4516 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4517 return VariadicMethod; 4518 return VariadicFunction; 4519 } 4520 return VariadicDoesNotApply; 4521 } 4522 4523 namespace { 4524 class FunctionCallCCC : public FunctionCallFilterCCC { 4525 public: 4526 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4527 unsigned NumArgs, MemberExpr *ME) 4528 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4529 FunctionName(FuncName) {} 4530 4531 bool ValidateCandidate(const TypoCorrection &candidate) override { 4532 if (!candidate.getCorrectionSpecifier() || 4533 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4534 return false; 4535 } 4536 4537 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4538 } 4539 4540 private: 4541 const IdentifierInfo *const FunctionName; 4542 }; 4543 } 4544 4545 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4546 FunctionDecl *FDecl, 4547 ArrayRef<Expr *> Args) { 4548 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4549 DeclarationName FuncName = FDecl->getDeclName(); 4550 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4551 4552 if (TypoCorrection Corrected = S.CorrectTypo( 4553 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4554 S.getScopeForContext(S.CurContext), nullptr, 4555 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4556 Args.size(), ME), 4557 Sema::CTK_ErrorRecovery)) { 4558 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4559 if (Corrected.isOverloaded()) { 4560 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4561 OverloadCandidateSet::iterator Best; 4562 for (NamedDecl *CD : Corrected) { 4563 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4564 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4565 OCS); 4566 } 4567 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4568 case OR_Success: 4569 ND = Best->FoundDecl; 4570 Corrected.setCorrectionDecl(ND); 4571 break; 4572 default: 4573 break; 4574 } 4575 } 4576 ND = ND->getUnderlyingDecl(); 4577 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4578 return Corrected; 4579 } 4580 } 4581 return TypoCorrection(); 4582 } 4583 4584 /// ConvertArgumentsForCall - Converts the arguments specified in 4585 /// Args/NumArgs to the parameter types of the function FDecl with 4586 /// function prototype Proto. Call is the call expression itself, and 4587 /// Fn is the function expression. For a C++ member function, this 4588 /// routine does not attempt to convert the object argument. Returns 4589 /// true if the call is ill-formed. 4590 bool 4591 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4592 FunctionDecl *FDecl, 4593 const FunctionProtoType *Proto, 4594 ArrayRef<Expr *> Args, 4595 SourceLocation RParenLoc, 4596 bool IsExecConfig) { 4597 // Bail out early if calling a builtin with custom typechecking. 4598 if (FDecl) 4599 if (unsigned ID = FDecl->getBuiltinID()) 4600 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4601 return false; 4602 4603 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4604 // assignment, to the types of the corresponding parameter, ... 4605 unsigned NumParams = Proto->getNumParams(); 4606 bool Invalid = false; 4607 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4608 unsigned FnKind = Fn->getType()->isBlockPointerType() 4609 ? 1 /* block */ 4610 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4611 : 0 /* function */); 4612 4613 // If too few arguments are available (and we don't have default 4614 // arguments for the remaining parameters), don't make the call. 4615 if (Args.size() < NumParams) { 4616 if (Args.size() < MinArgs) { 4617 TypoCorrection TC; 4618 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4619 unsigned diag_id = 4620 MinArgs == NumParams && !Proto->isVariadic() 4621 ? diag::err_typecheck_call_too_few_args_suggest 4622 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4623 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4624 << static_cast<unsigned>(Args.size()) 4625 << TC.getCorrectionRange()); 4626 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4627 Diag(RParenLoc, 4628 MinArgs == NumParams && !Proto->isVariadic() 4629 ? diag::err_typecheck_call_too_few_args_one 4630 : diag::err_typecheck_call_too_few_args_at_least_one) 4631 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4632 else 4633 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4634 ? diag::err_typecheck_call_too_few_args 4635 : diag::err_typecheck_call_too_few_args_at_least) 4636 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4637 << Fn->getSourceRange(); 4638 4639 // Emit the location of the prototype. 4640 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4641 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4642 << FDecl; 4643 4644 return true; 4645 } 4646 Call->setNumArgs(Context, NumParams); 4647 } 4648 4649 // If too many are passed and not variadic, error on the extras and drop 4650 // them. 4651 if (Args.size() > NumParams) { 4652 if (!Proto->isVariadic()) { 4653 TypoCorrection TC; 4654 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4655 unsigned diag_id = 4656 MinArgs == NumParams && !Proto->isVariadic() 4657 ? diag::err_typecheck_call_too_many_args_suggest 4658 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4659 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4660 << static_cast<unsigned>(Args.size()) 4661 << TC.getCorrectionRange()); 4662 } else if (NumParams == 1 && FDecl && 4663 FDecl->getParamDecl(0)->getDeclName()) 4664 Diag(Args[NumParams]->getLocStart(), 4665 MinArgs == NumParams 4666 ? diag::err_typecheck_call_too_many_args_one 4667 : diag::err_typecheck_call_too_many_args_at_most_one) 4668 << FnKind << FDecl->getParamDecl(0) 4669 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4670 << SourceRange(Args[NumParams]->getLocStart(), 4671 Args.back()->getLocEnd()); 4672 else 4673 Diag(Args[NumParams]->getLocStart(), 4674 MinArgs == NumParams 4675 ? diag::err_typecheck_call_too_many_args 4676 : diag::err_typecheck_call_too_many_args_at_most) 4677 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4678 << Fn->getSourceRange() 4679 << SourceRange(Args[NumParams]->getLocStart(), 4680 Args.back()->getLocEnd()); 4681 4682 // Emit the location of the prototype. 4683 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4684 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4685 << FDecl; 4686 4687 // This deletes the extra arguments. 4688 Call->setNumArgs(Context, NumParams); 4689 return true; 4690 } 4691 } 4692 SmallVector<Expr *, 8> AllArgs; 4693 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4694 4695 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4696 Proto, 0, Args, AllArgs, CallType); 4697 if (Invalid) 4698 return true; 4699 unsigned TotalNumArgs = AllArgs.size(); 4700 for (unsigned i = 0; i < TotalNumArgs; ++i) 4701 Call->setArg(i, AllArgs[i]); 4702 4703 return false; 4704 } 4705 4706 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4707 const FunctionProtoType *Proto, 4708 unsigned FirstParam, ArrayRef<Expr *> Args, 4709 SmallVectorImpl<Expr *> &AllArgs, 4710 VariadicCallType CallType, bool AllowExplicit, 4711 bool IsListInitialization) { 4712 unsigned NumParams = Proto->getNumParams(); 4713 bool Invalid = false; 4714 size_t ArgIx = 0; 4715 // Continue to check argument types (even if we have too few/many args). 4716 for (unsigned i = FirstParam; i < NumParams; i++) { 4717 QualType ProtoArgType = Proto->getParamType(i); 4718 4719 Expr *Arg; 4720 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4721 if (ArgIx < Args.size()) { 4722 Arg = Args[ArgIx++]; 4723 4724 if (RequireCompleteType(Arg->getLocStart(), 4725 ProtoArgType, 4726 diag::err_call_incomplete_argument, Arg)) 4727 return true; 4728 4729 // Strip the unbridged-cast placeholder expression off, if applicable. 4730 bool CFAudited = false; 4731 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4732 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4733 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4734 Arg = stripARCUnbridgedCast(Arg); 4735 else if (getLangOpts().ObjCAutoRefCount && 4736 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4737 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4738 CFAudited = true; 4739 4740 InitializedEntity Entity = 4741 Param ? InitializedEntity::InitializeParameter(Context, Param, 4742 ProtoArgType) 4743 : InitializedEntity::InitializeParameter( 4744 Context, ProtoArgType, Proto->isParamConsumed(i)); 4745 4746 // Remember that parameter belongs to a CF audited API. 4747 if (CFAudited) 4748 Entity.setParameterCFAudited(); 4749 4750 ExprResult ArgE = PerformCopyInitialization( 4751 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4752 if (ArgE.isInvalid()) 4753 return true; 4754 4755 Arg = ArgE.getAs<Expr>(); 4756 } else { 4757 assert(Param && "can't use default arguments without a known callee"); 4758 4759 ExprResult ArgExpr = 4760 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4761 if (ArgExpr.isInvalid()) 4762 return true; 4763 4764 Arg = ArgExpr.getAs<Expr>(); 4765 } 4766 4767 // Check for array bounds violations for each argument to the call. This 4768 // check only triggers warnings when the argument isn't a more complex Expr 4769 // with its own checking, such as a BinaryOperator. 4770 CheckArrayAccess(Arg); 4771 4772 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4773 CheckStaticArrayArgument(CallLoc, Param, Arg); 4774 4775 AllArgs.push_back(Arg); 4776 } 4777 4778 // If this is a variadic call, handle args passed through "...". 4779 if (CallType != VariadicDoesNotApply) { 4780 // Assume that extern "C" functions with variadic arguments that 4781 // return __unknown_anytype aren't *really* variadic. 4782 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4783 FDecl->isExternC()) { 4784 for (Expr *A : Args.slice(ArgIx)) { 4785 QualType paramType; // ignored 4786 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4787 Invalid |= arg.isInvalid(); 4788 AllArgs.push_back(arg.get()); 4789 } 4790 4791 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4792 } else { 4793 for (Expr *A : Args.slice(ArgIx)) { 4794 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4795 Invalid |= Arg.isInvalid(); 4796 AllArgs.push_back(Arg.get()); 4797 } 4798 } 4799 4800 // Check for array bounds violations. 4801 for (Expr *A : Args.slice(ArgIx)) 4802 CheckArrayAccess(A); 4803 } 4804 return Invalid; 4805 } 4806 4807 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4808 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4809 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4810 TL = DTL.getOriginalLoc(); 4811 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4812 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4813 << ATL.getLocalSourceRange(); 4814 } 4815 4816 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4817 /// array parameter, check that it is non-null, and that if it is formed by 4818 /// array-to-pointer decay, the underlying array is sufficiently large. 4819 /// 4820 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4821 /// array type derivation, then for each call to the function, the value of the 4822 /// corresponding actual argument shall provide access to the first element of 4823 /// an array with at least as many elements as specified by the size expression. 4824 void 4825 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4826 ParmVarDecl *Param, 4827 const Expr *ArgExpr) { 4828 // Static array parameters are not supported in C++. 4829 if (!Param || getLangOpts().CPlusPlus) 4830 return; 4831 4832 QualType OrigTy = Param->getOriginalType(); 4833 4834 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4835 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4836 return; 4837 4838 if (ArgExpr->isNullPointerConstant(Context, 4839 Expr::NPC_NeverValueDependent)) { 4840 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4841 DiagnoseCalleeStaticArrayParam(*this, Param); 4842 return; 4843 } 4844 4845 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4846 if (!CAT) 4847 return; 4848 4849 const ConstantArrayType *ArgCAT = 4850 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4851 if (!ArgCAT) 4852 return; 4853 4854 if (ArgCAT->getSize().ult(CAT->getSize())) { 4855 Diag(CallLoc, diag::warn_static_array_too_small) 4856 << ArgExpr->getSourceRange() 4857 << (unsigned) ArgCAT->getSize().getZExtValue() 4858 << (unsigned) CAT->getSize().getZExtValue(); 4859 DiagnoseCalleeStaticArrayParam(*this, Param); 4860 } 4861 } 4862 4863 /// Given a function expression of unknown-any type, try to rebuild it 4864 /// to have a function type. 4865 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4866 4867 /// Is the given type a placeholder that we need to lower out 4868 /// immediately during argument processing? 4869 static bool isPlaceholderToRemoveAsArg(QualType type) { 4870 // Placeholders are never sugared. 4871 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4872 if (!placeholder) return false; 4873 4874 switch (placeholder->getKind()) { 4875 // Ignore all the non-placeholder types. 4876 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4877 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4878 #include "clang/AST/BuiltinTypes.def" 4879 return false; 4880 4881 // We cannot lower out overload sets; they might validly be resolved 4882 // by the call machinery. 4883 case BuiltinType::Overload: 4884 return false; 4885 4886 // Unbridged casts in ARC can be handled in some call positions and 4887 // should be left in place. 4888 case BuiltinType::ARCUnbridgedCast: 4889 return false; 4890 4891 // Pseudo-objects should be converted as soon as possible. 4892 case BuiltinType::PseudoObject: 4893 return true; 4894 4895 // The debugger mode could theoretically but currently does not try 4896 // to resolve unknown-typed arguments based on known parameter types. 4897 case BuiltinType::UnknownAny: 4898 return true; 4899 4900 // These are always invalid as call arguments and should be reported. 4901 case BuiltinType::BoundMember: 4902 case BuiltinType::BuiltinFn: 4903 case BuiltinType::OMPArraySection: 4904 return true; 4905 4906 } 4907 llvm_unreachable("bad builtin type kind"); 4908 } 4909 4910 /// Check an argument list for placeholders that we won't try to 4911 /// handle later. 4912 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 4913 // Apply this processing to all the arguments at once instead of 4914 // dying at the first failure. 4915 bool hasInvalid = false; 4916 for (size_t i = 0, e = args.size(); i != e; i++) { 4917 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 4918 ExprResult result = S.CheckPlaceholderExpr(args[i]); 4919 if (result.isInvalid()) hasInvalid = true; 4920 else args[i] = result.get(); 4921 } else if (hasInvalid) { 4922 (void)S.CorrectDelayedTyposInExpr(args[i]); 4923 } 4924 } 4925 return hasInvalid; 4926 } 4927 4928 /// If a builtin function has a pointer argument with no explicit address 4929 /// space, then it should be able to accept a pointer to any address 4930 /// space as input. In order to do this, we need to replace the 4931 /// standard builtin declaration with one that uses the same address space 4932 /// as the call. 4933 /// 4934 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 4935 /// it does not contain any pointer arguments without 4936 /// an address space qualifer. Otherwise the rewritten 4937 /// FunctionDecl is returned. 4938 /// TODO: Handle pointer return types. 4939 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 4940 const FunctionDecl *FDecl, 4941 MultiExprArg ArgExprs) { 4942 4943 QualType DeclType = FDecl->getType(); 4944 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 4945 4946 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 4947 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 4948 return nullptr; 4949 4950 bool NeedsNewDecl = false; 4951 unsigned i = 0; 4952 SmallVector<QualType, 8> OverloadParams; 4953 4954 for (QualType ParamType : FT->param_types()) { 4955 4956 // Convert array arguments to pointer to simplify type lookup. 4957 Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get(); 4958 QualType ArgType = Arg->getType(); 4959 if (!ParamType->isPointerType() || 4960 ParamType.getQualifiers().hasAddressSpace() || 4961 !ArgType->isPointerType() || 4962 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 4963 OverloadParams.push_back(ParamType); 4964 continue; 4965 } 4966 4967 NeedsNewDecl = true; 4968 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 4969 4970 QualType PointeeType = ParamType->getPointeeType(); 4971 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 4972 OverloadParams.push_back(Context.getPointerType(PointeeType)); 4973 } 4974 4975 if (!NeedsNewDecl) 4976 return nullptr; 4977 4978 FunctionProtoType::ExtProtoInfo EPI; 4979 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 4980 OverloadParams, EPI); 4981 DeclContext *Parent = Context.getTranslationUnitDecl(); 4982 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 4983 FDecl->getLocation(), 4984 FDecl->getLocation(), 4985 FDecl->getIdentifier(), 4986 OverloadTy, 4987 /*TInfo=*/nullptr, 4988 SC_Extern, false, 4989 /*hasPrototype=*/true); 4990 SmallVector<ParmVarDecl*, 16> Params; 4991 FT = cast<FunctionProtoType>(OverloadTy); 4992 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 4993 QualType ParamType = FT->getParamType(i); 4994 ParmVarDecl *Parm = 4995 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 4996 SourceLocation(), nullptr, ParamType, 4997 /*TInfo=*/nullptr, SC_None, nullptr); 4998 Parm->setScopeInfo(0, i); 4999 Params.push_back(Parm); 5000 } 5001 OverloadDecl->setParams(Params); 5002 return OverloadDecl; 5003 } 5004 5005 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5006 /// This provides the location of the left/right parens and a list of comma 5007 /// locations. 5008 ExprResult 5009 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 5010 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5011 Expr *ExecConfig, bool IsExecConfig) { 5012 // Since this might be a postfix expression, get rid of ParenListExprs. 5013 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 5014 if (Result.isInvalid()) return ExprError(); 5015 Fn = Result.get(); 5016 5017 if (checkArgsForPlaceholders(*this, ArgExprs)) 5018 return ExprError(); 5019 5020 if (getLangOpts().CPlusPlus) { 5021 // If this is a pseudo-destructor expression, build the call immediately. 5022 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5023 if (!ArgExprs.empty()) { 5024 // Pseudo-destructor calls should not have any arguments. 5025 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 5026 << FixItHint::CreateRemoval( 5027 SourceRange(ArgExprs.front()->getLocStart(), 5028 ArgExprs.back()->getLocEnd())); 5029 } 5030 5031 return new (Context) 5032 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5033 } 5034 if (Fn->getType() == Context.PseudoObjectTy) { 5035 ExprResult result = CheckPlaceholderExpr(Fn); 5036 if (result.isInvalid()) return ExprError(); 5037 Fn = result.get(); 5038 } 5039 5040 // Determine whether this is a dependent call inside a C++ template, 5041 // in which case we won't do any semantic analysis now. 5042 // FIXME: Will need to cache the results of name lookup (including ADL) in 5043 // Fn. 5044 bool Dependent = false; 5045 if (Fn->isTypeDependent()) 5046 Dependent = true; 5047 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5048 Dependent = true; 5049 5050 if (Dependent) { 5051 if (ExecConfig) { 5052 return new (Context) CUDAKernelCallExpr( 5053 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5054 Context.DependentTy, VK_RValue, RParenLoc); 5055 } else { 5056 return new (Context) CallExpr( 5057 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5058 } 5059 } 5060 5061 // Determine whether this is a call to an object (C++ [over.call.object]). 5062 if (Fn->getType()->isRecordType()) 5063 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs, 5064 RParenLoc); 5065 5066 if (Fn->getType() == Context.UnknownAnyTy) { 5067 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5068 if (result.isInvalid()) return ExprError(); 5069 Fn = result.get(); 5070 } 5071 5072 if (Fn->getType() == Context.BoundMemberTy) { 5073 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 5074 } 5075 } 5076 5077 // Check for overloaded calls. This can happen even in C due to extensions. 5078 if (Fn->getType() == Context.OverloadTy) { 5079 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5080 5081 // We aren't supposed to apply this logic for if there's an '&' involved. 5082 if (!find.HasFormOfMemberPointer) { 5083 OverloadExpr *ovl = find.Expression; 5084 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5085 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 5086 RParenLoc, ExecConfig, 5087 /*AllowTypoCorrection=*/true, 5088 find.IsAddressOfOperand); 5089 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 5090 } 5091 } 5092 5093 // If we're directly calling a function, get the appropriate declaration. 5094 if (Fn->getType() == Context.UnknownAnyTy) { 5095 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5096 if (result.isInvalid()) return ExprError(); 5097 Fn = result.get(); 5098 } 5099 5100 Expr *NakedFn = Fn->IgnoreParens(); 5101 5102 bool CallingNDeclIndirectly = false; 5103 NamedDecl *NDecl = nullptr; 5104 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5105 if (UnOp->getOpcode() == UO_AddrOf) { 5106 CallingNDeclIndirectly = true; 5107 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5108 } 5109 } 5110 5111 if (isa<DeclRefExpr>(NakedFn)) { 5112 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5113 5114 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5115 if (FDecl && FDecl->getBuiltinID()) { 5116 // Rewrite the function decl for this builtin by replacing parameters 5117 // with no explicit address space with the address space of the arguments 5118 // in ArgExprs. 5119 if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5120 NDecl = FDecl; 5121 Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(), 5122 SourceLocation(), FDecl, false, 5123 SourceLocation(), FDecl->getType(), 5124 Fn->getValueKind(), FDecl); 5125 } 5126 } 5127 } else if (isa<MemberExpr>(NakedFn)) 5128 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5129 5130 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5131 if (CallingNDeclIndirectly && 5132 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 5133 Fn->getLocStart())) 5134 return ExprError(); 5135 5136 if (FD->hasAttr<EnableIfAttr>()) { 5137 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 5138 Diag(Fn->getLocStart(), 5139 isa<CXXMethodDecl>(FD) ? 5140 diag::err_ovl_no_viable_member_function_in_call : 5141 diag::err_ovl_no_viable_function_in_call) 5142 << FD << FD->getSourceRange(); 5143 Diag(FD->getLocation(), 5144 diag::note_ovl_candidate_disabled_by_enable_if_attr) 5145 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5146 } 5147 } 5148 } 5149 5150 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5151 ExecConfig, IsExecConfig); 5152 } 5153 5154 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5155 /// 5156 /// __builtin_astype( value, dst type ) 5157 /// 5158 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5159 SourceLocation BuiltinLoc, 5160 SourceLocation RParenLoc) { 5161 ExprValueKind VK = VK_RValue; 5162 ExprObjectKind OK = OK_Ordinary; 5163 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5164 QualType SrcTy = E->getType(); 5165 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5166 return ExprError(Diag(BuiltinLoc, 5167 diag::err_invalid_astype_of_different_size) 5168 << DstTy 5169 << SrcTy 5170 << E->getSourceRange()); 5171 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5172 } 5173 5174 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5175 /// provided arguments. 5176 /// 5177 /// __builtin_convertvector( value, dst type ) 5178 /// 5179 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5180 SourceLocation BuiltinLoc, 5181 SourceLocation RParenLoc) { 5182 TypeSourceInfo *TInfo; 5183 GetTypeFromParser(ParsedDestTy, &TInfo); 5184 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5185 } 5186 5187 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5188 /// i.e. an expression not of \p OverloadTy. The expression should 5189 /// unary-convert to an expression of function-pointer or 5190 /// block-pointer type. 5191 /// 5192 /// \param NDecl the declaration being called, if available 5193 ExprResult 5194 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5195 SourceLocation LParenLoc, 5196 ArrayRef<Expr *> Args, 5197 SourceLocation RParenLoc, 5198 Expr *Config, bool IsExecConfig) { 5199 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5200 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5201 5202 // Functions with 'interrupt' attribute cannot be called directly. 5203 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5204 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5205 return ExprError(); 5206 } 5207 5208 // Promote the function operand. 5209 // We special-case function promotion here because we only allow promoting 5210 // builtin functions to function pointers in the callee of a call. 5211 ExprResult Result; 5212 if (BuiltinID && 5213 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5214 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5215 CK_BuiltinFnToFnPtr).get(); 5216 } else { 5217 Result = CallExprUnaryConversions(Fn); 5218 } 5219 if (Result.isInvalid()) 5220 return ExprError(); 5221 Fn = Result.get(); 5222 5223 // Make the call expr early, before semantic checks. This guarantees cleanup 5224 // of arguments and function on error. 5225 CallExpr *TheCall; 5226 if (Config) 5227 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5228 cast<CallExpr>(Config), Args, 5229 Context.BoolTy, VK_RValue, 5230 RParenLoc); 5231 else 5232 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5233 VK_RValue, RParenLoc); 5234 5235 if (!getLangOpts().CPlusPlus) { 5236 // C cannot always handle TypoExpr nodes in builtin calls and direct 5237 // function calls as their argument checking don't necessarily handle 5238 // dependent types properly, so make sure any TypoExprs have been 5239 // dealt with. 5240 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5241 if (!Result.isUsable()) return ExprError(); 5242 TheCall = dyn_cast<CallExpr>(Result.get()); 5243 if (!TheCall) return Result; 5244 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5245 } 5246 5247 // Bail out early if calling a builtin with custom typechecking. 5248 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5249 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5250 5251 retry: 5252 const FunctionType *FuncT; 5253 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5254 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5255 // have type pointer to function". 5256 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5257 if (!FuncT) 5258 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5259 << Fn->getType() << Fn->getSourceRange()); 5260 } else if (const BlockPointerType *BPT = 5261 Fn->getType()->getAs<BlockPointerType>()) { 5262 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5263 } else { 5264 // Handle calls to expressions of unknown-any type. 5265 if (Fn->getType() == Context.UnknownAnyTy) { 5266 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5267 if (rewrite.isInvalid()) return ExprError(); 5268 Fn = rewrite.get(); 5269 TheCall->setCallee(Fn); 5270 goto retry; 5271 } 5272 5273 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5274 << Fn->getType() << Fn->getSourceRange()); 5275 } 5276 5277 if (getLangOpts().CUDA) { 5278 if (Config) { 5279 // CUDA: Kernel calls must be to global functions 5280 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5281 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5282 << FDecl->getName() << Fn->getSourceRange()); 5283 5284 // CUDA: Kernel function must have 'void' return type 5285 if (!FuncT->getReturnType()->isVoidType()) 5286 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5287 << Fn->getType() << Fn->getSourceRange()); 5288 } else { 5289 // CUDA: Calls to global functions must be configured 5290 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5291 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5292 << FDecl->getName() << Fn->getSourceRange()); 5293 } 5294 } 5295 5296 // Check for a valid return type 5297 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5298 FDecl)) 5299 return ExprError(); 5300 5301 // We know the result type of the call, set it. 5302 TheCall->setType(FuncT->getCallResultType(Context)); 5303 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5304 5305 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5306 if (Proto) { 5307 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5308 IsExecConfig)) 5309 return ExprError(); 5310 } else { 5311 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5312 5313 if (FDecl) { 5314 // Check if we have too few/too many template arguments, based 5315 // on our knowledge of the function definition. 5316 const FunctionDecl *Def = nullptr; 5317 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5318 Proto = Def->getType()->getAs<FunctionProtoType>(); 5319 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5320 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5321 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5322 } 5323 5324 // If the function we're calling isn't a function prototype, but we have 5325 // a function prototype from a prior declaratiom, use that prototype. 5326 if (!FDecl->hasPrototype()) 5327 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5328 } 5329 5330 // Promote the arguments (C99 6.5.2.2p6). 5331 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5332 Expr *Arg = Args[i]; 5333 5334 if (Proto && i < Proto->getNumParams()) { 5335 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5336 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5337 ExprResult ArgE = 5338 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5339 if (ArgE.isInvalid()) 5340 return true; 5341 5342 Arg = ArgE.getAs<Expr>(); 5343 5344 } else { 5345 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5346 5347 if (ArgE.isInvalid()) 5348 return true; 5349 5350 Arg = ArgE.getAs<Expr>(); 5351 } 5352 5353 if (RequireCompleteType(Arg->getLocStart(), 5354 Arg->getType(), 5355 diag::err_call_incomplete_argument, Arg)) 5356 return ExprError(); 5357 5358 TheCall->setArg(i, Arg); 5359 } 5360 } 5361 5362 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5363 if (!Method->isStatic()) 5364 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5365 << Fn->getSourceRange()); 5366 5367 // Check for sentinels 5368 if (NDecl) 5369 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5370 5371 // Do special checking on direct calls to functions. 5372 if (FDecl) { 5373 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5374 return ExprError(); 5375 5376 if (BuiltinID) 5377 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5378 } else if (NDecl) { 5379 if (CheckPointerCall(NDecl, TheCall, Proto)) 5380 return ExprError(); 5381 } else { 5382 if (CheckOtherCall(TheCall, Proto)) 5383 return ExprError(); 5384 } 5385 5386 return MaybeBindToTemporary(TheCall); 5387 } 5388 5389 ExprResult 5390 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5391 SourceLocation RParenLoc, Expr *InitExpr) { 5392 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5393 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5394 5395 TypeSourceInfo *TInfo; 5396 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5397 if (!TInfo) 5398 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5399 5400 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5401 } 5402 5403 ExprResult 5404 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5405 SourceLocation RParenLoc, Expr *LiteralExpr) { 5406 QualType literalType = TInfo->getType(); 5407 5408 if (literalType->isArrayType()) { 5409 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5410 diag::err_illegal_decl_array_incomplete_type, 5411 SourceRange(LParenLoc, 5412 LiteralExpr->getSourceRange().getEnd()))) 5413 return ExprError(); 5414 if (literalType->isVariableArrayType()) 5415 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5416 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5417 } else if (!literalType->isDependentType() && 5418 RequireCompleteType(LParenLoc, literalType, 5419 diag::err_typecheck_decl_incomplete_type, 5420 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5421 return ExprError(); 5422 5423 InitializedEntity Entity 5424 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5425 InitializationKind Kind 5426 = InitializationKind::CreateCStyleCast(LParenLoc, 5427 SourceRange(LParenLoc, RParenLoc), 5428 /*InitList=*/true); 5429 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5430 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5431 &literalType); 5432 if (Result.isInvalid()) 5433 return ExprError(); 5434 LiteralExpr = Result.get(); 5435 5436 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr; 5437 if (isFileScope && 5438 !LiteralExpr->isTypeDependent() && 5439 !LiteralExpr->isValueDependent() && 5440 !literalType->isDependentType()) { // 6.5.2.5p3 5441 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5442 return ExprError(); 5443 } 5444 5445 // In C, compound literals are l-values for some reason. 5446 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 5447 5448 return MaybeBindToTemporary( 5449 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5450 VK, LiteralExpr, isFileScope)); 5451 } 5452 5453 ExprResult 5454 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5455 SourceLocation RBraceLoc) { 5456 // Immediately handle non-overload placeholders. Overloads can be 5457 // resolved contextually, but everything else here can't. 5458 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5459 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5460 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5461 5462 // Ignore failures; dropping the entire initializer list because 5463 // of one failure would be terrible for indexing/etc. 5464 if (result.isInvalid()) continue; 5465 5466 InitArgList[I] = result.get(); 5467 } 5468 } 5469 5470 // Semantic analysis for initializers is done by ActOnDeclarator() and 5471 // CheckInitializer() - it requires knowledge of the object being intialized. 5472 5473 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5474 RBraceLoc); 5475 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5476 return E; 5477 } 5478 5479 /// Do an explicit extend of the given block pointer if we're in ARC. 5480 void Sema::maybeExtendBlockObject(ExprResult &E) { 5481 assert(E.get()->getType()->isBlockPointerType()); 5482 assert(E.get()->isRValue()); 5483 5484 // Only do this in an r-value context. 5485 if (!getLangOpts().ObjCAutoRefCount) return; 5486 5487 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5488 CK_ARCExtendBlockObject, E.get(), 5489 /*base path*/ nullptr, VK_RValue); 5490 ExprNeedsCleanups = true; 5491 } 5492 5493 /// Prepare a conversion of the given expression to an ObjC object 5494 /// pointer type. 5495 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5496 QualType type = E.get()->getType(); 5497 if (type->isObjCObjectPointerType()) { 5498 return CK_BitCast; 5499 } else if (type->isBlockPointerType()) { 5500 maybeExtendBlockObject(E); 5501 return CK_BlockPointerToObjCPointerCast; 5502 } else { 5503 assert(type->isPointerType()); 5504 return CK_CPointerToObjCPointerCast; 5505 } 5506 } 5507 5508 /// Prepares for a scalar cast, performing all the necessary stages 5509 /// except the final cast and returning the kind required. 5510 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5511 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5512 // Also, callers should have filtered out the invalid cases with 5513 // pointers. Everything else should be possible. 5514 5515 QualType SrcTy = Src.get()->getType(); 5516 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5517 return CK_NoOp; 5518 5519 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5520 case Type::STK_MemberPointer: 5521 llvm_unreachable("member pointer type in C"); 5522 5523 case Type::STK_CPointer: 5524 case Type::STK_BlockPointer: 5525 case Type::STK_ObjCObjectPointer: 5526 switch (DestTy->getScalarTypeKind()) { 5527 case Type::STK_CPointer: { 5528 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5529 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5530 if (SrcAS != DestAS) 5531 return CK_AddressSpaceConversion; 5532 return CK_BitCast; 5533 } 5534 case Type::STK_BlockPointer: 5535 return (SrcKind == Type::STK_BlockPointer 5536 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5537 case Type::STK_ObjCObjectPointer: 5538 if (SrcKind == Type::STK_ObjCObjectPointer) 5539 return CK_BitCast; 5540 if (SrcKind == Type::STK_CPointer) 5541 return CK_CPointerToObjCPointerCast; 5542 maybeExtendBlockObject(Src); 5543 return CK_BlockPointerToObjCPointerCast; 5544 case Type::STK_Bool: 5545 return CK_PointerToBoolean; 5546 case Type::STK_Integral: 5547 return CK_PointerToIntegral; 5548 case Type::STK_Floating: 5549 case Type::STK_FloatingComplex: 5550 case Type::STK_IntegralComplex: 5551 case Type::STK_MemberPointer: 5552 llvm_unreachable("illegal cast from pointer"); 5553 } 5554 llvm_unreachable("Should have returned before this"); 5555 5556 case Type::STK_Bool: // casting from bool is like casting from an integer 5557 case Type::STK_Integral: 5558 switch (DestTy->getScalarTypeKind()) { 5559 case Type::STK_CPointer: 5560 case Type::STK_ObjCObjectPointer: 5561 case Type::STK_BlockPointer: 5562 if (Src.get()->isNullPointerConstant(Context, 5563 Expr::NPC_ValueDependentIsNull)) 5564 return CK_NullToPointer; 5565 return CK_IntegralToPointer; 5566 case Type::STK_Bool: 5567 return CK_IntegralToBoolean; 5568 case Type::STK_Integral: 5569 return CK_IntegralCast; 5570 case Type::STK_Floating: 5571 return CK_IntegralToFloating; 5572 case Type::STK_IntegralComplex: 5573 Src = ImpCastExprToType(Src.get(), 5574 DestTy->castAs<ComplexType>()->getElementType(), 5575 CK_IntegralCast); 5576 return CK_IntegralRealToComplex; 5577 case Type::STK_FloatingComplex: 5578 Src = ImpCastExprToType(Src.get(), 5579 DestTy->castAs<ComplexType>()->getElementType(), 5580 CK_IntegralToFloating); 5581 return CK_FloatingRealToComplex; 5582 case Type::STK_MemberPointer: 5583 llvm_unreachable("member pointer type in C"); 5584 } 5585 llvm_unreachable("Should have returned before this"); 5586 5587 case Type::STK_Floating: 5588 switch (DestTy->getScalarTypeKind()) { 5589 case Type::STK_Floating: 5590 return CK_FloatingCast; 5591 case Type::STK_Bool: 5592 return CK_FloatingToBoolean; 5593 case Type::STK_Integral: 5594 return CK_FloatingToIntegral; 5595 case Type::STK_FloatingComplex: 5596 Src = ImpCastExprToType(Src.get(), 5597 DestTy->castAs<ComplexType>()->getElementType(), 5598 CK_FloatingCast); 5599 return CK_FloatingRealToComplex; 5600 case Type::STK_IntegralComplex: 5601 Src = ImpCastExprToType(Src.get(), 5602 DestTy->castAs<ComplexType>()->getElementType(), 5603 CK_FloatingToIntegral); 5604 return CK_IntegralRealToComplex; 5605 case Type::STK_CPointer: 5606 case Type::STK_ObjCObjectPointer: 5607 case Type::STK_BlockPointer: 5608 llvm_unreachable("valid float->pointer cast?"); 5609 case Type::STK_MemberPointer: 5610 llvm_unreachable("member pointer type in C"); 5611 } 5612 llvm_unreachable("Should have returned before this"); 5613 5614 case Type::STK_FloatingComplex: 5615 switch (DestTy->getScalarTypeKind()) { 5616 case Type::STK_FloatingComplex: 5617 return CK_FloatingComplexCast; 5618 case Type::STK_IntegralComplex: 5619 return CK_FloatingComplexToIntegralComplex; 5620 case Type::STK_Floating: { 5621 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5622 if (Context.hasSameType(ET, DestTy)) 5623 return CK_FloatingComplexToReal; 5624 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5625 return CK_FloatingCast; 5626 } 5627 case Type::STK_Bool: 5628 return CK_FloatingComplexToBoolean; 5629 case Type::STK_Integral: 5630 Src = ImpCastExprToType(Src.get(), 5631 SrcTy->castAs<ComplexType>()->getElementType(), 5632 CK_FloatingComplexToReal); 5633 return CK_FloatingToIntegral; 5634 case Type::STK_CPointer: 5635 case Type::STK_ObjCObjectPointer: 5636 case Type::STK_BlockPointer: 5637 llvm_unreachable("valid complex float->pointer cast?"); 5638 case Type::STK_MemberPointer: 5639 llvm_unreachable("member pointer type in C"); 5640 } 5641 llvm_unreachable("Should have returned before this"); 5642 5643 case Type::STK_IntegralComplex: 5644 switch (DestTy->getScalarTypeKind()) { 5645 case Type::STK_FloatingComplex: 5646 return CK_IntegralComplexToFloatingComplex; 5647 case Type::STK_IntegralComplex: 5648 return CK_IntegralComplexCast; 5649 case Type::STK_Integral: { 5650 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5651 if (Context.hasSameType(ET, DestTy)) 5652 return CK_IntegralComplexToReal; 5653 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5654 return CK_IntegralCast; 5655 } 5656 case Type::STK_Bool: 5657 return CK_IntegralComplexToBoolean; 5658 case Type::STK_Floating: 5659 Src = ImpCastExprToType(Src.get(), 5660 SrcTy->castAs<ComplexType>()->getElementType(), 5661 CK_IntegralComplexToReal); 5662 return CK_IntegralToFloating; 5663 case Type::STK_CPointer: 5664 case Type::STK_ObjCObjectPointer: 5665 case Type::STK_BlockPointer: 5666 llvm_unreachable("valid complex int->pointer cast?"); 5667 case Type::STK_MemberPointer: 5668 llvm_unreachable("member pointer type in C"); 5669 } 5670 llvm_unreachable("Should have returned before this"); 5671 } 5672 5673 llvm_unreachable("Unhandled scalar cast"); 5674 } 5675 5676 static bool breakDownVectorType(QualType type, uint64_t &len, 5677 QualType &eltType) { 5678 // Vectors are simple. 5679 if (const VectorType *vecType = type->getAs<VectorType>()) { 5680 len = vecType->getNumElements(); 5681 eltType = vecType->getElementType(); 5682 assert(eltType->isScalarType()); 5683 return true; 5684 } 5685 5686 // We allow lax conversion to and from non-vector types, but only if 5687 // they're real types (i.e. non-complex, non-pointer scalar types). 5688 if (!type->isRealType()) return false; 5689 5690 len = 1; 5691 eltType = type; 5692 return true; 5693 } 5694 5695 /// Are the two types lax-compatible vector types? That is, given 5696 /// that one of them is a vector, do they have equal storage sizes, 5697 /// where the storage size is the number of elements times the element 5698 /// size? 5699 /// 5700 /// This will also return false if either of the types is neither a 5701 /// vector nor a real type. 5702 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5703 assert(destTy->isVectorType() || srcTy->isVectorType()); 5704 5705 // Disallow lax conversions between scalars and ExtVectors (these 5706 // conversions are allowed for other vector types because common headers 5707 // depend on them). Most scalar OP ExtVector cases are handled by the 5708 // splat path anyway, which does what we want (convert, not bitcast). 5709 // What this rules out for ExtVectors is crazy things like char4*float. 5710 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5711 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5712 5713 uint64_t srcLen, destLen; 5714 QualType srcEltTy, destEltTy; 5715 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5716 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5717 5718 // ASTContext::getTypeSize will return the size rounded up to a 5719 // power of 2, so instead of using that, we need to use the raw 5720 // element size multiplied by the element count. 5721 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5722 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5723 5724 return (srcLen * srcEltSize == destLen * destEltSize); 5725 } 5726 5727 /// Is this a legal conversion between two types, one of which is 5728 /// known to be a vector type? 5729 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5730 assert(destTy->isVectorType() || srcTy->isVectorType()); 5731 5732 if (!Context.getLangOpts().LaxVectorConversions) 5733 return false; 5734 return areLaxCompatibleVectorTypes(srcTy, destTy); 5735 } 5736 5737 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5738 CastKind &Kind) { 5739 assert(VectorTy->isVectorType() && "Not a vector type!"); 5740 5741 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5742 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5743 return Diag(R.getBegin(), 5744 Ty->isVectorType() ? 5745 diag::err_invalid_conversion_between_vectors : 5746 diag::err_invalid_conversion_between_vector_and_integer) 5747 << VectorTy << Ty << R; 5748 } else 5749 return Diag(R.getBegin(), 5750 diag::err_invalid_conversion_between_vector_and_scalar) 5751 << VectorTy << Ty << R; 5752 5753 Kind = CK_BitCast; 5754 return false; 5755 } 5756 5757 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 5758 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 5759 5760 if (DestElemTy == SplattedExpr->getType()) 5761 return SplattedExpr; 5762 5763 assert(DestElemTy->isFloatingType() || 5764 DestElemTy->isIntegralOrEnumerationType()); 5765 5766 CastKind CK; 5767 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 5768 // OpenCL requires that we convert `true` boolean expressions to -1, but 5769 // only when splatting vectors. 5770 if (DestElemTy->isFloatingType()) { 5771 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 5772 // in two steps: boolean to signed integral, then to floating. 5773 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 5774 CK_BooleanToSignedIntegral); 5775 SplattedExpr = CastExprRes.get(); 5776 CK = CK_IntegralToFloating; 5777 } else { 5778 CK = CK_BooleanToSignedIntegral; 5779 } 5780 } else { 5781 ExprResult CastExprRes = SplattedExpr; 5782 CK = PrepareScalarCast(CastExprRes, DestElemTy); 5783 if (CastExprRes.isInvalid()) 5784 return ExprError(); 5785 SplattedExpr = CastExprRes.get(); 5786 } 5787 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 5788 } 5789 5790 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5791 Expr *CastExpr, CastKind &Kind) { 5792 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5793 5794 QualType SrcTy = CastExpr->getType(); 5795 5796 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5797 // an ExtVectorType. 5798 // In OpenCL, casts between vectors of different types are not allowed. 5799 // (See OpenCL 6.2). 5800 if (SrcTy->isVectorType()) { 5801 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 5802 || (getLangOpts().OpenCL && 5803 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5804 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5805 << DestTy << SrcTy << R; 5806 return ExprError(); 5807 } 5808 Kind = CK_BitCast; 5809 return CastExpr; 5810 } 5811 5812 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5813 // conversion will take place first from scalar to elt type, and then 5814 // splat from elt type to vector. 5815 if (SrcTy->isPointerType()) 5816 return Diag(R.getBegin(), 5817 diag::err_invalid_conversion_between_vector_and_scalar) 5818 << DestTy << SrcTy << R; 5819 5820 Kind = CK_VectorSplat; 5821 return prepareVectorSplat(DestTy, CastExpr); 5822 } 5823 5824 ExprResult 5825 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5826 Declarator &D, ParsedType &Ty, 5827 SourceLocation RParenLoc, Expr *CastExpr) { 5828 assert(!D.isInvalidType() && (CastExpr != nullptr) && 5829 "ActOnCastExpr(): missing type or expr"); 5830 5831 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5832 if (D.isInvalidType()) 5833 return ExprError(); 5834 5835 if (getLangOpts().CPlusPlus) { 5836 // Check that there are no default arguments (C++ only). 5837 CheckExtraCXXDefaultArguments(D); 5838 } else { 5839 // Make sure any TypoExprs have been dealt with. 5840 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 5841 if (!Res.isUsable()) 5842 return ExprError(); 5843 CastExpr = Res.get(); 5844 } 5845 5846 checkUnusedDeclAttributes(D); 5847 5848 QualType castType = castTInfo->getType(); 5849 Ty = CreateParsedType(castType, castTInfo); 5850 5851 bool isVectorLiteral = false; 5852 5853 // Check for an altivec or OpenCL literal, 5854 // i.e. all the elements are integer constants. 5855 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5856 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5857 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 5858 && castType->isVectorType() && (PE || PLE)) { 5859 if (PLE && PLE->getNumExprs() == 0) { 5860 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 5861 return ExprError(); 5862 } 5863 if (PE || PLE->getNumExprs() == 1) { 5864 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 5865 if (!E->getType()->isVectorType()) 5866 isVectorLiteral = true; 5867 } 5868 else 5869 isVectorLiteral = true; 5870 } 5871 5872 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 5873 // then handle it as such. 5874 if (isVectorLiteral) 5875 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 5876 5877 // If the Expr being casted is a ParenListExpr, handle it specially. 5878 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 5879 // sequence of BinOp comma operators. 5880 if (isa<ParenListExpr>(CastExpr)) { 5881 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 5882 if (Result.isInvalid()) return ExprError(); 5883 CastExpr = Result.get(); 5884 } 5885 5886 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 5887 !getSourceManager().isInSystemMacro(LParenLoc)) 5888 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 5889 5890 CheckTollFreeBridgeCast(castType, CastExpr); 5891 5892 CheckObjCBridgeRelatedCast(castType, CastExpr); 5893 5894 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 5895 } 5896 5897 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 5898 SourceLocation RParenLoc, Expr *E, 5899 TypeSourceInfo *TInfo) { 5900 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 5901 "Expected paren or paren list expression"); 5902 5903 Expr **exprs; 5904 unsigned numExprs; 5905 Expr *subExpr; 5906 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 5907 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 5908 LiteralLParenLoc = PE->getLParenLoc(); 5909 LiteralRParenLoc = PE->getRParenLoc(); 5910 exprs = PE->getExprs(); 5911 numExprs = PE->getNumExprs(); 5912 } else { // isa<ParenExpr> by assertion at function entrance 5913 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 5914 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 5915 subExpr = cast<ParenExpr>(E)->getSubExpr(); 5916 exprs = &subExpr; 5917 numExprs = 1; 5918 } 5919 5920 QualType Ty = TInfo->getType(); 5921 assert(Ty->isVectorType() && "Expected vector type"); 5922 5923 SmallVector<Expr *, 8> initExprs; 5924 const VectorType *VTy = Ty->getAs<VectorType>(); 5925 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 5926 5927 // '(...)' form of vector initialization in AltiVec: the number of 5928 // initializers must be one or must match the size of the vector. 5929 // If a single value is specified in the initializer then it will be 5930 // replicated to all the components of the vector 5931 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 5932 // The number of initializers must be one or must match the size of the 5933 // vector. If a single value is specified in the initializer then it will 5934 // be replicated to all the components of the vector 5935 if (numExprs == 1) { 5936 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5937 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5938 if (Literal.isInvalid()) 5939 return ExprError(); 5940 Literal = ImpCastExprToType(Literal.get(), ElemTy, 5941 PrepareScalarCast(Literal, ElemTy)); 5942 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 5943 } 5944 else if (numExprs < numElems) { 5945 Diag(E->getExprLoc(), 5946 diag::err_incorrect_number_of_vector_initializers); 5947 return ExprError(); 5948 } 5949 else 5950 initExprs.append(exprs, exprs + numExprs); 5951 } 5952 else { 5953 // For OpenCL, when the number of initializers is a single value, 5954 // it will be replicated to all components of the vector. 5955 if (getLangOpts().OpenCL && 5956 VTy->getVectorKind() == VectorType::GenericVector && 5957 numExprs == 1) { 5958 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5959 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5960 if (Literal.isInvalid()) 5961 return ExprError(); 5962 Literal = ImpCastExprToType(Literal.get(), ElemTy, 5963 PrepareScalarCast(Literal, ElemTy)); 5964 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 5965 } 5966 5967 initExprs.append(exprs, exprs + numExprs); 5968 } 5969 // FIXME: This means that pretty-printing the final AST will produce curly 5970 // braces instead of the original commas. 5971 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 5972 initExprs, LiteralRParenLoc); 5973 initE->setType(Ty); 5974 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 5975 } 5976 5977 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 5978 /// the ParenListExpr into a sequence of comma binary operators. 5979 ExprResult 5980 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 5981 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 5982 if (!E) 5983 return OrigExpr; 5984 5985 ExprResult Result(E->getExpr(0)); 5986 5987 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 5988 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 5989 E->getExpr(i)); 5990 5991 if (Result.isInvalid()) return ExprError(); 5992 5993 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 5994 } 5995 5996 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 5997 SourceLocation R, 5998 MultiExprArg Val) { 5999 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6000 return expr; 6001 } 6002 6003 /// \brief Emit a specialized diagnostic when one expression is a null pointer 6004 /// constant and the other is not a pointer. Returns true if a diagnostic is 6005 /// emitted. 6006 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6007 SourceLocation QuestionLoc) { 6008 Expr *NullExpr = LHSExpr; 6009 Expr *NonPointerExpr = RHSExpr; 6010 Expr::NullPointerConstantKind NullKind = 6011 NullExpr->isNullPointerConstant(Context, 6012 Expr::NPC_ValueDependentIsNotNull); 6013 6014 if (NullKind == Expr::NPCK_NotNull) { 6015 NullExpr = RHSExpr; 6016 NonPointerExpr = LHSExpr; 6017 NullKind = 6018 NullExpr->isNullPointerConstant(Context, 6019 Expr::NPC_ValueDependentIsNotNull); 6020 } 6021 6022 if (NullKind == Expr::NPCK_NotNull) 6023 return false; 6024 6025 if (NullKind == Expr::NPCK_ZeroExpression) 6026 return false; 6027 6028 if (NullKind == Expr::NPCK_ZeroLiteral) { 6029 // In this case, check to make sure that we got here from a "NULL" 6030 // string in the source code. 6031 NullExpr = NullExpr->IgnoreParenImpCasts(); 6032 SourceLocation loc = NullExpr->getExprLoc(); 6033 if (!findMacroSpelling(loc, "NULL")) 6034 return false; 6035 } 6036 6037 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6038 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6039 << NonPointerExpr->getType() << DiagType 6040 << NonPointerExpr->getSourceRange(); 6041 return true; 6042 } 6043 6044 /// \brief Return false if the condition expression is valid, true otherwise. 6045 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6046 QualType CondTy = Cond->getType(); 6047 6048 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6049 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6050 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6051 << CondTy << Cond->getSourceRange(); 6052 return true; 6053 } 6054 6055 // C99 6.5.15p2 6056 if (CondTy->isScalarType()) return false; 6057 6058 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6059 << CondTy << Cond->getSourceRange(); 6060 return true; 6061 } 6062 6063 /// \brief Handle when one or both operands are void type. 6064 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6065 ExprResult &RHS) { 6066 Expr *LHSExpr = LHS.get(); 6067 Expr *RHSExpr = RHS.get(); 6068 6069 if (!LHSExpr->getType()->isVoidType()) 6070 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6071 << RHSExpr->getSourceRange(); 6072 if (!RHSExpr->getType()->isVoidType()) 6073 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 6074 << LHSExpr->getSourceRange(); 6075 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6076 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6077 return S.Context.VoidTy; 6078 } 6079 6080 /// \brief Return false if the NullExpr can be promoted to PointerTy, 6081 /// true otherwise. 6082 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6083 QualType PointerTy) { 6084 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6085 !NullExpr.get()->isNullPointerConstant(S.Context, 6086 Expr::NPC_ValueDependentIsNull)) 6087 return true; 6088 6089 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6090 return false; 6091 } 6092 6093 /// \brief Checks compatibility between two pointers and return the resulting 6094 /// type. 6095 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6096 ExprResult &RHS, 6097 SourceLocation Loc) { 6098 QualType LHSTy = LHS.get()->getType(); 6099 QualType RHSTy = RHS.get()->getType(); 6100 6101 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6102 // Two identical pointers types are always compatible. 6103 return LHSTy; 6104 } 6105 6106 QualType lhptee, rhptee; 6107 6108 // Get the pointee types. 6109 bool IsBlockPointer = false; 6110 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6111 lhptee = LHSBTy->getPointeeType(); 6112 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6113 IsBlockPointer = true; 6114 } else { 6115 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6116 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6117 } 6118 6119 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6120 // differently qualified versions of compatible types, the result type is 6121 // a pointer to an appropriately qualified version of the composite 6122 // type. 6123 6124 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6125 // clause doesn't make sense for our extensions. E.g. address space 2 should 6126 // be incompatible with address space 3: they may live on different devices or 6127 // anything. 6128 Qualifiers lhQual = lhptee.getQualifiers(); 6129 Qualifiers rhQual = rhptee.getQualifiers(); 6130 6131 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6132 lhQual.removeCVRQualifiers(); 6133 rhQual.removeCVRQualifiers(); 6134 6135 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6136 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6137 6138 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6139 6140 if (CompositeTy.isNull()) { 6141 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6142 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6143 << RHS.get()->getSourceRange(); 6144 // In this situation, we assume void* type. No especially good 6145 // reason, but this is what gcc does, and we do have to pick 6146 // to get a consistent AST. 6147 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 6148 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6149 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6150 return incompatTy; 6151 } 6152 6153 // The pointer types are compatible. 6154 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 6155 if (IsBlockPointer) 6156 ResultTy = S.Context.getBlockPointerType(ResultTy); 6157 else 6158 ResultTy = S.Context.getPointerType(ResultTy); 6159 6160 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast); 6161 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast); 6162 return ResultTy; 6163 } 6164 6165 /// \brief Return the resulting type when the operands are both block pointers. 6166 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6167 ExprResult &LHS, 6168 ExprResult &RHS, 6169 SourceLocation Loc) { 6170 QualType LHSTy = LHS.get()->getType(); 6171 QualType RHSTy = RHS.get()->getType(); 6172 6173 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6174 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6175 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6176 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6177 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6178 return destType; 6179 } 6180 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6181 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6182 << RHS.get()->getSourceRange(); 6183 return QualType(); 6184 } 6185 6186 // We have 2 block pointer types. 6187 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6188 } 6189 6190 /// \brief Return the resulting type when the operands are both pointers. 6191 static QualType 6192 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6193 ExprResult &RHS, 6194 SourceLocation Loc) { 6195 // get the pointer types 6196 QualType LHSTy = LHS.get()->getType(); 6197 QualType RHSTy = RHS.get()->getType(); 6198 6199 // get the "pointed to" types 6200 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6201 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6202 6203 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6204 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6205 // Figure out necessary qualifiers (C99 6.5.15p6) 6206 QualType destPointee 6207 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6208 QualType destType = S.Context.getPointerType(destPointee); 6209 // Add qualifiers if necessary. 6210 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6211 // Promote to void*. 6212 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6213 return destType; 6214 } 6215 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6216 QualType destPointee 6217 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6218 QualType destType = S.Context.getPointerType(destPointee); 6219 // Add qualifiers if necessary. 6220 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6221 // Promote to void*. 6222 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6223 return destType; 6224 } 6225 6226 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6227 } 6228 6229 /// \brief Return false if the first expression is not an integer and the second 6230 /// expression is not a pointer, true otherwise. 6231 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6232 Expr* PointerExpr, SourceLocation Loc, 6233 bool IsIntFirstExpr) { 6234 if (!PointerExpr->getType()->isPointerType() || 6235 !Int.get()->getType()->isIntegerType()) 6236 return false; 6237 6238 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6239 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6240 6241 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6242 << Expr1->getType() << Expr2->getType() 6243 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6244 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6245 CK_IntegralToPointer); 6246 return true; 6247 } 6248 6249 /// \brief Simple conversion between integer and floating point types. 6250 /// 6251 /// Used when handling the OpenCL conditional operator where the 6252 /// condition is a vector while the other operands are scalar. 6253 /// 6254 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6255 /// types are either integer or floating type. Between the two 6256 /// operands, the type with the higher rank is defined as the "result 6257 /// type". The other operand needs to be promoted to the same type. No 6258 /// other type promotion is allowed. We cannot use 6259 /// UsualArithmeticConversions() for this purpose, since it always 6260 /// promotes promotable types. 6261 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6262 ExprResult &RHS, 6263 SourceLocation QuestionLoc) { 6264 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6265 if (LHS.isInvalid()) 6266 return QualType(); 6267 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6268 if (RHS.isInvalid()) 6269 return QualType(); 6270 6271 // For conversion purposes, we ignore any qualifiers. 6272 // For example, "const float" and "float" are equivalent. 6273 QualType LHSType = 6274 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6275 QualType RHSType = 6276 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6277 6278 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6279 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6280 << LHSType << LHS.get()->getSourceRange(); 6281 return QualType(); 6282 } 6283 6284 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6285 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6286 << RHSType << RHS.get()->getSourceRange(); 6287 return QualType(); 6288 } 6289 6290 // If both types are identical, no conversion is needed. 6291 if (LHSType == RHSType) 6292 return LHSType; 6293 6294 // Now handle "real" floating types (i.e. float, double, long double). 6295 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6296 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6297 /*IsCompAssign = */ false); 6298 6299 // Finally, we have two differing integer types. 6300 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6301 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6302 } 6303 6304 /// \brief Convert scalar operands to a vector that matches the 6305 /// condition in length. 6306 /// 6307 /// Used when handling the OpenCL conditional operator where the 6308 /// condition is a vector while the other operands are scalar. 6309 /// 6310 /// We first compute the "result type" for the scalar operands 6311 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6312 /// into a vector of that type where the length matches the condition 6313 /// vector type. s6.11.6 requires that the element types of the result 6314 /// and the condition must have the same number of bits. 6315 static QualType 6316 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6317 QualType CondTy, SourceLocation QuestionLoc) { 6318 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6319 if (ResTy.isNull()) return QualType(); 6320 6321 const VectorType *CV = CondTy->getAs<VectorType>(); 6322 assert(CV); 6323 6324 // Determine the vector result type 6325 unsigned NumElements = CV->getNumElements(); 6326 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6327 6328 // Ensure that all types have the same number of bits 6329 if (S.Context.getTypeSize(CV->getElementType()) 6330 != S.Context.getTypeSize(ResTy)) { 6331 // Since VectorTy is created internally, it does not pretty print 6332 // with an OpenCL name. Instead, we just print a description. 6333 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6334 SmallString<64> Str; 6335 llvm::raw_svector_ostream OS(Str); 6336 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6337 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6338 << CondTy << OS.str(); 6339 return QualType(); 6340 } 6341 6342 // Convert operands to the vector result type 6343 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6344 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6345 6346 return VectorTy; 6347 } 6348 6349 /// \brief Return false if this is a valid OpenCL condition vector 6350 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6351 SourceLocation QuestionLoc) { 6352 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6353 // integral type. 6354 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6355 assert(CondTy); 6356 QualType EleTy = CondTy->getElementType(); 6357 if (EleTy->isIntegerType()) return false; 6358 6359 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6360 << Cond->getType() << Cond->getSourceRange(); 6361 return true; 6362 } 6363 6364 /// \brief Return false if the vector condition type and the vector 6365 /// result type are compatible. 6366 /// 6367 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6368 /// number of elements, and their element types have the same number 6369 /// of bits. 6370 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6371 SourceLocation QuestionLoc) { 6372 const VectorType *CV = CondTy->getAs<VectorType>(); 6373 const VectorType *RV = VecResTy->getAs<VectorType>(); 6374 assert(CV && RV); 6375 6376 if (CV->getNumElements() != RV->getNumElements()) { 6377 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6378 << CondTy << VecResTy; 6379 return true; 6380 } 6381 6382 QualType CVE = CV->getElementType(); 6383 QualType RVE = RV->getElementType(); 6384 6385 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6386 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6387 << CondTy << VecResTy; 6388 return true; 6389 } 6390 6391 return false; 6392 } 6393 6394 /// \brief Return the resulting type for the conditional operator in 6395 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6396 /// s6.3.i) when the condition is a vector type. 6397 static QualType 6398 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6399 ExprResult &LHS, ExprResult &RHS, 6400 SourceLocation QuestionLoc) { 6401 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6402 if (Cond.isInvalid()) 6403 return QualType(); 6404 QualType CondTy = Cond.get()->getType(); 6405 6406 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6407 return QualType(); 6408 6409 // If either operand is a vector then find the vector type of the 6410 // result as specified in OpenCL v1.1 s6.3.i. 6411 if (LHS.get()->getType()->isVectorType() || 6412 RHS.get()->getType()->isVectorType()) { 6413 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6414 /*isCompAssign*/false, 6415 /*AllowBothBool*/true, 6416 /*AllowBoolConversions*/false); 6417 if (VecResTy.isNull()) return QualType(); 6418 // The result type must match the condition type as specified in 6419 // OpenCL v1.1 s6.11.6. 6420 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6421 return QualType(); 6422 return VecResTy; 6423 } 6424 6425 // Both operands are scalar. 6426 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6427 } 6428 6429 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6430 /// In that case, LHS = cond. 6431 /// C99 6.5.15 6432 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6433 ExprResult &RHS, ExprValueKind &VK, 6434 ExprObjectKind &OK, 6435 SourceLocation QuestionLoc) { 6436 6437 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6438 if (!LHSResult.isUsable()) return QualType(); 6439 LHS = LHSResult; 6440 6441 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6442 if (!RHSResult.isUsable()) return QualType(); 6443 RHS = RHSResult; 6444 6445 // C++ is sufficiently different to merit its own checker. 6446 if (getLangOpts().CPlusPlus) 6447 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6448 6449 VK = VK_RValue; 6450 OK = OK_Ordinary; 6451 6452 // The OpenCL operator with a vector condition is sufficiently 6453 // different to merit its own checker. 6454 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6455 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6456 6457 // First, check the condition. 6458 Cond = UsualUnaryConversions(Cond.get()); 6459 if (Cond.isInvalid()) 6460 return QualType(); 6461 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6462 return QualType(); 6463 6464 // Now check the two expressions. 6465 if (LHS.get()->getType()->isVectorType() || 6466 RHS.get()->getType()->isVectorType()) 6467 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6468 /*AllowBothBool*/true, 6469 /*AllowBoolConversions*/false); 6470 6471 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6472 if (LHS.isInvalid() || RHS.isInvalid()) 6473 return QualType(); 6474 6475 QualType LHSTy = LHS.get()->getType(); 6476 QualType RHSTy = RHS.get()->getType(); 6477 6478 // If both operands have arithmetic type, do the usual arithmetic conversions 6479 // to find a common type: C99 6.5.15p3,5. 6480 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6481 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6482 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6483 6484 return ResTy; 6485 } 6486 6487 // If both operands are the same structure or union type, the result is that 6488 // type. 6489 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6490 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6491 if (LHSRT->getDecl() == RHSRT->getDecl()) 6492 // "If both the operands have structure or union type, the result has 6493 // that type." This implies that CV qualifiers are dropped. 6494 return LHSTy.getUnqualifiedType(); 6495 // FIXME: Type of conditional expression must be complete in C mode. 6496 } 6497 6498 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6499 // The following || allows only one side to be void (a GCC-ism). 6500 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6501 return checkConditionalVoidType(*this, LHS, RHS); 6502 } 6503 6504 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6505 // the type of the other operand." 6506 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6507 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6508 6509 // All objective-c pointer type analysis is done here. 6510 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6511 QuestionLoc); 6512 if (LHS.isInvalid() || RHS.isInvalid()) 6513 return QualType(); 6514 if (!compositeType.isNull()) 6515 return compositeType; 6516 6517 6518 // Handle block pointer types. 6519 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6520 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6521 QuestionLoc); 6522 6523 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6524 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6525 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6526 QuestionLoc); 6527 6528 // GCC compatibility: soften pointer/integer mismatch. Note that 6529 // null pointers have been filtered out by this point. 6530 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6531 /*isIntFirstExpr=*/true)) 6532 return RHSTy; 6533 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6534 /*isIntFirstExpr=*/false)) 6535 return LHSTy; 6536 6537 // Emit a better diagnostic if one of the expressions is a null pointer 6538 // constant and the other is not a pointer type. In this case, the user most 6539 // likely forgot to take the address of the other expression. 6540 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6541 return QualType(); 6542 6543 // Otherwise, the operands are not compatible. 6544 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6545 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6546 << RHS.get()->getSourceRange(); 6547 return QualType(); 6548 } 6549 6550 /// FindCompositeObjCPointerType - Helper method to find composite type of 6551 /// two objective-c pointer types of the two input expressions. 6552 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6553 SourceLocation QuestionLoc) { 6554 QualType LHSTy = LHS.get()->getType(); 6555 QualType RHSTy = RHS.get()->getType(); 6556 6557 // Handle things like Class and struct objc_class*. Here we case the result 6558 // to the pseudo-builtin, because that will be implicitly cast back to the 6559 // redefinition type if an attempt is made to access its fields. 6560 if (LHSTy->isObjCClassType() && 6561 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6562 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6563 return LHSTy; 6564 } 6565 if (RHSTy->isObjCClassType() && 6566 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6567 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6568 return RHSTy; 6569 } 6570 // And the same for struct objc_object* / id 6571 if (LHSTy->isObjCIdType() && 6572 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6573 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6574 return LHSTy; 6575 } 6576 if (RHSTy->isObjCIdType() && 6577 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6578 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6579 return RHSTy; 6580 } 6581 // And the same for struct objc_selector* / SEL 6582 if (Context.isObjCSelType(LHSTy) && 6583 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6584 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6585 return LHSTy; 6586 } 6587 if (Context.isObjCSelType(RHSTy) && 6588 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6589 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6590 return RHSTy; 6591 } 6592 // Check constraints for Objective-C object pointers types. 6593 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6594 6595 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6596 // Two identical object pointer types are always compatible. 6597 return LHSTy; 6598 } 6599 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6600 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6601 QualType compositeType = LHSTy; 6602 6603 // If both operands are interfaces and either operand can be 6604 // assigned to the other, use that type as the composite 6605 // type. This allows 6606 // xxx ? (A*) a : (B*) b 6607 // where B is a subclass of A. 6608 // 6609 // Additionally, as for assignment, if either type is 'id' 6610 // allow silent coercion. Finally, if the types are 6611 // incompatible then make sure to use 'id' as the composite 6612 // type so the result is acceptable for sending messages to. 6613 6614 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6615 // It could return the composite type. 6616 if (!(compositeType = 6617 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6618 // Nothing more to do. 6619 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6620 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6621 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6622 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6623 } else if ((LHSTy->isObjCQualifiedIdType() || 6624 RHSTy->isObjCQualifiedIdType()) && 6625 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6626 // Need to handle "id<xx>" explicitly. 6627 // GCC allows qualified id and any Objective-C type to devolve to 6628 // id. Currently localizing to here until clear this should be 6629 // part of ObjCQualifiedIdTypesAreCompatible. 6630 compositeType = Context.getObjCIdType(); 6631 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6632 compositeType = Context.getObjCIdType(); 6633 } else { 6634 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6635 << LHSTy << RHSTy 6636 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6637 QualType incompatTy = Context.getObjCIdType(); 6638 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6639 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6640 return incompatTy; 6641 } 6642 // The object pointer types are compatible. 6643 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6644 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6645 return compositeType; 6646 } 6647 // Check Objective-C object pointer types and 'void *' 6648 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6649 if (getLangOpts().ObjCAutoRefCount) { 6650 // ARC forbids the implicit conversion of object pointers to 'void *', 6651 // so these types are not compatible. 6652 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6653 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6654 LHS = RHS = true; 6655 return QualType(); 6656 } 6657 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6658 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6659 QualType destPointee 6660 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6661 QualType destType = Context.getPointerType(destPointee); 6662 // Add qualifiers if necessary. 6663 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6664 // Promote to void*. 6665 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6666 return destType; 6667 } 6668 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6669 if (getLangOpts().ObjCAutoRefCount) { 6670 // ARC forbids the implicit conversion of object pointers to 'void *', 6671 // so these types are not compatible. 6672 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6673 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6674 LHS = RHS = true; 6675 return QualType(); 6676 } 6677 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6678 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6679 QualType destPointee 6680 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6681 QualType destType = Context.getPointerType(destPointee); 6682 // Add qualifiers if necessary. 6683 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6684 // Promote to void*. 6685 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6686 return destType; 6687 } 6688 return QualType(); 6689 } 6690 6691 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6692 /// ParenRange in parentheses. 6693 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6694 const PartialDiagnostic &Note, 6695 SourceRange ParenRange) { 6696 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 6697 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 6698 EndLoc.isValid()) { 6699 Self.Diag(Loc, Note) 6700 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 6701 << FixItHint::CreateInsertion(EndLoc, ")"); 6702 } else { 6703 // We can't display the parentheses, so just show the bare note. 6704 Self.Diag(Loc, Note) << ParenRange; 6705 } 6706 } 6707 6708 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 6709 return BinaryOperator::isAdditiveOp(Opc) || 6710 BinaryOperator::isMultiplicativeOp(Opc) || 6711 BinaryOperator::isShiftOp(Opc); 6712 } 6713 6714 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 6715 /// expression, either using a built-in or overloaded operator, 6716 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 6717 /// expression. 6718 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 6719 Expr **RHSExprs) { 6720 // Don't strip parenthesis: we should not warn if E is in parenthesis. 6721 E = E->IgnoreImpCasts(); 6722 E = E->IgnoreConversionOperator(); 6723 E = E->IgnoreImpCasts(); 6724 6725 // Built-in binary operator. 6726 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 6727 if (IsArithmeticOp(OP->getOpcode())) { 6728 *Opcode = OP->getOpcode(); 6729 *RHSExprs = OP->getRHS(); 6730 return true; 6731 } 6732 } 6733 6734 // Overloaded operator. 6735 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 6736 if (Call->getNumArgs() != 2) 6737 return false; 6738 6739 // Make sure this is really a binary operator that is safe to pass into 6740 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 6741 OverloadedOperatorKind OO = Call->getOperator(); 6742 if (OO < OO_Plus || OO > OO_Arrow || 6743 OO == OO_PlusPlus || OO == OO_MinusMinus) 6744 return false; 6745 6746 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 6747 if (IsArithmeticOp(OpKind)) { 6748 *Opcode = OpKind; 6749 *RHSExprs = Call->getArg(1); 6750 return true; 6751 } 6752 } 6753 6754 return false; 6755 } 6756 6757 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 6758 /// or is a logical expression such as (x==y) which has int type, but is 6759 /// commonly interpreted as boolean. 6760 static bool ExprLooksBoolean(Expr *E) { 6761 E = E->IgnoreParenImpCasts(); 6762 6763 if (E->getType()->isBooleanType()) 6764 return true; 6765 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 6766 return OP->isComparisonOp() || OP->isLogicalOp(); 6767 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 6768 return OP->getOpcode() == UO_LNot; 6769 if (E->getType()->isPointerType()) 6770 return true; 6771 6772 return false; 6773 } 6774 6775 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 6776 /// and binary operator are mixed in a way that suggests the programmer assumed 6777 /// the conditional operator has higher precedence, for example: 6778 /// "int x = a + someBinaryCondition ? 1 : 2". 6779 static void DiagnoseConditionalPrecedence(Sema &Self, 6780 SourceLocation OpLoc, 6781 Expr *Condition, 6782 Expr *LHSExpr, 6783 Expr *RHSExpr) { 6784 BinaryOperatorKind CondOpcode; 6785 Expr *CondRHS; 6786 6787 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 6788 return; 6789 if (!ExprLooksBoolean(CondRHS)) 6790 return; 6791 6792 // The condition is an arithmetic binary expression, with a right- 6793 // hand side that looks boolean, so warn. 6794 6795 Self.Diag(OpLoc, diag::warn_precedence_conditional) 6796 << Condition->getSourceRange() 6797 << BinaryOperator::getOpcodeStr(CondOpcode); 6798 6799 SuggestParentheses(Self, OpLoc, 6800 Self.PDiag(diag::note_precedence_silence) 6801 << BinaryOperator::getOpcodeStr(CondOpcode), 6802 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 6803 6804 SuggestParentheses(Self, OpLoc, 6805 Self.PDiag(diag::note_precedence_conditional_first), 6806 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 6807 } 6808 6809 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 6810 /// in the case of a the GNU conditional expr extension. 6811 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 6812 SourceLocation ColonLoc, 6813 Expr *CondExpr, Expr *LHSExpr, 6814 Expr *RHSExpr) { 6815 if (!getLangOpts().CPlusPlus) { 6816 // C cannot handle TypoExpr nodes in the condition because it 6817 // doesn't handle dependent types properly, so make sure any TypoExprs have 6818 // been dealt with before checking the operands. 6819 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 6820 if (!CondResult.isUsable()) return ExprError(); 6821 CondExpr = CondResult.get(); 6822 } 6823 6824 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 6825 // was the condition. 6826 OpaqueValueExpr *opaqueValue = nullptr; 6827 Expr *commonExpr = nullptr; 6828 if (!LHSExpr) { 6829 commonExpr = CondExpr; 6830 // Lower out placeholder types first. This is important so that we don't 6831 // try to capture a placeholder. This happens in few cases in C++; such 6832 // as Objective-C++'s dictionary subscripting syntax. 6833 if (commonExpr->hasPlaceholderType()) { 6834 ExprResult result = CheckPlaceholderExpr(commonExpr); 6835 if (!result.isUsable()) return ExprError(); 6836 commonExpr = result.get(); 6837 } 6838 // We usually want to apply unary conversions *before* saving, except 6839 // in the special case of a C++ l-value conditional. 6840 if (!(getLangOpts().CPlusPlus 6841 && !commonExpr->isTypeDependent() 6842 && commonExpr->getValueKind() == RHSExpr->getValueKind() 6843 && commonExpr->isGLValue() 6844 && commonExpr->isOrdinaryOrBitFieldObject() 6845 && RHSExpr->isOrdinaryOrBitFieldObject() 6846 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 6847 ExprResult commonRes = UsualUnaryConversions(commonExpr); 6848 if (commonRes.isInvalid()) 6849 return ExprError(); 6850 commonExpr = commonRes.get(); 6851 } 6852 6853 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 6854 commonExpr->getType(), 6855 commonExpr->getValueKind(), 6856 commonExpr->getObjectKind(), 6857 commonExpr); 6858 LHSExpr = CondExpr = opaqueValue; 6859 } 6860 6861 ExprValueKind VK = VK_RValue; 6862 ExprObjectKind OK = OK_Ordinary; 6863 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 6864 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 6865 VK, OK, QuestionLoc); 6866 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 6867 RHS.isInvalid()) 6868 return ExprError(); 6869 6870 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 6871 RHS.get()); 6872 6873 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 6874 6875 if (!commonExpr) 6876 return new (Context) 6877 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 6878 RHS.get(), result, VK, OK); 6879 6880 return new (Context) BinaryConditionalOperator( 6881 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 6882 ColonLoc, result, VK, OK); 6883 } 6884 6885 // checkPointerTypesForAssignment - This is a very tricky routine (despite 6886 // being closely modeled after the C99 spec:-). The odd characteristic of this 6887 // routine is it effectively iqnores the qualifiers on the top level pointee. 6888 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 6889 // FIXME: add a couple examples in this comment. 6890 static Sema::AssignConvertType 6891 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 6892 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6893 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6894 6895 // get the "pointed to" type (ignoring qualifiers at the top level) 6896 const Type *lhptee, *rhptee; 6897 Qualifiers lhq, rhq; 6898 std::tie(lhptee, lhq) = 6899 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 6900 std::tie(rhptee, rhq) = 6901 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 6902 6903 Sema::AssignConvertType ConvTy = Sema::Compatible; 6904 6905 // C99 6.5.16.1p1: This following citation is common to constraints 6906 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 6907 // qualifiers of the type *pointed to* by the right; 6908 6909 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 6910 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 6911 lhq.compatiblyIncludesObjCLifetime(rhq)) { 6912 // Ignore lifetime for further calculation. 6913 lhq.removeObjCLifetime(); 6914 rhq.removeObjCLifetime(); 6915 } 6916 6917 if (!lhq.compatiblyIncludes(rhq)) { 6918 // Treat address-space mismatches as fatal. TODO: address subspaces 6919 if (!lhq.isAddressSpaceSupersetOf(rhq)) 6920 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6921 6922 // It's okay to add or remove GC or lifetime qualifiers when converting to 6923 // and from void*. 6924 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 6925 .compatiblyIncludes( 6926 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 6927 && (lhptee->isVoidType() || rhptee->isVoidType())) 6928 ; // keep old 6929 6930 // Treat lifetime mismatches as fatal. 6931 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 6932 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6933 6934 // For GCC compatibility, other qualifier mismatches are treated 6935 // as still compatible in C. 6936 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6937 } 6938 6939 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 6940 // incomplete type and the other is a pointer to a qualified or unqualified 6941 // version of void... 6942 if (lhptee->isVoidType()) { 6943 if (rhptee->isIncompleteOrObjectType()) 6944 return ConvTy; 6945 6946 // As an extension, we allow cast to/from void* to function pointer. 6947 assert(rhptee->isFunctionType()); 6948 return Sema::FunctionVoidPointer; 6949 } 6950 6951 if (rhptee->isVoidType()) { 6952 if (lhptee->isIncompleteOrObjectType()) 6953 return ConvTy; 6954 6955 // As an extension, we allow cast to/from void* to function pointer. 6956 assert(lhptee->isFunctionType()); 6957 return Sema::FunctionVoidPointer; 6958 } 6959 6960 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 6961 // unqualified versions of compatible types, ... 6962 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 6963 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 6964 // Check if the pointee types are compatible ignoring the sign. 6965 // We explicitly check for char so that we catch "char" vs 6966 // "unsigned char" on systems where "char" is unsigned. 6967 if (lhptee->isCharType()) 6968 ltrans = S.Context.UnsignedCharTy; 6969 else if (lhptee->hasSignedIntegerRepresentation()) 6970 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 6971 6972 if (rhptee->isCharType()) 6973 rtrans = S.Context.UnsignedCharTy; 6974 else if (rhptee->hasSignedIntegerRepresentation()) 6975 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 6976 6977 if (ltrans == rtrans) { 6978 // Types are compatible ignoring the sign. Qualifier incompatibility 6979 // takes priority over sign incompatibility because the sign 6980 // warning can be disabled. 6981 if (ConvTy != Sema::Compatible) 6982 return ConvTy; 6983 6984 return Sema::IncompatiblePointerSign; 6985 } 6986 6987 // If we are a multi-level pointer, it's possible that our issue is simply 6988 // one of qualification - e.g. char ** -> const char ** is not allowed. If 6989 // the eventual target type is the same and the pointers have the same 6990 // level of indirection, this must be the issue. 6991 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 6992 do { 6993 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 6994 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 6995 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 6996 6997 if (lhptee == rhptee) 6998 return Sema::IncompatibleNestedPointerQualifiers; 6999 } 7000 7001 // General pointer incompatibility takes priority over qualifiers. 7002 return Sema::IncompatiblePointer; 7003 } 7004 if (!S.getLangOpts().CPlusPlus && 7005 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 7006 return Sema::IncompatiblePointer; 7007 return ConvTy; 7008 } 7009 7010 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7011 /// block pointer types are compatible or whether a block and normal pointer 7012 /// are compatible. It is more restrict than comparing two function pointer 7013 // types. 7014 static Sema::AssignConvertType 7015 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7016 QualType RHSType) { 7017 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7018 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7019 7020 QualType lhptee, rhptee; 7021 7022 // get the "pointed to" type (ignoring qualifiers at the top level) 7023 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7024 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7025 7026 // In C++, the types have to match exactly. 7027 if (S.getLangOpts().CPlusPlus) 7028 return Sema::IncompatibleBlockPointer; 7029 7030 Sema::AssignConvertType ConvTy = Sema::Compatible; 7031 7032 // For blocks we enforce that qualifiers are identical. 7033 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 7034 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7035 7036 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7037 return Sema::IncompatibleBlockPointer; 7038 7039 return ConvTy; 7040 } 7041 7042 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7043 /// for assignment compatibility. 7044 static Sema::AssignConvertType 7045 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7046 QualType RHSType) { 7047 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7048 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7049 7050 if (LHSType->isObjCBuiltinType()) { 7051 // Class is not compatible with ObjC object pointers. 7052 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7053 !RHSType->isObjCQualifiedClassType()) 7054 return Sema::IncompatiblePointer; 7055 return Sema::Compatible; 7056 } 7057 if (RHSType->isObjCBuiltinType()) { 7058 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7059 !LHSType->isObjCQualifiedClassType()) 7060 return Sema::IncompatiblePointer; 7061 return Sema::Compatible; 7062 } 7063 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7064 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7065 7066 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7067 // make an exception for id<P> 7068 !LHSType->isObjCQualifiedIdType()) 7069 return Sema::CompatiblePointerDiscardsQualifiers; 7070 7071 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7072 return Sema::Compatible; 7073 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7074 return Sema::IncompatibleObjCQualifiedId; 7075 return Sema::IncompatiblePointer; 7076 } 7077 7078 Sema::AssignConvertType 7079 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7080 QualType LHSType, QualType RHSType) { 7081 // Fake up an opaque expression. We don't actually care about what 7082 // cast operations are required, so if CheckAssignmentConstraints 7083 // adds casts to this they'll be wasted, but fortunately that doesn't 7084 // usually happen on valid code. 7085 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7086 ExprResult RHSPtr = &RHSExpr; 7087 CastKind K = CK_Invalid; 7088 7089 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7090 } 7091 7092 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7093 /// has code to accommodate several GCC extensions when type checking 7094 /// pointers. Here are some objectionable examples that GCC considers warnings: 7095 /// 7096 /// int a, *pint; 7097 /// short *pshort; 7098 /// struct foo *pfoo; 7099 /// 7100 /// pint = pshort; // warning: assignment from incompatible pointer type 7101 /// a = pint; // warning: assignment makes integer from pointer without a cast 7102 /// pint = a; // warning: assignment makes pointer from integer without a cast 7103 /// pint = pfoo; // warning: assignment from incompatible pointer type 7104 /// 7105 /// As a result, the code for dealing with pointers is more complex than the 7106 /// C99 spec dictates. 7107 /// 7108 /// Sets 'Kind' for any result kind except Incompatible. 7109 Sema::AssignConvertType 7110 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7111 CastKind &Kind, bool ConvertRHS) { 7112 QualType RHSType = RHS.get()->getType(); 7113 QualType OrigLHSType = LHSType; 7114 7115 // Get canonical types. We're not formatting these types, just comparing 7116 // them. 7117 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7118 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7119 7120 // Common case: no conversion required. 7121 if (LHSType == RHSType) { 7122 Kind = CK_NoOp; 7123 return Compatible; 7124 } 7125 7126 // If we have an atomic type, try a non-atomic assignment, then just add an 7127 // atomic qualification step. 7128 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7129 Sema::AssignConvertType result = 7130 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7131 if (result != Compatible) 7132 return result; 7133 if (Kind != CK_NoOp && ConvertRHS) 7134 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7135 Kind = CK_NonAtomicToAtomic; 7136 return Compatible; 7137 } 7138 7139 // If the left-hand side is a reference type, then we are in a 7140 // (rare!) case where we've allowed the use of references in C, 7141 // e.g., as a parameter type in a built-in function. In this case, 7142 // just make sure that the type referenced is compatible with the 7143 // right-hand side type. The caller is responsible for adjusting 7144 // LHSType so that the resulting expression does not have reference 7145 // type. 7146 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7147 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7148 Kind = CK_LValueBitCast; 7149 return Compatible; 7150 } 7151 return Incompatible; 7152 } 7153 7154 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7155 // to the same ExtVector type. 7156 if (LHSType->isExtVectorType()) { 7157 if (RHSType->isExtVectorType()) 7158 return Incompatible; 7159 if (RHSType->isArithmeticType()) { 7160 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7161 if (ConvertRHS) 7162 RHS = prepareVectorSplat(LHSType, RHS.get()); 7163 Kind = CK_VectorSplat; 7164 return Compatible; 7165 } 7166 } 7167 7168 // Conversions to or from vector type. 7169 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7170 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7171 // Allow assignments of an AltiVec vector type to an equivalent GCC 7172 // vector type and vice versa 7173 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7174 Kind = CK_BitCast; 7175 return Compatible; 7176 } 7177 7178 // If we are allowing lax vector conversions, and LHS and RHS are both 7179 // vectors, the total size only needs to be the same. This is a bitcast; 7180 // no bits are changed but the result type is different. 7181 if (isLaxVectorConversion(RHSType, LHSType)) { 7182 Kind = CK_BitCast; 7183 return IncompatibleVectors; 7184 } 7185 } 7186 return Incompatible; 7187 } 7188 7189 // Arithmetic conversions. 7190 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7191 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7192 if (ConvertRHS) 7193 Kind = PrepareScalarCast(RHS, LHSType); 7194 return Compatible; 7195 } 7196 7197 // Conversions to normal pointers. 7198 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7199 // U* -> T* 7200 if (isa<PointerType>(RHSType)) { 7201 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7202 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7203 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7204 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7205 } 7206 7207 // int -> T* 7208 if (RHSType->isIntegerType()) { 7209 Kind = CK_IntegralToPointer; // FIXME: null? 7210 return IntToPointer; 7211 } 7212 7213 // C pointers are not compatible with ObjC object pointers, 7214 // with two exceptions: 7215 if (isa<ObjCObjectPointerType>(RHSType)) { 7216 // - conversions to void* 7217 if (LHSPointer->getPointeeType()->isVoidType()) { 7218 Kind = CK_BitCast; 7219 return Compatible; 7220 } 7221 7222 // - conversions from 'Class' to the redefinition type 7223 if (RHSType->isObjCClassType() && 7224 Context.hasSameType(LHSType, 7225 Context.getObjCClassRedefinitionType())) { 7226 Kind = CK_BitCast; 7227 return Compatible; 7228 } 7229 7230 Kind = CK_BitCast; 7231 return IncompatiblePointer; 7232 } 7233 7234 // U^ -> void* 7235 if (RHSType->getAs<BlockPointerType>()) { 7236 if (LHSPointer->getPointeeType()->isVoidType()) { 7237 Kind = CK_BitCast; 7238 return Compatible; 7239 } 7240 } 7241 7242 return Incompatible; 7243 } 7244 7245 // Conversions to block pointers. 7246 if (isa<BlockPointerType>(LHSType)) { 7247 // U^ -> T^ 7248 if (RHSType->isBlockPointerType()) { 7249 Kind = CK_BitCast; 7250 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7251 } 7252 7253 // int or null -> T^ 7254 if (RHSType->isIntegerType()) { 7255 Kind = CK_IntegralToPointer; // FIXME: null 7256 return IntToBlockPointer; 7257 } 7258 7259 // id -> T^ 7260 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7261 Kind = CK_AnyPointerToBlockPointerCast; 7262 return Compatible; 7263 } 7264 7265 // void* -> T^ 7266 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7267 if (RHSPT->getPointeeType()->isVoidType()) { 7268 Kind = CK_AnyPointerToBlockPointerCast; 7269 return Compatible; 7270 } 7271 7272 return Incompatible; 7273 } 7274 7275 // Conversions to Objective-C pointers. 7276 if (isa<ObjCObjectPointerType>(LHSType)) { 7277 // A* -> B* 7278 if (RHSType->isObjCObjectPointerType()) { 7279 Kind = CK_BitCast; 7280 Sema::AssignConvertType result = 7281 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7282 if (getLangOpts().ObjCAutoRefCount && 7283 result == Compatible && 7284 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7285 result = IncompatibleObjCWeakRef; 7286 return result; 7287 } 7288 7289 // int or null -> A* 7290 if (RHSType->isIntegerType()) { 7291 Kind = CK_IntegralToPointer; // FIXME: null 7292 return IntToPointer; 7293 } 7294 7295 // In general, C pointers are not compatible with ObjC object pointers, 7296 // with two exceptions: 7297 if (isa<PointerType>(RHSType)) { 7298 Kind = CK_CPointerToObjCPointerCast; 7299 7300 // - conversions from 'void*' 7301 if (RHSType->isVoidPointerType()) { 7302 return Compatible; 7303 } 7304 7305 // - conversions to 'Class' from its redefinition type 7306 if (LHSType->isObjCClassType() && 7307 Context.hasSameType(RHSType, 7308 Context.getObjCClassRedefinitionType())) { 7309 return Compatible; 7310 } 7311 7312 return IncompatiblePointer; 7313 } 7314 7315 // Only under strict condition T^ is compatible with an Objective-C pointer. 7316 if (RHSType->isBlockPointerType() && 7317 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7318 if (ConvertRHS) 7319 maybeExtendBlockObject(RHS); 7320 Kind = CK_BlockPointerToObjCPointerCast; 7321 return Compatible; 7322 } 7323 7324 return Incompatible; 7325 } 7326 7327 // Conversions from pointers that are not covered by the above. 7328 if (isa<PointerType>(RHSType)) { 7329 // T* -> _Bool 7330 if (LHSType == Context.BoolTy) { 7331 Kind = CK_PointerToBoolean; 7332 return Compatible; 7333 } 7334 7335 // T* -> int 7336 if (LHSType->isIntegerType()) { 7337 Kind = CK_PointerToIntegral; 7338 return PointerToInt; 7339 } 7340 7341 return Incompatible; 7342 } 7343 7344 // Conversions from Objective-C pointers that are not covered by the above. 7345 if (isa<ObjCObjectPointerType>(RHSType)) { 7346 // T* -> _Bool 7347 if (LHSType == Context.BoolTy) { 7348 Kind = CK_PointerToBoolean; 7349 return Compatible; 7350 } 7351 7352 // T* -> int 7353 if (LHSType->isIntegerType()) { 7354 Kind = CK_PointerToIntegral; 7355 return PointerToInt; 7356 } 7357 7358 return Incompatible; 7359 } 7360 7361 // struct A -> struct B 7362 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7363 if (Context.typesAreCompatible(LHSType, RHSType)) { 7364 Kind = CK_NoOp; 7365 return Compatible; 7366 } 7367 } 7368 7369 return Incompatible; 7370 } 7371 7372 /// \brief Constructs a transparent union from an expression that is 7373 /// used to initialize the transparent union. 7374 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7375 ExprResult &EResult, QualType UnionType, 7376 FieldDecl *Field) { 7377 // Build an initializer list that designates the appropriate member 7378 // of the transparent union. 7379 Expr *E = EResult.get(); 7380 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7381 E, SourceLocation()); 7382 Initializer->setType(UnionType); 7383 Initializer->setInitializedFieldInUnion(Field); 7384 7385 // Build a compound literal constructing a value of the transparent 7386 // union type from this initializer list. 7387 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7388 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7389 VK_RValue, Initializer, false); 7390 } 7391 7392 Sema::AssignConvertType 7393 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7394 ExprResult &RHS) { 7395 QualType RHSType = RHS.get()->getType(); 7396 7397 // If the ArgType is a Union type, we want to handle a potential 7398 // transparent_union GCC extension. 7399 const RecordType *UT = ArgType->getAsUnionType(); 7400 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7401 return Incompatible; 7402 7403 // The field to initialize within the transparent union. 7404 RecordDecl *UD = UT->getDecl(); 7405 FieldDecl *InitField = nullptr; 7406 // It's compatible if the expression matches any of the fields. 7407 for (auto *it : UD->fields()) { 7408 if (it->getType()->isPointerType()) { 7409 // If the transparent union contains a pointer type, we allow: 7410 // 1) void pointer 7411 // 2) null pointer constant 7412 if (RHSType->isPointerType()) 7413 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7414 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7415 InitField = it; 7416 break; 7417 } 7418 7419 if (RHS.get()->isNullPointerConstant(Context, 7420 Expr::NPC_ValueDependentIsNull)) { 7421 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7422 CK_NullToPointer); 7423 InitField = it; 7424 break; 7425 } 7426 } 7427 7428 CastKind Kind = CK_Invalid; 7429 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7430 == Compatible) { 7431 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7432 InitField = it; 7433 break; 7434 } 7435 } 7436 7437 if (!InitField) 7438 return Incompatible; 7439 7440 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7441 return Compatible; 7442 } 7443 7444 Sema::AssignConvertType 7445 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7446 bool Diagnose, 7447 bool DiagnoseCFAudited, 7448 bool ConvertRHS) { 7449 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7450 // we can't avoid *all* modifications at the moment, so we need some somewhere 7451 // to put the updated value. 7452 ExprResult LocalRHS = CallerRHS; 7453 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7454 7455 if (getLangOpts().CPlusPlus) { 7456 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7457 // C++ 5.17p3: If the left operand is not of class type, the 7458 // expression is implicitly converted (C++ 4) to the 7459 // cv-unqualified type of the left operand. 7460 ExprResult Res; 7461 if (Diagnose) { 7462 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7463 AA_Assigning); 7464 } else { 7465 ImplicitConversionSequence ICS = 7466 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7467 /*SuppressUserConversions=*/false, 7468 /*AllowExplicit=*/false, 7469 /*InOverloadResolution=*/false, 7470 /*CStyle=*/false, 7471 /*AllowObjCWritebackConversion=*/false); 7472 if (ICS.isFailure()) 7473 return Incompatible; 7474 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7475 ICS, AA_Assigning); 7476 } 7477 if (Res.isInvalid()) 7478 return Incompatible; 7479 Sema::AssignConvertType result = Compatible; 7480 if (getLangOpts().ObjCAutoRefCount && 7481 !CheckObjCARCUnavailableWeakConversion(LHSType, 7482 RHS.get()->getType())) 7483 result = IncompatibleObjCWeakRef; 7484 RHS = Res; 7485 return result; 7486 } 7487 7488 // FIXME: Currently, we fall through and treat C++ classes like C 7489 // structures. 7490 // FIXME: We also fall through for atomics; not sure what should 7491 // happen there, though. 7492 } else if (RHS.get()->getType() == Context.OverloadTy) { 7493 // As a set of extensions to C, we support overloading on functions. These 7494 // functions need to be resolved here. 7495 DeclAccessPair DAP; 7496 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7497 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7498 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7499 else 7500 return Incompatible; 7501 } 7502 7503 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7504 // a null pointer constant. 7505 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7506 LHSType->isBlockPointerType()) && 7507 RHS.get()->isNullPointerConstant(Context, 7508 Expr::NPC_ValueDependentIsNull)) { 7509 if (Diagnose || ConvertRHS) { 7510 CastKind Kind; 7511 CXXCastPath Path; 7512 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 7513 /*IgnoreBaseAccess=*/false, Diagnose); 7514 if (ConvertRHS) 7515 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7516 } 7517 return Compatible; 7518 } 7519 7520 // This check seems unnatural, however it is necessary to ensure the proper 7521 // conversion of functions/arrays. If the conversion were done for all 7522 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7523 // expressions that suppress this implicit conversion (&, sizeof). 7524 // 7525 // Suppress this for references: C++ 8.5.3p5. 7526 if (!LHSType->isReferenceType()) { 7527 // FIXME: We potentially allocate here even if ConvertRHS is false. 7528 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 7529 if (RHS.isInvalid()) 7530 return Incompatible; 7531 } 7532 7533 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7534 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) { 7535 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol(); 7536 if (PDecl && !PDecl->hasDefinition()) { 7537 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7538 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7539 } 7540 } 7541 7542 CastKind Kind = CK_Invalid; 7543 Sema::AssignConvertType result = 7544 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 7545 7546 // C99 6.5.16.1p2: The value of the right operand is converted to the 7547 // type of the assignment expression. 7548 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7549 // so that we can use references in built-in functions even in C. 7550 // The getNonReferenceType() call makes sure that the resulting expression 7551 // does not have reference type. 7552 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7553 QualType Ty = LHSType.getNonLValueExprType(Context); 7554 Expr *E = RHS.get(); 7555 if (getLangOpts().ObjCAutoRefCount) 7556 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7557 Diagnose, DiagnoseCFAudited); 7558 if (getLangOpts().ObjC1 && 7559 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType, 7560 E->getType(), E, Diagnose) || 7561 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 7562 RHS = E; 7563 return Compatible; 7564 } 7565 7566 if (ConvertRHS) 7567 RHS = ImpCastExprToType(E, Ty, Kind); 7568 } 7569 return result; 7570 } 7571 7572 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7573 ExprResult &RHS) { 7574 Diag(Loc, diag::err_typecheck_invalid_operands) 7575 << LHS.get()->getType() << RHS.get()->getType() 7576 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7577 return QualType(); 7578 } 7579 7580 /// Try to convert a value of non-vector type to a vector type by converting 7581 /// the type to the element type of the vector and then performing a splat. 7582 /// If the language is OpenCL, we only use conversions that promote scalar 7583 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 7584 /// for float->int. 7585 /// 7586 /// \param scalar - if non-null, actually perform the conversions 7587 /// \return true if the operation fails (but without diagnosing the failure) 7588 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 7589 QualType scalarTy, 7590 QualType vectorEltTy, 7591 QualType vectorTy) { 7592 // The conversion to apply to the scalar before splatting it, 7593 // if necessary. 7594 CastKind scalarCast = CK_Invalid; 7595 7596 if (vectorEltTy->isIntegralType(S.Context)) { 7597 if (!scalarTy->isIntegralType(S.Context)) 7598 return true; 7599 if (S.getLangOpts().OpenCL && 7600 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 7601 return true; 7602 scalarCast = CK_IntegralCast; 7603 } else if (vectorEltTy->isRealFloatingType()) { 7604 if (scalarTy->isRealFloatingType()) { 7605 if (S.getLangOpts().OpenCL && 7606 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 7607 return true; 7608 scalarCast = CK_FloatingCast; 7609 } 7610 else if (scalarTy->isIntegralType(S.Context)) 7611 scalarCast = CK_IntegralToFloating; 7612 else 7613 return true; 7614 } else { 7615 return true; 7616 } 7617 7618 // Adjust scalar if desired. 7619 if (scalar) { 7620 if (scalarCast != CK_Invalid) 7621 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 7622 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 7623 } 7624 return false; 7625 } 7626 7627 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 7628 SourceLocation Loc, bool IsCompAssign, 7629 bool AllowBothBool, 7630 bool AllowBoolConversions) { 7631 if (!IsCompAssign) { 7632 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 7633 if (LHS.isInvalid()) 7634 return QualType(); 7635 } 7636 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7637 if (RHS.isInvalid()) 7638 return QualType(); 7639 7640 // For conversion purposes, we ignore any qualifiers. 7641 // For example, "const float" and "float" are equivalent. 7642 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 7643 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 7644 7645 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 7646 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 7647 assert(LHSVecType || RHSVecType); 7648 7649 // AltiVec-style "vector bool op vector bool" combinations are allowed 7650 // for some operators but not others. 7651 if (!AllowBothBool && 7652 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7653 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 7654 return InvalidOperands(Loc, LHS, RHS); 7655 7656 // If the vector types are identical, return. 7657 if (Context.hasSameType(LHSType, RHSType)) 7658 return LHSType; 7659 7660 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 7661 if (LHSVecType && RHSVecType && 7662 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7663 if (isa<ExtVectorType>(LHSVecType)) { 7664 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7665 return LHSType; 7666 } 7667 7668 if (!IsCompAssign) 7669 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7670 return RHSType; 7671 } 7672 7673 // AllowBoolConversions says that bool and non-bool AltiVec vectors 7674 // can be mixed, with the result being the non-bool type. The non-bool 7675 // operand must have integer element type. 7676 if (AllowBoolConversions && LHSVecType && RHSVecType && 7677 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 7678 (Context.getTypeSize(LHSVecType->getElementType()) == 7679 Context.getTypeSize(RHSVecType->getElementType()))) { 7680 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 7681 LHSVecType->getElementType()->isIntegerType() && 7682 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 7683 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7684 return LHSType; 7685 } 7686 if (!IsCompAssign && 7687 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7688 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 7689 RHSVecType->getElementType()->isIntegerType()) { 7690 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7691 return RHSType; 7692 } 7693 } 7694 7695 // If there's an ext-vector type and a scalar, try to convert the scalar to 7696 // the vector element type and splat. 7697 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 7698 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 7699 LHSVecType->getElementType(), LHSType)) 7700 return LHSType; 7701 } 7702 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 7703 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 7704 LHSType, RHSVecType->getElementType(), 7705 RHSType)) 7706 return RHSType; 7707 } 7708 7709 // If we're allowing lax vector conversions, only the total (data) size 7710 // needs to be the same. 7711 // FIXME: Should we really be allowing this? 7712 // FIXME: We really just pick the LHS type arbitrarily? 7713 if (isLaxVectorConversion(RHSType, LHSType)) { 7714 QualType resultType = LHSType; 7715 RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast); 7716 return resultType; 7717 } 7718 7719 // Okay, the expression is invalid. 7720 7721 // If there's a non-vector, non-real operand, diagnose that. 7722 if ((!RHSVecType && !RHSType->isRealType()) || 7723 (!LHSVecType && !LHSType->isRealType())) { 7724 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 7725 << LHSType << RHSType 7726 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7727 return QualType(); 7728 } 7729 7730 // OpenCL V1.1 6.2.6.p1: 7731 // If the operands are of more than one vector type, then an error shall 7732 // occur. Implicit conversions between vector types are not permitted, per 7733 // section 6.2.1. 7734 if (getLangOpts().OpenCL && 7735 RHSVecType && isa<ExtVectorType>(RHSVecType) && 7736 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 7737 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 7738 << RHSType; 7739 return QualType(); 7740 } 7741 7742 // Otherwise, use the generic diagnostic. 7743 Diag(Loc, diag::err_typecheck_vector_not_convertable) 7744 << LHSType << RHSType 7745 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7746 return QualType(); 7747 } 7748 7749 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 7750 // expression. These are mainly cases where the null pointer is used as an 7751 // integer instead of a pointer. 7752 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 7753 SourceLocation Loc, bool IsCompare) { 7754 // The canonical way to check for a GNU null is with isNullPointerConstant, 7755 // but we use a bit of a hack here for speed; this is a relatively 7756 // hot path, and isNullPointerConstant is slow. 7757 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 7758 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 7759 7760 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 7761 7762 // Avoid analyzing cases where the result will either be invalid (and 7763 // diagnosed as such) or entirely valid and not something to warn about. 7764 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 7765 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 7766 return; 7767 7768 // Comparison operations would not make sense with a null pointer no matter 7769 // what the other expression is. 7770 if (!IsCompare) { 7771 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 7772 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 7773 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 7774 return; 7775 } 7776 7777 // The rest of the operations only make sense with a null pointer 7778 // if the other expression is a pointer. 7779 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 7780 NonNullType->canDecayToPointerType()) 7781 return; 7782 7783 S.Diag(Loc, diag::warn_null_in_comparison_operation) 7784 << LHSNull /* LHS is NULL */ << NonNullType 7785 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7786 } 7787 7788 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 7789 ExprResult &RHS, 7790 SourceLocation Loc, bool IsDiv) { 7791 // Check for division/remainder by zero. 7792 llvm::APSInt RHSValue; 7793 if (!RHS.get()->isValueDependent() && 7794 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 7795 S.DiagRuntimeBehavior(Loc, RHS.get(), 7796 S.PDiag(diag::warn_remainder_division_by_zero) 7797 << IsDiv << RHS.get()->getSourceRange()); 7798 } 7799 7800 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 7801 SourceLocation Loc, 7802 bool IsCompAssign, bool IsDiv) { 7803 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7804 7805 if (LHS.get()->getType()->isVectorType() || 7806 RHS.get()->getType()->isVectorType()) 7807 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 7808 /*AllowBothBool*/getLangOpts().AltiVec, 7809 /*AllowBoolConversions*/false); 7810 7811 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 7812 if (LHS.isInvalid() || RHS.isInvalid()) 7813 return QualType(); 7814 7815 7816 if (compType.isNull() || !compType->isArithmeticType()) 7817 return InvalidOperands(Loc, LHS, RHS); 7818 if (IsDiv) 7819 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 7820 return compType; 7821 } 7822 7823 QualType Sema::CheckRemainderOperands( 7824 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 7825 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7826 7827 if (LHS.get()->getType()->isVectorType() || 7828 RHS.get()->getType()->isVectorType()) { 7829 if (LHS.get()->getType()->hasIntegerRepresentation() && 7830 RHS.get()->getType()->hasIntegerRepresentation()) 7831 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 7832 /*AllowBothBool*/getLangOpts().AltiVec, 7833 /*AllowBoolConversions*/false); 7834 return InvalidOperands(Loc, LHS, RHS); 7835 } 7836 7837 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 7838 if (LHS.isInvalid() || RHS.isInvalid()) 7839 return QualType(); 7840 7841 if (compType.isNull() || !compType->isIntegerType()) 7842 return InvalidOperands(Loc, LHS, RHS); 7843 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 7844 return compType; 7845 } 7846 7847 /// \brief Diagnose invalid arithmetic on two void pointers. 7848 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 7849 Expr *LHSExpr, Expr *RHSExpr) { 7850 S.Diag(Loc, S.getLangOpts().CPlusPlus 7851 ? diag::err_typecheck_pointer_arith_void_type 7852 : diag::ext_gnu_void_ptr) 7853 << 1 /* two pointers */ << LHSExpr->getSourceRange() 7854 << RHSExpr->getSourceRange(); 7855 } 7856 7857 /// \brief Diagnose invalid arithmetic on a void pointer. 7858 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 7859 Expr *Pointer) { 7860 S.Diag(Loc, S.getLangOpts().CPlusPlus 7861 ? diag::err_typecheck_pointer_arith_void_type 7862 : diag::ext_gnu_void_ptr) 7863 << 0 /* one pointer */ << Pointer->getSourceRange(); 7864 } 7865 7866 /// \brief Diagnose invalid arithmetic on two function pointers. 7867 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 7868 Expr *LHS, Expr *RHS) { 7869 assert(LHS->getType()->isAnyPointerType()); 7870 assert(RHS->getType()->isAnyPointerType()); 7871 S.Diag(Loc, S.getLangOpts().CPlusPlus 7872 ? diag::err_typecheck_pointer_arith_function_type 7873 : diag::ext_gnu_ptr_func_arith) 7874 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 7875 // We only show the second type if it differs from the first. 7876 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 7877 RHS->getType()) 7878 << RHS->getType()->getPointeeType() 7879 << LHS->getSourceRange() << RHS->getSourceRange(); 7880 } 7881 7882 /// \brief Diagnose invalid arithmetic on a function pointer. 7883 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 7884 Expr *Pointer) { 7885 assert(Pointer->getType()->isAnyPointerType()); 7886 S.Diag(Loc, S.getLangOpts().CPlusPlus 7887 ? diag::err_typecheck_pointer_arith_function_type 7888 : diag::ext_gnu_ptr_func_arith) 7889 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 7890 << 0 /* one pointer, so only one type */ 7891 << Pointer->getSourceRange(); 7892 } 7893 7894 /// \brief Emit error if Operand is incomplete pointer type 7895 /// 7896 /// \returns True if pointer has incomplete type 7897 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 7898 Expr *Operand) { 7899 QualType ResType = Operand->getType(); 7900 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 7901 ResType = ResAtomicType->getValueType(); 7902 7903 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 7904 QualType PointeeTy = ResType->getPointeeType(); 7905 return S.RequireCompleteType(Loc, PointeeTy, 7906 diag::err_typecheck_arithmetic_incomplete_type, 7907 PointeeTy, Operand->getSourceRange()); 7908 } 7909 7910 /// \brief Check the validity of an arithmetic pointer operand. 7911 /// 7912 /// If the operand has pointer type, this code will check for pointer types 7913 /// which are invalid in arithmetic operations. These will be diagnosed 7914 /// appropriately, including whether or not the use is supported as an 7915 /// extension. 7916 /// 7917 /// \returns True when the operand is valid to use (even if as an extension). 7918 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 7919 Expr *Operand) { 7920 QualType ResType = Operand->getType(); 7921 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 7922 ResType = ResAtomicType->getValueType(); 7923 7924 if (!ResType->isAnyPointerType()) return true; 7925 7926 QualType PointeeTy = ResType->getPointeeType(); 7927 if (PointeeTy->isVoidType()) { 7928 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 7929 return !S.getLangOpts().CPlusPlus; 7930 } 7931 if (PointeeTy->isFunctionType()) { 7932 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 7933 return !S.getLangOpts().CPlusPlus; 7934 } 7935 7936 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 7937 7938 return true; 7939 } 7940 7941 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 7942 /// operands. 7943 /// 7944 /// This routine will diagnose any invalid arithmetic on pointer operands much 7945 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 7946 /// for emitting a single diagnostic even for operations where both LHS and RHS 7947 /// are (potentially problematic) pointers. 7948 /// 7949 /// \returns True when the operand is valid to use (even if as an extension). 7950 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 7951 Expr *LHSExpr, Expr *RHSExpr) { 7952 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 7953 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 7954 if (!isLHSPointer && !isRHSPointer) return true; 7955 7956 QualType LHSPointeeTy, RHSPointeeTy; 7957 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 7958 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 7959 7960 // if both are pointers check if operation is valid wrt address spaces 7961 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 7962 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 7963 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 7964 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 7965 S.Diag(Loc, 7966 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7967 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 7968 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 7969 return false; 7970 } 7971 } 7972 7973 // Check for arithmetic on pointers to incomplete types. 7974 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 7975 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 7976 if (isLHSVoidPtr || isRHSVoidPtr) { 7977 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 7978 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 7979 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 7980 7981 return !S.getLangOpts().CPlusPlus; 7982 } 7983 7984 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 7985 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 7986 if (isLHSFuncPtr || isRHSFuncPtr) { 7987 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 7988 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 7989 RHSExpr); 7990 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 7991 7992 return !S.getLangOpts().CPlusPlus; 7993 } 7994 7995 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 7996 return false; 7997 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 7998 return false; 7999 8000 return true; 8001 } 8002 8003 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8004 /// literal. 8005 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8006 Expr *LHSExpr, Expr *RHSExpr) { 8007 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8008 Expr* IndexExpr = RHSExpr; 8009 if (!StrExpr) { 8010 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8011 IndexExpr = LHSExpr; 8012 } 8013 8014 bool IsStringPlusInt = StrExpr && 8015 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8016 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8017 return; 8018 8019 llvm::APSInt index; 8020 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8021 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8022 if (index.isNonNegative() && 8023 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8024 index.isUnsigned())) 8025 return; 8026 } 8027 8028 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8029 Self.Diag(OpLoc, diag::warn_string_plus_int) 8030 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8031 8032 // Only print a fixit for "str" + int, not for int + "str". 8033 if (IndexExpr == RHSExpr) { 8034 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8035 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8036 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8037 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8038 << FixItHint::CreateInsertion(EndLoc, "]"); 8039 } else 8040 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8041 } 8042 8043 /// \brief Emit a warning when adding a char literal to a string. 8044 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8045 Expr *LHSExpr, Expr *RHSExpr) { 8046 const Expr *StringRefExpr = LHSExpr; 8047 const CharacterLiteral *CharExpr = 8048 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8049 8050 if (!CharExpr) { 8051 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8052 StringRefExpr = RHSExpr; 8053 } 8054 8055 if (!CharExpr || !StringRefExpr) 8056 return; 8057 8058 const QualType StringType = StringRefExpr->getType(); 8059 8060 // Return if not a PointerType. 8061 if (!StringType->isAnyPointerType()) 8062 return; 8063 8064 // Return if not a CharacterType. 8065 if (!StringType->getPointeeType()->isAnyCharacterType()) 8066 return; 8067 8068 ASTContext &Ctx = Self.getASTContext(); 8069 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 8070 8071 const QualType CharType = CharExpr->getType(); 8072 if (!CharType->isAnyCharacterType() && 8073 CharType->isIntegerType() && 8074 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8075 Self.Diag(OpLoc, diag::warn_string_plus_char) 8076 << DiagRange << Ctx.CharTy; 8077 } else { 8078 Self.Diag(OpLoc, diag::warn_string_plus_char) 8079 << DiagRange << CharExpr->getType(); 8080 } 8081 8082 // Only print a fixit for str + char, not for char + str. 8083 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8084 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 8085 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8086 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 8087 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8088 << FixItHint::CreateInsertion(EndLoc, "]"); 8089 } else { 8090 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8091 } 8092 } 8093 8094 /// \brief Emit error when two pointers are incompatible. 8095 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8096 Expr *LHSExpr, Expr *RHSExpr) { 8097 assert(LHSExpr->getType()->isAnyPointerType()); 8098 assert(RHSExpr->getType()->isAnyPointerType()); 8099 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8100 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8101 << RHSExpr->getSourceRange(); 8102 } 8103 8104 // C99 6.5.6 8105 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8106 SourceLocation Loc, BinaryOperatorKind Opc, 8107 QualType* CompLHSTy) { 8108 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8109 8110 if (LHS.get()->getType()->isVectorType() || 8111 RHS.get()->getType()->isVectorType()) { 8112 QualType compType = CheckVectorOperands( 8113 LHS, RHS, Loc, CompLHSTy, 8114 /*AllowBothBool*/getLangOpts().AltiVec, 8115 /*AllowBoolConversions*/getLangOpts().ZVector); 8116 if (CompLHSTy) *CompLHSTy = compType; 8117 return compType; 8118 } 8119 8120 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8121 if (LHS.isInvalid() || RHS.isInvalid()) 8122 return QualType(); 8123 8124 // Diagnose "string literal" '+' int and string '+' "char literal". 8125 if (Opc == BO_Add) { 8126 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 8127 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 8128 } 8129 8130 // handle the common case first (both operands are arithmetic). 8131 if (!compType.isNull() && compType->isArithmeticType()) { 8132 if (CompLHSTy) *CompLHSTy = compType; 8133 return compType; 8134 } 8135 8136 // Type-checking. Ultimately the pointer's going to be in PExp; 8137 // note that we bias towards the LHS being the pointer. 8138 Expr *PExp = LHS.get(), *IExp = RHS.get(); 8139 8140 bool isObjCPointer; 8141 if (PExp->getType()->isPointerType()) { 8142 isObjCPointer = false; 8143 } else if (PExp->getType()->isObjCObjectPointerType()) { 8144 isObjCPointer = true; 8145 } else { 8146 std::swap(PExp, IExp); 8147 if (PExp->getType()->isPointerType()) { 8148 isObjCPointer = false; 8149 } else if (PExp->getType()->isObjCObjectPointerType()) { 8150 isObjCPointer = true; 8151 } else { 8152 return InvalidOperands(Loc, LHS, RHS); 8153 } 8154 } 8155 assert(PExp->getType()->isAnyPointerType()); 8156 8157 if (!IExp->getType()->isIntegerType()) 8158 return InvalidOperands(Loc, LHS, RHS); 8159 8160 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 8161 return QualType(); 8162 8163 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 8164 return QualType(); 8165 8166 // Check array bounds for pointer arithemtic 8167 CheckArrayAccess(PExp, IExp); 8168 8169 if (CompLHSTy) { 8170 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 8171 if (LHSTy.isNull()) { 8172 LHSTy = LHS.get()->getType(); 8173 if (LHSTy->isPromotableIntegerType()) 8174 LHSTy = Context.getPromotedIntegerType(LHSTy); 8175 } 8176 *CompLHSTy = LHSTy; 8177 } 8178 8179 return PExp->getType(); 8180 } 8181 8182 // C99 6.5.6 8183 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8184 SourceLocation Loc, 8185 QualType* CompLHSTy) { 8186 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8187 8188 if (LHS.get()->getType()->isVectorType() || 8189 RHS.get()->getType()->isVectorType()) { 8190 QualType compType = CheckVectorOperands( 8191 LHS, RHS, Loc, CompLHSTy, 8192 /*AllowBothBool*/getLangOpts().AltiVec, 8193 /*AllowBoolConversions*/getLangOpts().ZVector); 8194 if (CompLHSTy) *CompLHSTy = compType; 8195 return compType; 8196 } 8197 8198 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8199 if (LHS.isInvalid() || RHS.isInvalid()) 8200 return QualType(); 8201 8202 // Enforce type constraints: C99 6.5.6p3. 8203 8204 // Handle the common case first (both operands are arithmetic). 8205 if (!compType.isNull() && compType->isArithmeticType()) { 8206 if (CompLHSTy) *CompLHSTy = compType; 8207 return compType; 8208 } 8209 8210 // Either ptr - int or ptr - ptr. 8211 if (LHS.get()->getType()->isAnyPointerType()) { 8212 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8213 8214 // Diagnose bad cases where we step over interface counts. 8215 if (LHS.get()->getType()->isObjCObjectPointerType() && 8216 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8217 return QualType(); 8218 8219 // The result type of a pointer-int computation is the pointer type. 8220 if (RHS.get()->getType()->isIntegerType()) { 8221 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8222 return QualType(); 8223 8224 // Check array bounds for pointer arithemtic 8225 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8226 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8227 8228 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8229 return LHS.get()->getType(); 8230 } 8231 8232 // Handle pointer-pointer subtractions. 8233 if (const PointerType *RHSPTy 8234 = RHS.get()->getType()->getAs<PointerType>()) { 8235 QualType rpointee = RHSPTy->getPointeeType(); 8236 8237 if (getLangOpts().CPlusPlus) { 8238 // Pointee types must be the same: C++ [expr.add] 8239 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8240 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8241 } 8242 } else { 8243 // Pointee types must be compatible C99 6.5.6p3 8244 if (!Context.typesAreCompatible( 8245 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8246 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8247 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8248 return QualType(); 8249 } 8250 } 8251 8252 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8253 LHS.get(), RHS.get())) 8254 return QualType(); 8255 8256 // The pointee type may have zero size. As an extension, a structure or 8257 // union may have zero size or an array may have zero length. In this 8258 // case subtraction does not make sense. 8259 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8260 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8261 if (ElementSize.isZero()) { 8262 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8263 << rpointee.getUnqualifiedType() 8264 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8265 } 8266 } 8267 8268 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8269 return Context.getPointerDiffType(); 8270 } 8271 } 8272 8273 return InvalidOperands(Loc, LHS, RHS); 8274 } 8275 8276 static bool isScopedEnumerationType(QualType T) { 8277 if (const EnumType *ET = T->getAs<EnumType>()) 8278 return ET->getDecl()->isScoped(); 8279 return false; 8280 } 8281 8282 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8283 SourceLocation Loc, BinaryOperatorKind Opc, 8284 QualType LHSType) { 8285 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8286 // so skip remaining warnings as we don't want to modify values within Sema. 8287 if (S.getLangOpts().OpenCL) 8288 return; 8289 8290 llvm::APSInt Right; 8291 // Check right/shifter operand 8292 if (RHS.get()->isValueDependent() || 8293 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8294 return; 8295 8296 if (Right.isNegative()) { 8297 S.DiagRuntimeBehavior(Loc, RHS.get(), 8298 S.PDiag(diag::warn_shift_negative) 8299 << RHS.get()->getSourceRange()); 8300 return; 8301 } 8302 llvm::APInt LeftBits(Right.getBitWidth(), 8303 S.Context.getTypeSize(LHS.get()->getType())); 8304 if (Right.uge(LeftBits)) { 8305 S.DiagRuntimeBehavior(Loc, RHS.get(), 8306 S.PDiag(diag::warn_shift_gt_typewidth) 8307 << RHS.get()->getSourceRange()); 8308 return; 8309 } 8310 if (Opc != BO_Shl) 8311 return; 8312 8313 // When left shifting an ICE which is signed, we can check for overflow which 8314 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8315 // integers have defined behavior modulo one more than the maximum value 8316 // representable in the result type, so never warn for those. 8317 llvm::APSInt Left; 8318 if (LHS.get()->isValueDependent() || 8319 LHSType->hasUnsignedIntegerRepresentation() || 8320 !LHS.get()->EvaluateAsInt(Left, S.Context)) 8321 return; 8322 8323 // If LHS does not have a signed type and non-negative value 8324 // then, the behavior is undefined. Warn about it. 8325 if (Left.isNegative()) { 8326 S.DiagRuntimeBehavior(Loc, LHS.get(), 8327 S.PDiag(diag::warn_shift_lhs_negative) 8328 << LHS.get()->getSourceRange()); 8329 return; 8330 } 8331 8332 llvm::APInt ResultBits = 8333 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 8334 if (LeftBits.uge(ResultBits)) 8335 return; 8336 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 8337 Result = Result.shl(Right); 8338 8339 // Print the bit representation of the signed integer as an unsigned 8340 // hexadecimal number. 8341 SmallString<40> HexResult; 8342 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 8343 8344 // If we are only missing a sign bit, this is less likely to result in actual 8345 // bugs -- if the result is cast back to an unsigned type, it will have the 8346 // expected value. Thus we place this behind a different warning that can be 8347 // turned off separately if needed. 8348 if (LeftBits == ResultBits - 1) { 8349 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 8350 << HexResult << LHSType 8351 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8352 return; 8353 } 8354 8355 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 8356 << HexResult.str() << Result.getMinSignedBits() << LHSType 8357 << Left.getBitWidth() << LHS.get()->getSourceRange() 8358 << RHS.get()->getSourceRange(); 8359 } 8360 8361 /// \brief Return the resulting type when an OpenCL vector is shifted 8362 /// by a scalar or vector shift amount. 8363 static QualType checkOpenCLVectorShift(Sema &S, 8364 ExprResult &LHS, ExprResult &RHS, 8365 SourceLocation Loc, bool IsCompAssign) { 8366 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 8367 if (!LHS.get()->getType()->isVectorType()) { 8368 S.Diag(Loc, diag::err_shift_rhs_only_vector) 8369 << RHS.get()->getType() << LHS.get()->getType() 8370 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8371 return QualType(); 8372 } 8373 8374 if (!IsCompAssign) { 8375 LHS = S.UsualUnaryConversions(LHS.get()); 8376 if (LHS.isInvalid()) return QualType(); 8377 } 8378 8379 RHS = S.UsualUnaryConversions(RHS.get()); 8380 if (RHS.isInvalid()) return QualType(); 8381 8382 QualType LHSType = LHS.get()->getType(); 8383 const VectorType *LHSVecTy = LHSType->castAs<VectorType>(); 8384 QualType LHSEleType = LHSVecTy->getElementType(); 8385 8386 // Note that RHS might not be a vector. 8387 QualType RHSType = RHS.get()->getType(); 8388 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 8389 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 8390 8391 // OpenCL v1.1 s6.3.j says that the operands need to be integers. 8392 if (!LHSEleType->isIntegerType()) { 8393 S.Diag(Loc, diag::err_typecheck_expect_int) 8394 << LHS.get()->getType() << LHS.get()->getSourceRange(); 8395 return QualType(); 8396 } 8397 8398 if (!RHSEleType->isIntegerType()) { 8399 S.Diag(Loc, diag::err_typecheck_expect_int) 8400 << RHS.get()->getType() << RHS.get()->getSourceRange(); 8401 return QualType(); 8402 } 8403 8404 if (RHSVecTy) { 8405 // OpenCL v1.1 s6.3.j says that for vector types, the operators 8406 // are applied component-wise. So if RHS is a vector, then ensure 8407 // that the number of elements is the same as LHS... 8408 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 8409 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 8410 << LHS.get()->getType() << RHS.get()->getType() 8411 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8412 return QualType(); 8413 } 8414 } else { 8415 // ...else expand RHS to match the number of elements in LHS. 8416 QualType VecTy = 8417 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 8418 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 8419 } 8420 8421 return LHSType; 8422 } 8423 8424 // C99 6.5.7 8425 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 8426 SourceLocation Loc, BinaryOperatorKind Opc, 8427 bool IsCompAssign) { 8428 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8429 8430 // Vector shifts promote their scalar inputs to vector type. 8431 if (LHS.get()->getType()->isVectorType() || 8432 RHS.get()->getType()->isVectorType()) { 8433 if (LangOpts.OpenCL) 8434 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8435 if (LangOpts.ZVector) { 8436 // The shift operators for the z vector extensions work basically 8437 // like OpenCL shifts, except that neither the LHS nor the RHS is 8438 // allowed to be a "vector bool". 8439 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 8440 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 8441 return InvalidOperands(Loc, LHS, RHS); 8442 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 8443 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8444 return InvalidOperands(Loc, LHS, RHS); 8445 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8446 } 8447 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8448 /*AllowBothBool*/true, 8449 /*AllowBoolConversions*/false); 8450 } 8451 8452 // Shifts don't perform usual arithmetic conversions, they just do integer 8453 // promotions on each operand. C99 6.5.7p3 8454 8455 // For the LHS, do usual unary conversions, but then reset them away 8456 // if this is a compound assignment. 8457 ExprResult OldLHS = LHS; 8458 LHS = UsualUnaryConversions(LHS.get()); 8459 if (LHS.isInvalid()) 8460 return QualType(); 8461 QualType LHSType = LHS.get()->getType(); 8462 if (IsCompAssign) LHS = OldLHS; 8463 8464 // The RHS is simpler. 8465 RHS = UsualUnaryConversions(RHS.get()); 8466 if (RHS.isInvalid()) 8467 return QualType(); 8468 QualType RHSType = RHS.get()->getType(); 8469 8470 // C99 6.5.7p2: Each of the operands shall have integer type. 8471 if (!LHSType->hasIntegerRepresentation() || 8472 !RHSType->hasIntegerRepresentation()) 8473 return InvalidOperands(Loc, LHS, RHS); 8474 8475 // C++0x: Don't allow scoped enums. FIXME: Use something better than 8476 // hasIntegerRepresentation() above instead of this. 8477 if (isScopedEnumerationType(LHSType) || 8478 isScopedEnumerationType(RHSType)) { 8479 return InvalidOperands(Loc, LHS, RHS); 8480 } 8481 // Sanity-check shift operands 8482 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 8483 8484 // "The type of the result is that of the promoted left operand." 8485 return LHSType; 8486 } 8487 8488 static bool IsWithinTemplateSpecialization(Decl *D) { 8489 if (DeclContext *DC = D->getDeclContext()) { 8490 if (isa<ClassTemplateSpecializationDecl>(DC)) 8491 return true; 8492 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 8493 return FD->isFunctionTemplateSpecialization(); 8494 } 8495 return false; 8496 } 8497 8498 /// If two different enums are compared, raise a warning. 8499 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 8500 Expr *RHS) { 8501 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 8502 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 8503 8504 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 8505 if (!LHSEnumType) 8506 return; 8507 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 8508 if (!RHSEnumType) 8509 return; 8510 8511 // Ignore anonymous enums. 8512 if (!LHSEnumType->getDecl()->getIdentifier()) 8513 return; 8514 if (!RHSEnumType->getDecl()->getIdentifier()) 8515 return; 8516 8517 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 8518 return; 8519 8520 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 8521 << LHSStrippedType << RHSStrippedType 8522 << LHS->getSourceRange() << RHS->getSourceRange(); 8523 } 8524 8525 /// \brief Diagnose bad pointer comparisons. 8526 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 8527 ExprResult &LHS, ExprResult &RHS, 8528 bool IsError) { 8529 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 8530 : diag::ext_typecheck_comparison_of_distinct_pointers) 8531 << LHS.get()->getType() << RHS.get()->getType() 8532 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8533 } 8534 8535 /// \brief Returns false if the pointers are converted to a composite type, 8536 /// true otherwise. 8537 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 8538 ExprResult &LHS, ExprResult &RHS) { 8539 // C++ [expr.rel]p2: 8540 // [...] Pointer conversions (4.10) and qualification 8541 // conversions (4.4) are performed on pointer operands (or on 8542 // a pointer operand and a null pointer constant) to bring 8543 // them to their composite pointer type. [...] 8544 // 8545 // C++ [expr.eq]p1 uses the same notion for (in)equality 8546 // comparisons of pointers. 8547 8548 // C++ [expr.eq]p2: 8549 // In addition, pointers to members can be compared, or a pointer to 8550 // member and a null pointer constant. Pointer to member conversions 8551 // (4.11) and qualification conversions (4.4) are performed to bring 8552 // them to a common type. If one operand is a null pointer constant, 8553 // the common type is the type of the other operand. Otherwise, the 8554 // common type is a pointer to member type similar (4.4) to the type 8555 // of one of the operands, with a cv-qualification signature (4.4) 8556 // that is the union of the cv-qualification signatures of the operand 8557 // types. 8558 8559 QualType LHSType = LHS.get()->getType(); 8560 QualType RHSType = RHS.get()->getType(); 8561 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 8562 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 8563 8564 bool NonStandardCompositeType = false; 8565 bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType; 8566 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 8567 if (T.isNull()) { 8568 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 8569 return true; 8570 } 8571 8572 if (NonStandardCompositeType) 8573 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 8574 << LHSType << RHSType << T << LHS.get()->getSourceRange() 8575 << RHS.get()->getSourceRange(); 8576 8577 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 8578 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 8579 return false; 8580 } 8581 8582 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 8583 ExprResult &LHS, 8584 ExprResult &RHS, 8585 bool IsError) { 8586 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 8587 : diag::ext_typecheck_comparison_of_fptr_to_void) 8588 << LHS.get()->getType() << RHS.get()->getType() 8589 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8590 } 8591 8592 static bool isObjCObjectLiteral(ExprResult &E) { 8593 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 8594 case Stmt::ObjCArrayLiteralClass: 8595 case Stmt::ObjCDictionaryLiteralClass: 8596 case Stmt::ObjCStringLiteralClass: 8597 case Stmt::ObjCBoxedExprClass: 8598 return true; 8599 default: 8600 // Note that ObjCBoolLiteral is NOT an object literal! 8601 return false; 8602 } 8603 } 8604 8605 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 8606 const ObjCObjectPointerType *Type = 8607 LHS->getType()->getAs<ObjCObjectPointerType>(); 8608 8609 // If this is not actually an Objective-C object, bail out. 8610 if (!Type) 8611 return false; 8612 8613 // Get the LHS object's interface type. 8614 QualType InterfaceType = Type->getPointeeType(); 8615 8616 // If the RHS isn't an Objective-C object, bail out. 8617 if (!RHS->getType()->isObjCObjectPointerType()) 8618 return false; 8619 8620 // Try to find the -isEqual: method. 8621 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 8622 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 8623 InterfaceType, 8624 /*instance=*/true); 8625 if (!Method) { 8626 if (Type->isObjCIdType()) { 8627 // For 'id', just check the global pool. 8628 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 8629 /*receiverId=*/true); 8630 } else { 8631 // Check protocols. 8632 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 8633 /*instance=*/true); 8634 } 8635 } 8636 8637 if (!Method) 8638 return false; 8639 8640 QualType T = Method->parameters()[0]->getType(); 8641 if (!T->isObjCObjectPointerType()) 8642 return false; 8643 8644 QualType R = Method->getReturnType(); 8645 if (!R->isScalarType()) 8646 return false; 8647 8648 return true; 8649 } 8650 8651 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 8652 FromE = FromE->IgnoreParenImpCasts(); 8653 switch (FromE->getStmtClass()) { 8654 default: 8655 break; 8656 case Stmt::ObjCStringLiteralClass: 8657 // "string literal" 8658 return LK_String; 8659 case Stmt::ObjCArrayLiteralClass: 8660 // "array literal" 8661 return LK_Array; 8662 case Stmt::ObjCDictionaryLiteralClass: 8663 // "dictionary literal" 8664 return LK_Dictionary; 8665 case Stmt::BlockExprClass: 8666 return LK_Block; 8667 case Stmt::ObjCBoxedExprClass: { 8668 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 8669 switch (Inner->getStmtClass()) { 8670 case Stmt::IntegerLiteralClass: 8671 case Stmt::FloatingLiteralClass: 8672 case Stmt::CharacterLiteralClass: 8673 case Stmt::ObjCBoolLiteralExprClass: 8674 case Stmt::CXXBoolLiteralExprClass: 8675 // "numeric literal" 8676 return LK_Numeric; 8677 case Stmt::ImplicitCastExprClass: { 8678 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 8679 // Boolean literals can be represented by implicit casts. 8680 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 8681 return LK_Numeric; 8682 break; 8683 } 8684 default: 8685 break; 8686 } 8687 return LK_Boxed; 8688 } 8689 } 8690 return LK_None; 8691 } 8692 8693 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 8694 ExprResult &LHS, ExprResult &RHS, 8695 BinaryOperator::Opcode Opc){ 8696 Expr *Literal; 8697 Expr *Other; 8698 if (isObjCObjectLiteral(LHS)) { 8699 Literal = LHS.get(); 8700 Other = RHS.get(); 8701 } else { 8702 Literal = RHS.get(); 8703 Other = LHS.get(); 8704 } 8705 8706 // Don't warn on comparisons against nil. 8707 Other = Other->IgnoreParenCasts(); 8708 if (Other->isNullPointerConstant(S.getASTContext(), 8709 Expr::NPC_ValueDependentIsNotNull)) 8710 return; 8711 8712 // This should be kept in sync with warn_objc_literal_comparison. 8713 // LK_String should always be after the other literals, since it has its own 8714 // warning flag. 8715 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 8716 assert(LiteralKind != Sema::LK_Block); 8717 if (LiteralKind == Sema::LK_None) { 8718 llvm_unreachable("Unknown Objective-C object literal kind"); 8719 } 8720 8721 if (LiteralKind == Sema::LK_String) 8722 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 8723 << Literal->getSourceRange(); 8724 else 8725 S.Diag(Loc, diag::warn_objc_literal_comparison) 8726 << LiteralKind << Literal->getSourceRange(); 8727 8728 if (BinaryOperator::isEqualityOp(Opc) && 8729 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 8730 SourceLocation Start = LHS.get()->getLocStart(); 8731 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 8732 CharSourceRange OpRange = 8733 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 8734 8735 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 8736 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 8737 << FixItHint::CreateReplacement(OpRange, " isEqual:") 8738 << FixItHint::CreateInsertion(End, "]"); 8739 } 8740 } 8741 8742 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 8743 ExprResult &RHS, 8744 SourceLocation Loc, 8745 BinaryOperatorKind Opc) { 8746 // Check that left hand side is !something. 8747 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 8748 if (!UO || UO->getOpcode() != UO_LNot) return; 8749 8750 // Only check if the right hand side is non-bool arithmetic type. 8751 if (RHS.get()->isKnownToHaveBooleanValue()) return; 8752 8753 // Make sure that the something in !something is not bool. 8754 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 8755 if (SubExpr->isKnownToHaveBooleanValue()) return; 8756 8757 // Emit warning. 8758 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 8759 << Loc; 8760 8761 // First note suggest !(x < y) 8762 SourceLocation FirstOpen = SubExpr->getLocStart(); 8763 SourceLocation FirstClose = RHS.get()->getLocEnd(); 8764 FirstClose = S.getLocForEndOfToken(FirstClose); 8765 if (FirstClose.isInvalid()) 8766 FirstOpen = SourceLocation(); 8767 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 8768 << FixItHint::CreateInsertion(FirstOpen, "(") 8769 << FixItHint::CreateInsertion(FirstClose, ")"); 8770 8771 // Second note suggests (!x) < y 8772 SourceLocation SecondOpen = LHS.get()->getLocStart(); 8773 SourceLocation SecondClose = LHS.get()->getLocEnd(); 8774 SecondClose = S.getLocForEndOfToken(SecondClose); 8775 if (SecondClose.isInvalid()) 8776 SecondOpen = SourceLocation(); 8777 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 8778 << FixItHint::CreateInsertion(SecondOpen, "(") 8779 << FixItHint::CreateInsertion(SecondClose, ")"); 8780 } 8781 8782 // Get the decl for a simple expression: a reference to a variable, 8783 // an implicit C++ field reference, or an implicit ObjC ivar reference. 8784 static ValueDecl *getCompareDecl(Expr *E) { 8785 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 8786 return DR->getDecl(); 8787 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 8788 if (Ivar->isFreeIvar()) 8789 return Ivar->getDecl(); 8790 } 8791 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 8792 if (Mem->isImplicitAccess()) 8793 return Mem->getMemberDecl(); 8794 } 8795 return nullptr; 8796 } 8797 8798 // C99 6.5.8, C++ [expr.rel] 8799 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 8800 SourceLocation Loc, BinaryOperatorKind Opc, 8801 bool IsRelational) { 8802 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 8803 8804 // Handle vector comparisons separately. 8805 if (LHS.get()->getType()->isVectorType() || 8806 RHS.get()->getType()->isVectorType()) 8807 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 8808 8809 QualType LHSType = LHS.get()->getType(); 8810 QualType RHSType = RHS.get()->getType(); 8811 8812 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 8813 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 8814 8815 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 8816 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc); 8817 8818 if (!LHSType->hasFloatingRepresentation() && 8819 !(LHSType->isBlockPointerType() && IsRelational) && 8820 !LHS.get()->getLocStart().isMacroID() && 8821 !RHS.get()->getLocStart().isMacroID() && 8822 ActiveTemplateInstantiations.empty()) { 8823 // For non-floating point types, check for self-comparisons of the form 8824 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 8825 // often indicate logic errors in the program. 8826 // 8827 // NOTE: Don't warn about comparison expressions resulting from macro 8828 // expansion. Also don't warn about comparisons which are only self 8829 // comparisons within a template specialization. The warnings should catch 8830 // obvious cases in the definition of the template anyways. The idea is to 8831 // warn when the typed comparison operator will always evaluate to the same 8832 // result. 8833 ValueDecl *DL = getCompareDecl(LHSStripped); 8834 ValueDecl *DR = getCompareDecl(RHSStripped); 8835 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 8836 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 8837 << 0 // self- 8838 << (Opc == BO_EQ 8839 || Opc == BO_LE 8840 || Opc == BO_GE)); 8841 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 8842 !DL->getType()->isReferenceType() && 8843 !DR->getType()->isReferenceType()) { 8844 // what is it always going to eval to? 8845 char always_evals_to; 8846 switch(Opc) { 8847 case BO_EQ: // e.g. array1 == array2 8848 always_evals_to = 0; // false 8849 break; 8850 case BO_NE: // e.g. array1 != array2 8851 always_evals_to = 1; // true 8852 break; 8853 default: 8854 // best we can say is 'a constant' 8855 always_evals_to = 2; // e.g. array1 <= array2 8856 break; 8857 } 8858 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 8859 << 1 // array 8860 << always_evals_to); 8861 } 8862 8863 if (isa<CastExpr>(LHSStripped)) 8864 LHSStripped = LHSStripped->IgnoreParenCasts(); 8865 if (isa<CastExpr>(RHSStripped)) 8866 RHSStripped = RHSStripped->IgnoreParenCasts(); 8867 8868 // Warn about comparisons against a string constant (unless the other 8869 // operand is null), the user probably wants strcmp. 8870 Expr *literalString = nullptr; 8871 Expr *literalStringStripped = nullptr; 8872 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 8873 !RHSStripped->isNullPointerConstant(Context, 8874 Expr::NPC_ValueDependentIsNull)) { 8875 literalString = LHS.get(); 8876 literalStringStripped = LHSStripped; 8877 } else if ((isa<StringLiteral>(RHSStripped) || 8878 isa<ObjCEncodeExpr>(RHSStripped)) && 8879 !LHSStripped->isNullPointerConstant(Context, 8880 Expr::NPC_ValueDependentIsNull)) { 8881 literalString = RHS.get(); 8882 literalStringStripped = RHSStripped; 8883 } 8884 8885 if (literalString) { 8886 DiagRuntimeBehavior(Loc, nullptr, 8887 PDiag(diag::warn_stringcompare) 8888 << isa<ObjCEncodeExpr>(literalStringStripped) 8889 << literalString->getSourceRange()); 8890 } 8891 } 8892 8893 // C99 6.5.8p3 / C99 6.5.9p4 8894 UsualArithmeticConversions(LHS, RHS); 8895 if (LHS.isInvalid() || RHS.isInvalid()) 8896 return QualType(); 8897 8898 LHSType = LHS.get()->getType(); 8899 RHSType = RHS.get()->getType(); 8900 8901 // The result of comparisons is 'bool' in C++, 'int' in C. 8902 QualType ResultTy = Context.getLogicalOperationType(); 8903 8904 if (IsRelational) { 8905 if (LHSType->isRealType() && RHSType->isRealType()) 8906 return ResultTy; 8907 } else { 8908 // Check for comparisons of floating point operands using != and ==. 8909 if (LHSType->hasFloatingRepresentation()) 8910 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 8911 8912 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 8913 return ResultTy; 8914 } 8915 8916 const Expr::NullPointerConstantKind LHSNullKind = 8917 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 8918 const Expr::NullPointerConstantKind RHSNullKind = 8919 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 8920 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 8921 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 8922 8923 if (!IsRelational && LHSIsNull != RHSIsNull) { 8924 bool IsEquality = Opc == BO_EQ; 8925 if (RHSIsNull) 8926 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 8927 RHS.get()->getSourceRange()); 8928 else 8929 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 8930 LHS.get()->getSourceRange()); 8931 } 8932 8933 // All of the following pointer-related warnings are GCC extensions, except 8934 // when handling null pointer constants. 8935 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 8936 QualType LCanPointeeTy = 8937 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 8938 QualType RCanPointeeTy = 8939 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 8940 8941 if (getLangOpts().CPlusPlus) { 8942 if (LCanPointeeTy == RCanPointeeTy) 8943 return ResultTy; 8944 if (!IsRelational && 8945 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 8946 // Valid unless comparison between non-null pointer and function pointer 8947 // This is a gcc extension compatibility comparison. 8948 // In a SFINAE context, we treat this as a hard error to maintain 8949 // conformance with the C++ standard. 8950 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 8951 && !LHSIsNull && !RHSIsNull) { 8952 diagnoseFunctionPointerToVoidComparison( 8953 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 8954 8955 if (isSFINAEContext()) 8956 return QualType(); 8957 8958 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8959 return ResultTy; 8960 } 8961 } 8962 8963 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 8964 return QualType(); 8965 else 8966 return ResultTy; 8967 } 8968 // C99 6.5.9p2 and C99 6.5.8p2 8969 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 8970 RCanPointeeTy.getUnqualifiedType())) { 8971 // Valid unless a relational comparison of function pointers 8972 if (IsRelational && LCanPointeeTy->isFunctionType()) { 8973 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 8974 << LHSType << RHSType << LHS.get()->getSourceRange() 8975 << RHS.get()->getSourceRange(); 8976 } 8977 } else if (!IsRelational && 8978 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 8979 // Valid unless comparison between non-null pointer and function pointer 8980 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 8981 && !LHSIsNull && !RHSIsNull) 8982 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 8983 /*isError*/false); 8984 } else { 8985 // Invalid 8986 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 8987 } 8988 if (LCanPointeeTy != RCanPointeeTy) { 8989 // Treat NULL constant as a special case in OpenCL. 8990 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 8991 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 8992 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 8993 Diag(Loc, 8994 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8995 << LHSType << RHSType << 0 /* comparison */ 8996 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8997 } 8998 } 8999 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 9000 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 9001 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 9002 : CK_BitCast; 9003 if (LHSIsNull && !RHSIsNull) 9004 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 9005 else 9006 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 9007 } 9008 return ResultTy; 9009 } 9010 9011 if (getLangOpts().CPlusPlus) { 9012 // Comparison of nullptr_t with itself. 9013 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 9014 return ResultTy; 9015 9016 // Comparison of pointers with null pointer constants and equality 9017 // comparisons of member pointers to null pointer constants. 9018 if (RHSIsNull && 9019 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 9020 (!IsRelational && 9021 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 9022 RHS = ImpCastExprToType(RHS.get(), LHSType, 9023 LHSType->isMemberPointerType() 9024 ? CK_NullToMemberPointer 9025 : CK_NullToPointer); 9026 return ResultTy; 9027 } 9028 if (LHSIsNull && 9029 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 9030 (!IsRelational && 9031 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 9032 LHS = ImpCastExprToType(LHS.get(), RHSType, 9033 RHSType->isMemberPointerType() 9034 ? CK_NullToMemberPointer 9035 : CK_NullToPointer); 9036 return ResultTy; 9037 } 9038 9039 // Comparison of member pointers. 9040 if (!IsRelational && 9041 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 9042 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 9043 return QualType(); 9044 else 9045 return ResultTy; 9046 } 9047 9048 // Handle scoped enumeration types specifically, since they don't promote 9049 // to integers. 9050 if (LHS.get()->getType()->isEnumeralType() && 9051 Context.hasSameUnqualifiedType(LHS.get()->getType(), 9052 RHS.get()->getType())) 9053 return ResultTy; 9054 } 9055 9056 // Handle block pointer types. 9057 if (!IsRelational && LHSType->isBlockPointerType() && 9058 RHSType->isBlockPointerType()) { 9059 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 9060 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 9061 9062 if (!LHSIsNull && !RHSIsNull && 9063 !Context.typesAreCompatible(lpointee, rpointee)) { 9064 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9065 << LHSType << RHSType << LHS.get()->getSourceRange() 9066 << RHS.get()->getSourceRange(); 9067 } 9068 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9069 return ResultTy; 9070 } 9071 9072 // Allow block pointers to be compared with null pointer constants. 9073 if (!IsRelational 9074 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 9075 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 9076 if (!LHSIsNull && !RHSIsNull) { 9077 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 9078 ->getPointeeType()->isVoidType()) 9079 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 9080 ->getPointeeType()->isVoidType()))) 9081 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 9082 << LHSType << RHSType << LHS.get()->getSourceRange() 9083 << RHS.get()->getSourceRange(); 9084 } 9085 if (LHSIsNull && !RHSIsNull) 9086 LHS = ImpCastExprToType(LHS.get(), RHSType, 9087 RHSType->isPointerType() ? CK_BitCast 9088 : CK_AnyPointerToBlockPointerCast); 9089 else 9090 RHS = ImpCastExprToType(RHS.get(), LHSType, 9091 LHSType->isPointerType() ? CK_BitCast 9092 : CK_AnyPointerToBlockPointerCast); 9093 return ResultTy; 9094 } 9095 9096 if (LHSType->isObjCObjectPointerType() || 9097 RHSType->isObjCObjectPointerType()) { 9098 const PointerType *LPT = LHSType->getAs<PointerType>(); 9099 const PointerType *RPT = RHSType->getAs<PointerType>(); 9100 if (LPT || RPT) { 9101 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 9102 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 9103 9104 if (!LPtrToVoid && !RPtrToVoid && 9105 !Context.typesAreCompatible(LHSType, RHSType)) { 9106 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9107 /*isError*/false); 9108 } 9109 if (LHSIsNull && !RHSIsNull) { 9110 Expr *E = LHS.get(); 9111 if (getLangOpts().ObjCAutoRefCount) 9112 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 9113 LHS = ImpCastExprToType(E, RHSType, 9114 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9115 } 9116 else { 9117 Expr *E = RHS.get(); 9118 if (getLangOpts().ObjCAutoRefCount) 9119 CheckObjCARCConversion(SourceRange(), LHSType, E, 9120 CCK_ImplicitConversion, /*Diagnose=*/true, 9121 /*DiagnoseCFAudited=*/false, Opc); 9122 RHS = ImpCastExprToType(E, LHSType, 9123 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 9124 } 9125 return ResultTy; 9126 } 9127 if (LHSType->isObjCObjectPointerType() && 9128 RHSType->isObjCObjectPointerType()) { 9129 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 9130 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 9131 /*isError*/false); 9132 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 9133 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 9134 9135 if (LHSIsNull && !RHSIsNull) 9136 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 9137 else 9138 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 9139 return ResultTy; 9140 } 9141 } 9142 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 9143 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 9144 unsigned DiagID = 0; 9145 bool isError = false; 9146 if (LangOpts.DebuggerSupport) { 9147 // Under a debugger, allow the comparison of pointers to integers, 9148 // since users tend to want to compare addresses. 9149 } else if ((LHSIsNull && LHSType->isIntegerType()) || 9150 (RHSIsNull && RHSType->isIntegerType())) { 9151 if (IsRelational && !getLangOpts().CPlusPlus) 9152 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 9153 } else if (IsRelational && !getLangOpts().CPlusPlus) 9154 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 9155 else if (getLangOpts().CPlusPlus) { 9156 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 9157 isError = true; 9158 } else 9159 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 9160 9161 if (DiagID) { 9162 Diag(Loc, DiagID) 9163 << LHSType << RHSType << LHS.get()->getSourceRange() 9164 << RHS.get()->getSourceRange(); 9165 if (isError) 9166 return QualType(); 9167 } 9168 9169 if (LHSType->isIntegerType()) 9170 LHS = ImpCastExprToType(LHS.get(), RHSType, 9171 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9172 else 9173 RHS = ImpCastExprToType(RHS.get(), LHSType, 9174 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 9175 return ResultTy; 9176 } 9177 9178 // Handle block pointers. 9179 if (!IsRelational && RHSIsNull 9180 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 9181 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9182 return ResultTy; 9183 } 9184 if (!IsRelational && LHSIsNull 9185 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 9186 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9187 return ResultTy; 9188 } 9189 9190 return InvalidOperands(Loc, LHS, RHS); 9191 } 9192 9193 9194 // Return a signed type that is of identical size and number of elements. 9195 // For floating point vectors, return an integer type of identical size 9196 // and number of elements. 9197 QualType Sema::GetSignedVectorType(QualType V) { 9198 const VectorType *VTy = V->getAs<VectorType>(); 9199 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 9200 if (TypeSize == Context.getTypeSize(Context.CharTy)) 9201 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 9202 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9203 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 9204 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9205 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 9206 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9207 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 9208 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 9209 "Unhandled vector element size in vector compare"); 9210 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 9211 } 9212 9213 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9214 /// operates on extended vector types. Instead of producing an IntTy result, 9215 /// like a scalar comparison, a vector comparison produces a vector of integer 9216 /// types. 9217 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9218 SourceLocation Loc, 9219 bool IsRelational) { 9220 // Check to make sure we're operating on vectors of the same type and width, 9221 // Allowing one side to be a scalar of element type. 9222 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9223 /*AllowBothBool*/true, 9224 /*AllowBoolConversions*/getLangOpts().ZVector); 9225 if (vType.isNull()) 9226 return vType; 9227 9228 QualType LHSType = LHS.get()->getType(); 9229 9230 // If AltiVec, the comparison results in a numeric type, i.e. 9231 // bool for C++, int for C 9232 if (getLangOpts().AltiVec && 9233 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 9234 return Context.getLogicalOperationType(); 9235 9236 // For non-floating point types, check for self-comparisons of the form 9237 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9238 // often indicate logic errors in the program. 9239 if (!LHSType->hasFloatingRepresentation() && 9240 ActiveTemplateInstantiations.empty()) { 9241 if (DeclRefExpr* DRL 9242 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 9243 if (DeclRefExpr* DRR 9244 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 9245 if (DRL->getDecl() == DRR->getDecl()) 9246 DiagRuntimeBehavior(Loc, nullptr, 9247 PDiag(diag::warn_comparison_always) 9248 << 0 // self- 9249 << 2 // "a constant" 9250 ); 9251 } 9252 9253 // Check for comparisons of floating point operands using != and ==. 9254 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 9255 assert (RHS.get()->getType()->hasFloatingRepresentation()); 9256 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9257 } 9258 9259 // Return a signed type for the vector. 9260 return GetSignedVectorType(LHSType); 9261 } 9262 9263 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9264 SourceLocation Loc) { 9265 // Ensure that either both operands are of the same vector type, or 9266 // one operand is of a vector type and the other is of its element type. 9267 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 9268 /*AllowBothBool*/true, 9269 /*AllowBoolConversions*/false); 9270 if (vType.isNull()) 9271 return InvalidOperands(Loc, LHS, RHS); 9272 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 9273 vType->hasFloatingRepresentation()) 9274 return InvalidOperands(Loc, LHS, RHS); 9275 9276 return GetSignedVectorType(LHS.get()->getType()); 9277 } 9278 9279 inline QualType Sema::CheckBitwiseOperands( 9280 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9281 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9282 9283 if (LHS.get()->getType()->isVectorType() || 9284 RHS.get()->getType()->isVectorType()) { 9285 if (LHS.get()->getType()->hasIntegerRepresentation() && 9286 RHS.get()->getType()->hasIntegerRepresentation()) 9287 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9288 /*AllowBothBool*/true, 9289 /*AllowBoolConversions*/getLangOpts().ZVector); 9290 return InvalidOperands(Loc, LHS, RHS); 9291 } 9292 9293 ExprResult LHSResult = LHS, RHSResult = RHS; 9294 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 9295 IsCompAssign); 9296 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 9297 return QualType(); 9298 LHS = LHSResult.get(); 9299 RHS = RHSResult.get(); 9300 9301 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 9302 return compType; 9303 return InvalidOperands(Loc, LHS, RHS); 9304 } 9305 9306 // C99 6.5.[13,14] 9307 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9308 SourceLocation Loc, 9309 BinaryOperatorKind Opc) { 9310 // Check vector operands differently. 9311 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 9312 return CheckVectorLogicalOperands(LHS, RHS, Loc); 9313 9314 // Diagnose cases where the user write a logical and/or but probably meant a 9315 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 9316 // is a constant. 9317 if (LHS.get()->getType()->isIntegerType() && 9318 !LHS.get()->getType()->isBooleanType() && 9319 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 9320 // Don't warn in macros or template instantiations. 9321 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 9322 // If the RHS can be constant folded, and if it constant folds to something 9323 // that isn't 0 or 1 (which indicate a potential logical operation that 9324 // happened to fold to true/false) then warn. 9325 // Parens on the RHS are ignored. 9326 llvm::APSInt Result; 9327 if (RHS.get()->EvaluateAsInt(Result, Context)) 9328 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 9329 !RHS.get()->getExprLoc().isMacroID()) || 9330 (Result != 0 && Result != 1)) { 9331 Diag(Loc, diag::warn_logical_instead_of_bitwise) 9332 << RHS.get()->getSourceRange() 9333 << (Opc == BO_LAnd ? "&&" : "||"); 9334 // Suggest replacing the logical operator with the bitwise version 9335 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 9336 << (Opc == BO_LAnd ? "&" : "|") 9337 << FixItHint::CreateReplacement(SourceRange( 9338 Loc, getLocForEndOfToken(Loc)), 9339 Opc == BO_LAnd ? "&" : "|"); 9340 if (Opc == BO_LAnd) 9341 // Suggest replacing "Foo() && kNonZero" with "Foo()" 9342 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 9343 << FixItHint::CreateRemoval( 9344 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 9345 RHS.get()->getLocEnd())); 9346 } 9347 } 9348 9349 if (!Context.getLangOpts().CPlusPlus) { 9350 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 9351 // not operate on the built-in scalar and vector float types. 9352 if (Context.getLangOpts().OpenCL && 9353 Context.getLangOpts().OpenCLVersion < 120) { 9354 if (LHS.get()->getType()->isFloatingType() || 9355 RHS.get()->getType()->isFloatingType()) 9356 return InvalidOperands(Loc, LHS, RHS); 9357 } 9358 9359 LHS = UsualUnaryConversions(LHS.get()); 9360 if (LHS.isInvalid()) 9361 return QualType(); 9362 9363 RHS = UsualUnaryConversions(RHS.get()); 9364 if (RHS.isInvalid()) 9365 return QualType(); 9366 9367 if (!LHS.get()->getType()->isScalarType() || 9368 !RHS.get()->getType()->isScalarType()) 9369 return InvalidOperands(Loc, LHS, RHS); 9370 9371 return Context.IntTy; 9372 } 9373 9374 // The following is safe because we only use this method for 9375 // non-overloadable operands. 9376 9377 // C++ [expr.log.and]p1 9378 // C++ [expr.log.or]p1 9379 // The operands are both contextually converted to type bool. 9380 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 9381 if (LHSRes.isInvalid()) 9382 return InvalidOperands(Loc, LHS, RHS); 9383 LHS = LHSRes; 9384 9385 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 9386 if (RHSRes.isInvalid()) 9387 return InvalidOperands(Loc, LHS, RHS); 9388 RHS = RHSRes; 9389 9390 // C++ [expr.log.and]p2 9391 // C++ [expr.log.or]p2 9392 // The result is a bool. 9393 return Context.BoolTy; 9394 } 9395 9396 static bool IsReadonlyMessage(Expr *E, Sema &S) { 9397 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 9398 if (!ME) return false; 9399 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 9400 ObjCMessageExpr *Base = 9401 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 9402 if (!Base) return false; 9403 return Base->getMethodDecl() != nullptr; 9404 } 9405 9406 /// Is the given expression (which must be 'const') a reference to a 9407 /// variable which was originally non-const, but which has become 9408 /// 'const' due to being captured within a block? 9409 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 9410 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 9411 assert(E->isLValue() && E->getType().isConstQualified()); 9412 E = E->IgnoreParens(); 9413 9414 // Must be a reference to a declaration from an enclosing scope. 9415 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 9416 if (!DRE) return NCCK_None; 9417 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 9418 9419 // The declaration must be a variable which is not declared 'const'. 9420 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 9421 if (!var) return NCCK_None; 9422 if (var->getType().isConstQualified()) return NCCK_None; 9423 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 9424 9425 // Decide whether the first capture was for a block or a lambda. 9426 DeclContext *DC = S.CurContext, *Prev = nullptr; 9427 while (DC != var->getDeclContext()) { 9428 Prev = DC; 9429 DC = DC->getParent(); 9430 } 9431 // Unless we have an init-capture, we've gone one step too far. 9432 if (!var->isInitCapture()) 9433 DC = Prev; 9434 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 9435 } 9436 9437 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9438 Ty = Ty.getNonReferenceType(); 9439 if (IsDereference && Ty->isPointerType()) 9440 Ty = Ty->getPointeeType(); 9441 return !Ty.isConstQualified(); 9442 } 9443 9444 /// Emit the "read-only variable not assignable" error and print notes to give 9445 /// more information about why the variable is not assignable, such as pointing 9446 /// to the declaration of a const variable, showing that a method is const, or 9447 /// that the function is returning a const reference. 9448 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 9449 SourceLocation Loc) { 9450 // Update err_typecheck_assign_const and note_typecheck_assign_const 9451 // when this enum is changed. 9452 enum { 9453 ConstFunction, 9454 ConstVariable, 9455 ConstMember, 9456 ConstMethod, 9457 ConstUnknown, // Keep as last element 9458 }; 9459 9460 SourceRange ExprRange = E->getSourceRange(); 9461 9462 // Only emit one error on the first const found. All other consts will emit 9463 // a note to the error. 9464 bool DiagnosticEmitted = false; 9465 9466 // Track if the current expression is the result of a derefence, and if the 9467 // next checked expression is the result of a derefence. 9468 bool IsDereference = false; 9469 bool NextIsDereference = false; 9470 9471 // Loop to process MemberExpr chains. 9472 while (true) { 9473 IsDereference = NextIsDereference; 9474 NextIsDereference = false; 9475 9476 E = E->IgnoreParenImpCasts(); 9477 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9478 NextIsDereference = ME->isArrow(); 9479 const ValueDecl *VD = ME->getMemberDecl(); 9480 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 9481 // Mutable fields can be modified even if the class is const. 9482 if (Field->isMutable()) { 9483 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 9484 break; 9485 } 9486 9487 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 9488 if (!DiagnosticEmitted) { 9489 S.Diag(Loc, diag::err_typecheck_assign_const) 9490 << ExprRange << ConstMember << false /*static*/ << Field 9491 << Field->getType(); 9492 DiagnosticEmitted = true; 9493 } 9494 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9495 << ConstMember << false /*static*/ << Field << Field->getType() 9496 << Field->getSourceRange(); 9497 } 9498 E = ME->getBase(); 9499 continue; 9500 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 9501 if (VDecl->getType().isConstQualified()) { 9502 if (!DiagnosticEmitted) { 9503 S.Diag(Loc, diag::err_typecheck_assign_const) 9504 << ExprRange << ConstMember << true /*static*/ << VDecl 9505 << VDecl->getType(); 9506 DiagnosticEmitted = true; 9507 } 9508 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9509 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 9510 << VDecl->getSourceRange(); 9511 } 9512 // Static fields do not inherit constness from parents. 9513 break; 9514 } 9515 break; 9516 } // End MemberExpr 9517 break; 9518 } 9519 9520 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9521 // Function calls 9522 const FunctionDecl *FD = CE->getDirectCallee(); 9523 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 9524 if (!DiagnosticEmitted) { 9525 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9526 << ConstFunction << FD; 9527 DiagnosticEmitted = true; 9528 } 9529 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 9530 diag::note_typecheck_assign_const) 9531 << ConstFunction << FD << FD->getReturnType() 9532 << FD->getReturnTypeSourceRange(); 9533 } 9534 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9535 // Point to variable declaration. 9536 if (const ValueDecl *VD = DRE->getDecl()) { 9537 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 9538 if (!DiagnosticEmitted) { 9539 S.Diag(Loc, diag::err_typecheck_assign_const) 9540 << ExprRange << ConstVariable << VD << VD->getType(); 9541 DiagnosticEmitted = true; 9542 } 9543 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9544 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 9545 } 9546 } 9547 } else if (isa<CXXThisExpr>(E)) { 9548 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 9549 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 9550 if (MD->isConst()) { 9551 if (!DiagnosticEmitted) { 9552 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9553 << ConstMethod << MD; 9554 DiagnosticEmitted = true; 9555 } 9556 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 9557 << ConstMethod << MD << MD->getSourceRange(); 9558 } 9559 } 9560 } 9561 } 9562 9563 if (DiagnosticEmitted) 9564 return; 9565 9566 // Can't determine a more specific message, so display the generic error. 9567 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 9568 } 9569 9570 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 9571 /// emit an error and return true. If so, return false. 9572 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 9573 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 9574 SourceLocation OrigLoc = Loc; 9575 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 9576 &Loc); 9577 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 9578 IsLV = Expr::MLV_InvalidMessageExpression; 9579 if (IsLV == Expr::MLV_Valid) 9580 return false; 9581 9582 unsigned DiagID = 0; 9583 bool NeedType = false; 9584 switch (IsLV) { // C99 6.5.16p2 9585 case Expr::MLV_ConstQualified: 9586 // Use a specialized diagnostic when we're assigning to an object 9587 // from an enclosing function or block. 9588 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 9589 if (NCCK == NCCK_Block) 9590 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 9591 else 9592 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 9593 break; 9594 } 9595 9596 // In ARC, use some specialized diagnostics for occasions where we 9597 // infer 'const'. These are always pseudo-strong variables. 9598 if (S.getLangOpts().ObjCAutoRefCount) { 9599 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 9600 if (declRef && isa<VarDecl>(declRef->getDecl())) { 9601 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 9602 9603 // Use the normal diagnostic if it's pseudo-__strong but the 9604 // user actually wrote 'const'. 9605 if (var->isARCPseudoStrong() && 9606 (!var->getTypeSourceInfo() || 9607 !var->getTypeSourceInfo()->getType().isConstQualified())) { 9608 // There are two pseudo-strong cases: 9609 // - self 9610 ObjCMethodDecl *method = S.getCurMethodDecl(); 9611 if (method && var == method->getSelfDecl()) 9612 DiagID = method->isClassMethod() 9613 ? diag::err_typecheck_arc_assign_self_class_method 9614 : diag::err_typecheck_arc_assign_self; 9615 9616 // - fast enumeration variables 9617 else 9618 DiagID = diag::err_typecheck_arr_assign_enumeration; 9619 9620 SourceRange Assign; 9621 if (Loc != OrigLoc) 9622 Assign = SourceRange(OrigLoc, OrigLoc); 9623 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9624 // We need to preserve the AST regardless, so migration tool 9625 // can do its job. 9626 return false; 9627 } 9628 } 9629 } 9630 9631 // If none of the special cases above are triggered, then this is a 9632 // simple const assignment. 9633 if (DiagID == 0) { 9634 DiagnoseConstAssignment(S, E, Loc); 9635 return true; 9636 } 9637 9638 break; 9639 case Expr::MLV_ConstAddrSpace: 9640 DiagnoseConstAssignment(S, E, Loc); 9641 return true; 9642 case Expr::MLV_ArrayType: 9643 case Expr::MLV_ArrayTemporary: 9644 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 9645 NeedType = true; 9646 break; 9647 case Expr::MLV_NotObjectType: 9648 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 9649 NeedType = true; 9650 break; 9651 case Expr::MLV_LValueCast: 9652 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 9653 break; 9654 case Expr::MLV_Valid: 9655 llvm_unreachable("did not take early return for MLV_Valid"); 9656 case Expr::MLV_InvalidExpression: 9657 case Expr::MLV_MemberFunction: 9658 case Expr::MLV_ClassTemporary: 9659 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 9660 break; 9661 case Expr::MLV_IncompleteType: 9662 case Expr::MLV_IncompleteVoidType: 9663 return S.RequireCompleteType(Loc, E->getType(), 9664 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 9665 case Expr::MLV_DuplicateVectorComponents: 9666 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 9667 break; 9668 case Expr::MLV_NoSetterProperty: 9669 llvm_unreachable("readonly properties should be processed differently"); 9670 case Expr::MLV_InvalidMessageExpression: 9671 DiagID = diag::error_readonly_message_assignment; 9672 break; 9673 case Expr::MLV_SubObjCPropertySetting: 9674 DiagID = diag::error_no_subobject_property_setting; 9675 break; 9676 } 9677 9678 SourceRange Assign; 9679 if (Loc != OrigLoc) 9680 Assign = SourceRange(OrigLoc, OrigLoc); 9681 if (NeedType) 9682 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 9683 else 9684 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9685 return true; 9686 } 9687 9688 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 9689 SourceLocation Loc, 9690 Sema &Sema) { 9691 // C / C++ fields 9692 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 9693 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 9694 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 9695 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 9696 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 9697 } 9698 9699 // Objective-C instance variables 9700 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 9701 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 9702 if (OL && OR && OL->getDecl() == OR->getDecl()) { 9703 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 9704 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 9705 if (RL && RR && RL->getDecl() == RR->getDecl()) 9706 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 9707 } 9708 } 9709 9710 // C99 6.5.16.1 9711 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 9712 SourceLocation Loc, 9713 QualType CompoundType) { 9714 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 9715 9716 // Verify that LHS is a modifiable lvalue, and emit error if not. 9717 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 9718 return QualType(); 9719 9720 QualType LHSType = LHSExpr->getType(); 9721 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 9722 CompoundType; 9723 AssignConvertType ConvTy; 9724 if (CompoundType.isNull()) { 9725 Expr *RHSCheck = RHS.get(); 9726 9727 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 9728 9729 QualType LHSTy(LHSType); 9730 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 9731 if (RHS.isInvalid()) 9732 return QualType(); 9733 // Special case of NSObject attributes on c-style pointer types. 9734 if (ConvTy == IncompatiblePointer && 9735 ((Context.isObjCNSObjectType(LHSType) && 9736 RHSType->isObjCObjectPointerType()) || 9737 (Context.isObjCNSObjectType(RHSType) && 9738 LHSType->isObjCObjectPointerType()))) 9739 ConvTy = Compatible; 9740 9741 if (ConvTy == Compatible && 9742 LHSType->isObjCObjectType()) 9743 Diag(Loc, diag::err_objc_object_assignment) 9744 << LHSType; 9745 9746 // If the RHS is a unary plus or minus, check to see if they = and + are 9747 // right next to each other. If so, the user may have typo'd "x =+ 4" 9748 // instead of "x += 4". 9749 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 9750 RHSCheck = ICE->getSubExpr(); 9751 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 9752 if ((UO->getOpcode() == UO_Plus || 9753 UO->getOpcode() == UO_Minus) && 9754 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 9755 // Only if the two operators are exactly adjacent. 9756 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 9757 // And there is a space or other character before the subexpr of the 9758 // unary +/-. We don't want to warn on "x=-1". 9759 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 9760 UO->getSubExpr()->getLocStart().isFileID()) { 9761 Diag(Loc, diag::warn_not_compound_assign) 9762 << (UO->getOpcode() == UO_Plus ? "+" : "-") 9763 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 9764 } 9765 } 9766 9767 if (ConvTy == Compatible) { 9768 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 9769 // Warn about retain cycles where a block captures the LHS, but 9770 // not if the LHS is a simple variable into which the block is 9771 // being stored...unless that variable can be captured by reference! 9772 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 9773 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 9774 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 9775 checkRetainCycles(LHSExpr, RHS.get()); 9776 9777 // It is safe to assign a weak reference into a strong variable. 9778 // Although this code can still have problems: 9779 // id x = self.weakProp; 9780 // id y = self.weakProp; 9781 // we do not warn to warn spuriously when 'x' and 'y' are on separate 9782 // paths through the function. This should be revisited if 9783 // -Wrepeated-use-of-weak is made flow-sensitive. 9784 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 9785 RHS.get()->getLocStart())) 9786 getCurFunction()->markSafeWeakUse(RHS.get()); 9787 9788 } else if (getLangOpts().ObjCAutoRefCount) { 9789 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 9790 } 9791 } 9792 } else { 9793 // Compound assignment "x += y" 9794 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 9795 } 9796 9797 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 9798 RHS.get(), AA_Assigning)) 9799 return QualType(); 9800 9801 CheckForNullPointerDereference(*this, LHSExpr); 9802 9803 // C99 6.5.16p3: The type of an assignment expression is the type of the 9804 // left operand unless the left operand has qualified type, in which case 9805 // it is the unqualified version of the type of the left operand. 9806 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 9807 // is converted to the type of the assignment expression (above). 9808 // C++ 5.17p1: the type of the assignment expression is that of its left 9809 // operand. 9810 return (getLangOpts().CPlusPlus 9811 ? LHSType : LHSType.getUnqualifiedType()); 9812 } 9813 9814 // C99 6.5.17 9815 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 9816 SourceLocation Loc) { 9817 LHS = S.CheckPlaceholderExpr(LHS.get()); 9818 RHS = S.CheckPlaceholderExpr(RHS.get()); 9819 if (LHS.isInvalid() || RHS.isInvalid()) 9820 return QualType(); 9821 9822 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 9823 // operands, but not unary promotions. 9824 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 9825 9826 // So we treat the LHS as a ignored value, and in C++ we allow the 9827 // containing site to determine what should be done with the RHS. 9828 LHS = S.IgnoredValueConversions(LHS.get()); 9829 if (LHS.isInvalid()) 9830 return QualType(); 9831 9832 S.DiagnoseUnusedExprResult(LHS.get()); 9833 9834 if (!S.getLangOpts().CPlusPlus) { 9835 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 9836 if (RHS.isInvalid()) 9837 return QualType(); 9838 if (!RHS.get()->getType()->isVoidType()) 9839 S.RequireCompleteType(Loc, RHS.get()->getType(), 9840 diag::err_incomplete_type); 9841 } 9842 9843 return RHS.get()->getType(); 9844 } 9845 9846 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 9847 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 9848 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 9849 ExprValueKind &VK, 9850 ExprObjectKind &OK, 9851 SourceLocation OpLoc, 9852 bool IsInc, bool IsPrefix) { 9853 if (Op->isTypeDependent()) 9854 return S.Context.DependentTy; 9855 9856 QualType ResType = Op->getType(); 9857 // Atomic types can be used for increment / decrement where the non-atomic 9858 // versions can, so ignore the _Atomic() specifier for the purpose of 9859 // checking. 9860 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9861 ResType = ResAtomicType->getValueType(); 9862 9863 assert(!ResType.isNull() && "no type for increment/decrement expression"); 9864 9865 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 9866 // Decrement of bool is not allowed. 9867 if (!IsInc) { 9868 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 9869 return QualType(); 9870 } 9871 // Increment of bool sets it to true, but is deprecated. 9872 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 9873 : diag::warn_increment_bool) 9874 << Op->getSourceRange(); 9875 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 9876 // Error on enum increments and decrements in C++ mode 9877 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 9878 return QualType(); 9879 } else if (ResType->isRealType()) { 9880 // OK! 9881 } else if (ResType->isPointerType()) { 9882 // C99 6.5.2.4p2, 6.5.6p2 9883 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 9884 return QualType(); 9885 } else if (ResType->isObjCObjectPointerType()) { 9886 // On modern runtimes, ObjC pointer arithmetic is forbidden. 9887 // Otherwise, we just need a complete type. 9888 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 9889 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 9890 return QualType(); 9891 } else if (ResType->isAnyComplexType()) { 9892 // C99 does not support ++/-- on complex types, we allow as an extension. 9893 S.Diag(OpLoc, diag::ext_integer_increment_complex) 9894 << ResType << Op->getSourceRange(); 9895 } else if (ResType->isPlaceholderType()) { 9896 ExprResult PR = S.CheckPlaceholderExpr(Op); 9897 if (PR.isInvalid()) return QualType(); 9898 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 9899 IsInc, IsPrefix); 9900 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 9901 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 9902 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 9903 (ResType->getAs<VectorType>()->getVectorKind() != 9904 VectorType::AltiVecBool)) { 9905 // The z vector extensions allow ++ and -- for non-bool vectors. 9906 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 9907 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 9908 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 9909 } else { 9910 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 9911 << ResType << int(IsInc) << Op->getSourceRange(); 9912 return QualType(); 9913 } 9914 // At this point, we know we have a real, complex or pointer type. 9915 // Now make sure the operand is a modifiable lvalue. 9916 if (CheckForModifiableLvalue(Op, OpLoc, S)) 9917 return QualType(); 9918 // In C++, a prefix increment is the same type as the operand. Otherwise 9919 // (in C or with postfix), the increment is the unqualified type of the 9920 // operand. 9921 if (IsPrefix && S.getLangOpts().CPlusPlus) { 9922 VK = VK_LValue; 9923 OK = Op->getObjectKind(); 9924 return ResType; 9925 } else { 9926 VK = VK_RValue; 9927 return ResType.getUnqualifiedType(); 9928 } 9929 } 9930 9931 9932 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 9933 /// This routine allows us to typecheck complex/recursive expressions 9934 /// where the declaration is needed for type checking. We only need to 9935 /// handle cases when the expression references a function designator 9936 /// or is an lvalue. Here are some examples: 9937 /// - &(x) => x 9938 /// - &*****f => f for f a function designator. 9939 /// - &s.xx => s 9940 /// - &s.zz[1].yy -> s, if zz is an array 9941 /// - *(x + 1) -> x, if x is an array 9942 /// - &"123"[2] -> 0 9943 /// - & __real__ x -> x 9944 static ValueDecl *getPrimaryDecl(Expr *E) { 9945 switch (E->getStmtClass()) { 9946 case Stmt::DeclRefExprClass: 9947 return cast<DeclRefExpr>(E)->getDecl(); 9948 case Stmt::MemberExprClass: 9949 // If this is an arrow operator, the address is an offset from 9950 // the base's value, so the object the base refers to is 9951 // irrelevant. 9952 if (cast<MemberExpr>(E)->isArrow()) 9953 return nullptr; 9954 // Otherwise, the expression refers to a part of the base 9955 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 9956 case Stmt::ArraySubscriptExprClass: { 9957 // FIXME: This code shouldn't be necessary! We should catch the implicit 9958 // promotion of register arrays earlier. 9959 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 9960 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 9961 if (ICE->getSubExpr()->getType()->isArrayType()) 9962 return getPrimaryDecl(ICE->getSubExpr()); 9963 } 9964 return nullptr; 9965 } 9966 case Stmt::UnaryOperatorClass: { 9967 UnaryOperator *UO = cast<UnaryOperator>(E); 9968 9969 switch(UO->getOpcode()) { 9970 case UO_Real: 9971 case UO_Imag: 9972 case UO_Extension: 9973 return getPrimaryDecl(UO->getSubExpr()); 9974 default: 9975 return nullptr; 9976 } 9977 } 9978 case Stmt::ParenExprClass: 9979 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 9980 case Stmt::ImplicitCastExprClass: 9981 // If the result of an implicit cast is an l-value, we care about 9982 // the sub-expression; otherwise, the result here doesn't matter. 9983 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 9984 default: 9985 return nullptr; 9986 } 9987 } 9988 9989 namespace { 9990 enum { 9991 AO_Bit_Field = 0, 9992 AO_Vector_Element = 1, 9993 AO_Property_Expansion = 2, 9994 AO_Register_Variable = 3, 9995 AO_No_Error = 4 9996 }; 9997 } 9998 /// \brief Diagnose invalid operand for address of operations. 9999 /// 10000 /// \param Type The type of operand which cannot have its address taken. 10001 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 10002 Expr *E, unsigned Type) { 10003 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 10004 } 10005 10006 /// CheckAddressOfOperand - The operand of & must be either a function 10007 /// designator or an lvalue designating an object. If it is an lvalue, the 10008 /// object cannot be declared with storage class register or be a bit field. 10009 /// Note: The usual conversions are *not* applied to the operand of the & 10010 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 10011 /// In C++, the operand might be an overloaded function name, in which case 10012 /// we allow the '&' but retain the overloaded-function type. 10013 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 10014 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 10015 if (PTy->getKind() == BuiltinType::Overload) { 10016 Expr *E = OrigOp.get()->IgnoreParens(); 10017 if (!isa<OverloadExpr>(E)) { 10018 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 10019 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 10020 << OrigOp.get()->getSourceRange(); 10021 return QualType(); 10022 } 10023 10024 OverloadExpr *Ovl = cast<OverloadExpr>(E); 10025 if (isa<UnresolvedMemberExpr>(Ovl)) 10026 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 10027 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10028 << OrigOp.get()->getSourceRange(); 10029 return QualType(); 10030 } 10031 10032 return Context.OverloadTy; 10033 } 10034 10035 if (PTy->getKind() == BuiltinType::UnknownAny) 10036 return Context.UnknownAnyTy; 10037 10038 if (PTy->getKind() == BuiltinType::BoundMember) { 10039 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10040 << OrigOp.get()->getSourceRange(); 10041 return QualType(); 10042 } 10043 10044 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 10045 if (OrigOp.isInvalid()) return QualType(); 10046 } 10047 10048 if (OrigOp.get()->isTypeDependent()) 10049 return Context.DependentTy; 10050 10051 assert(!OrigOp.get()->getType()->isPlaceholderType()); 10052 10053 // Make sure to ignore parentheses in subsequent checks 10054 Expr *op = OrigOp.get()->IgnoreParens(); 10055 10056 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 10057 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 10058 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 10059 return QualType(); 10060 } 10061 10062 if (getLangOpts().C99) { 10063 // Implement C99-only parts of addressof rules. 10064 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 10065 if (uOp->getOpcode() == UO_Deref) 10066 // Per C99 6.5.3.2, the address of a deref always returns a valid result 10067 // (assuming the deref expression is valid). 10068 return uOp->getSubExpr()->getType(); 10069 } 10070 // Technically, there should be a check for array subscript 10071 // expressions here, but the result of one is always an lvalue anyway. 10072 } 10073 ValueDecl *dcl = getPrimaryDecl(op); 10074 10075 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 10076 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 10077 op->getLocStart())) 10078 return QualType(); 10079 10080 Expr::LValueClassification lval = op->ClassifyLValue(Context); 10081 unsigned AddressOfError = AO_No_Error; 10082 10083 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 10084 bool sfinae = (bool)isSFINAEContext(); 10085 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 10086 : diag::ext_typecheck_addrof_temporary) 10087 << op->getType() << op->getSourceRange(); 10088 if (sfinae) 10089 return QualType(); 10090 // Materialize the temporary as an lvalue so that we can take its address. 10091 OrigOp = op = new (Context) 10092 MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 10093 } else if (isa<ObjCSelectorExpr>(op)) { 10094 return Context.getPointerType(op->getType()); 10095 } else if (lval == Expr::LV_MemberFunction) { 10096 // If it's an instance method, make a member pointer. 10097 // The expression must have exactly the form &A::foo. 10098 10099 // If the underlying expression isn't a decl ref, give up. 10100 if (!isa<DeclRefExpr>(op)) { 10101 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 10102 << OrigOp.get()->getSourceRange(); 10103 return QualType(); 10104 } 10105 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 10106 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 10107 10108 // The id-expression was parenthesized. 10109 if (OrigOp.get() != DRE) { 10110 Diag(OpLoc, diag::err_parens_pointer_member_function) 10111 << OrigOp.get()->getSourceRange(); 10112 10113 // The method was named without a qualifier. 10114 } else if (!DRE->getQualifier()) { 10115 if (MD->getParent()->getName().empty()) 10116 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10117 << op->getSourceRange(); 10118 else { 10119 SmallString<32> Str; 10120 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 10121 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 10122 << op->getSourceRange() 10123 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 10124 } 10125 } 10126 10127 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 10128 if (isa<CXXDestructorDecl>(MD)) 10129 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 10130 10131 QualType MPTy = Context.getMemberPointerType( 10132 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 10133 // Under the MS ABI, lock down the inheritance model now. 10134 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10135 (void)isCompleteType(OpLoc, MPTy); 10136 return MPTy; 10137 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 10138 // C99 6.5.3.2p1 10139 // The operand must be either an l-value or a function designator 10140 if (!op->getType()->isFunctionType()) { 10141 // Use a special diagnostic for loads from property references. 10142 if (isa<PseudoObjectExpr>(op)) { 10143 AddressOfError = AO_Property_Expansion; 10144 } else { 10145 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 10146 << op->getType() << op->getSourceRange(); 10147 return QualType(); 10148 } 10149 } 10150 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 10151 // The operand cannot be a bit-field 10152 AddressOfError = AO_Bit_Field; 10153 } else if (op->getObjectKind() == OK_VectorComponent) { 10154 // The operand cannot be an element of a vector 10155 AddressOfError = AO_Vector_Element; 10156 } else if (dcl) { // C99 6.5.3.2p1 10157 // We have an lvalue with a decl. Make sure the decl is not declared 10158 // with the register storage-class specifier. 10159 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 10160 // in C++ it is not error to take address of a register 10161 // variable (c++03 7.1.1P3) 10162 if (vd->getStorageClass() == SC_Register && 10163 !getLangOpts().CPlusPlus) { 10164 AddressOfError = AO_Register_Variable; 10165 } 10166 } else if (isa<MSPropertyDecl>(dcl)) { 10167 AddressOfError = AO_Property_Expansion; 10168 } else if (isa<FunctionTemplateDecl>(dcl)) { 10169 return Context.OverloadTy; 10170 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 10171 // Okay: we can take the address of a field. 10172 // Could be a pointer to member, though, if there is an explicit 10173 // scope qualifier for the class. 10174 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 10175 DeclContext *Ctx = dcl->getDeclContext(); 10176 if (Ctx && Ctx->isRecord()) { 10177 if (dcl->getType()->isReferenceType()) { 10178 Diag(OpLoc, 10179 diag::err_cannot_form_pointer_to_member_of_reference_type) 10180 << dcl->getDeclName() << dcl->getType(); 10181 return QualType(); 10182 } 10183 10184 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 10185 Ctx = Ctx->getParent(); 10186 10187 QualType MPTy = Context.getMemberPointerType( 10188 op->getType(), 10189 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 10190 // Under the MS ABI, lock down the inheritance model now. 10191 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10192 (void)isCompleteType(OpLoc, MPTy); 10193 return MPTy; 10194 } 10195 } 10196 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 10197 llvm_unreachable("Unknown/unexpected decl type"); 10198 } 10199 10200 if (AddressOfError != AO_No_Error) { 10201 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 10202 return QualType(); 10203 } 10204 10205 if (lval == Expr::LV_IncompleteVoidType) { 10206 // Taking the address of a void variable is technically illegal, but we 10207 // allow it in cases which are otherwise valid. 10208 // Example: "extern void x; void* y = &x;". 10209 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 10210 } 10211 10212 // If the operand has type "type", the result has type "pointer to type". 10213 if (op->getType()->isObjCObjectType()) 10214 return Context.getObjCObjectPointerType(op->getType()); 10215 return Context.getPointerType(op->getType()); 10216 } 10217 10218 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 10219 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 10220 if (!DRE) 10221 return; 10222 const Decl *D = DRE->getDecl(); 10223 if (!D) 10224 return; 10225 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 10226 if (!Param) 10227 return; 10228 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 10229 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 10230 return; 10231 if (FunctionScopeInfo *FD = S.getCurFunction()) 10232 if (!FD->ModifiedNonNullParams.count(Param)) 10233 FD->ModifiedNonNullParams.insert(Param); 10234 } 10235 10236 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 10237 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 10238 SourceLocation OpLoc) { 10239 if (Op->isTypeDependent()) 10240 return S.Context.DependentTy; 10241 10242 ExprResult ConvResult = S.UsualUnaryConversions(Op); 10243 if (ConvResult.isInvalid()) 10244 return QualType(); 10245 Op = ConvResult.get(); 10246 QualType OpTy = Op->getType(); 10247 QualType Result; 10248 10249 if (isa<CXXReinterpretCastExpr>(Op)) { 10250 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 10251 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 10252 Op->getSourceRange()); 10253 } 10254 10255 if (const PointerType *PT = OpTy->getAs<PointerType>()) 10256 Result = PT->getPointeeType(); 10257 else if (const ObjCObjectPointerType *OPT = 10258 OpTy->getAs<ObjCObjectPointerType>()) 10259 Result = OPT->getPointeeType(); 10260 else { 10261 ExprResult PR = S.CheckPlaceholderExpr(Op); 10262 if (PR.isInvalid()) return QualType(); 10263 if (PR.get() != Op) 10264 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 10265 } 10266 10267 if (Result.isNull()) { 10268 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 10269 << OpTy << Op->getSourceRange(); 10270 return QualType(); 10271 } 10272 10273 // Note that per both C89 and C99, indirection is always legal, even if Result 10274 // is an incomplete type or void. It would be possible to warn about 10275 // dereferencing a void pointer, but it's completely well-defined, and such a 10276 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 10277 // for pointers to 'void' but is fine for any other pointer type: 10278 // 10279 // C++ [expr.unary.op]p1: 10280 // [...] the expression to which [the unary * operator] is applied shall 10281 // be a pointer to an object type, or a pointer to a function type 10282 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 10283 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 10284 << OpTy << Op->getSourceRange(); 10285 10286 // Dereferences are usually l-values... 10287 VK = VK_LValue; 10288 10289 // ...except that certain expressions are never l-values in C. 10290 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 10291 VK = VK_RValue; 10292 10293 return Result; 10294 } 10295 10296 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 10297 BinaryOperatorKind Opc; 10298 switch (Kind) { 10299 default: llvm_unreachable("Unknown binop!"); 10300 case tok::periodstar: Opc = BO_PtrMemD; break; 10301 case tok::arrowstar: Opc = BO_PtrMemI; break; 10302 case tok::star: Opc = BO_Mul; break; 10303 case tok::slash: Opc = BO_Div; break; 10304 case tok::percent: Opc = BO_Rem; break; 10305 case tok::plus: Opc = BO_Add; break; 10306 case tok::minus: Opc = BO_Sub; break; 10307 case tok::lessless: Opc = BO_Shl; break; 10308 case tok::greatergreater: Opc = BO_Shr; break; 10309 case tok::lessequal: Opc = BO_LE; break; 10310 case tok::less: Opc = BO_LT; break; 10311 case tok::greaterequal: Opc = BO_GE; break; 10312 case tok::greater: Opc = BO_GT; break; 10313 case tok::exclaimequal: Opc = BO_NE; break; 10314 case tok::equalequal: Opc = BO_EQ; break; 10315 case tok::amp: Opc = BO_And; break; 10316 case tok::caret: Opc = BO_Xor; break; 10317 case tok::pipe: Opc = BO_Or; break; 10318 case tok::ampamp: Opc = BO_LAnd; break; 10319 case tok::pipepipe: Opc = BO_LOr; break; 10320 case tok::equal: Opc = BO_Assign; break; 10321 case tok::starequal: Opc = BO_MulAssign; break; 10322 case tok::slashequal: Opc = BO_DivAssign; break; 10323 case tok::percentequal: Opc = BO_RemAssign; break; 10324 case tok::plusequal: Opc = BO_AddAssign; break; 10325 case tok::minusequal: Opc = BO_SubAssign; break; 10326 case tok::lesslessequal: Opc = BO_ShlAssign; break; 10327 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 10328 case tok::ampequal: Opc = BO_AndAssign; break; 10329 case tok::caretequal: Opc = BO_XorAssign; break; 10330 case tok::pipeequal: Opc = BO_OrAssign; break; 10331 case tok::comma: Opc = BO_Comma; break; 10332 } 10333 return Opc; 10334 } 10335 10336 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 10337 tok::TokenKind Kind) { 10338 UnaryOperatorKind Opc; 10339 switch (Kind) { 10340 default: llvm_unreachable("Unknown unary op!"); 10341 case tok::plusplus: Opc = UO_PreInc; break; 10342 case tok::minusminus: Opc = UO_PreDec; break; 10343 case tok::amp: Opc = UO_AddrOf; break; 10344 case tok::star: Opc = UO_Deref; break; 10345 case tok::plus: Opc = UO_Plus; break; 10346 case tok::minus: Opc = UO_Minus; break; 10347 case tok::tilde: Opc = UO_Not; break; 10348 case tok::exclaim: Opc = UO_LNot; break; 10349 case tok::kw___real: Opc = UO_Real; break; 10350 case tok::kw___imag: Opc = UO_Imag; break; 10351 case tok::kw___extension__: Opc = UO_Extension; break; 10352 } 10353 return Opc; 10354 } 10355 10356 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 10357 /// This warning is only emitted for builtin assignment operations. It is also 10358 /// suppressed in the event of macro expansions. 10359 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 10360 SourceLocation OpLoc) { 10361 if (!S.ActiveTemplateInstantiations.empty()) 10362 return; 10363 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 10364 return; 10365 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10366 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10367 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10368 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10369 if (!LHSDeclRef || !RHSDeclRef || 10370 LHSDeclRef->getLocation().isMacroID() || 10371 RHSDeclRef->getLocation().isMacroID()) 10372 return; 10373 const ValueDecl *LHSDecl = 10374 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 10375 const ValueDecl *RHSDecl = 10376 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 10377 if (LHSDecl != RHSDecl) 10378 return; 10379 if (LHSDecl->getType().isVolatileQualified()) 10380 return; 10381 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 10382 if (RefTy->getPointeeType().isVolatileQualified()) 10383 return; 10384 10385 S.Diag(OpLoc, diag::warn_self_assignment) 10386 << LHSDeclRef->getType() 10387 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10388 } 10389 10390 /// Check if a bitwise-& is performed on an Objective-C pointer. This 10391 /// is usually indicative of introspection within the Objective-C pointer. 10392 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 10393 SourceLocation OpLoc) { 10394 if (!S.getLangOpts().ObjC1) 10395 return; 10396 10397 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 10398 const Expr *LHS = L.get(); 10399 const Expr *RHS = R.get(); 10400 10401 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10402 ObjCPointerExpr = LHS; 10403 OtherExpr = RHS; 10404 } 10405 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10406 ObjCPointerExpr = RHS; 10407 OtherExpr = LHS; 10408 } 10409 10410 // This warning is deliberately made very specific to reduce false 10411 // positives with logic that uses '&' for hashing. This logic mainly 10412 // looks for code trying to introspect into tagged pointers, which 10413 // code should generally never do. 10414 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 10415 unsigned Diag = diag::warn_objc_pointer_masking; 10416 // Determine if we are introspecting the result of performSelectorXXX. 10417 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 10418 // Special case messages to -performSelector and friends, which 10419 // can return non-pointer values boxed in a pointer value. 10420 // Some clients may wish to silence warnings in this subcase. 10421 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 10422 Selector S = ME->getSelector(); 10423 StringRef SelArg0 = S.getNameForSlot(0); 10424 if (SelArg0.startswith("performSelector")) 10425 Diag = diag::warn_objc_pointer_masking_performSelector; 10426 } 10427 10428 S.Diag(OpLoc, Diag) 10429 << ObjCPointerExpr->getSourceRange(); 10430 } 10431 } 10432 10433 static NamedDecl *getDeclFromExpr(Expr *E) { 10434 if (!E) 10435 return nullptr; 10436 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 10437 return DRE->getDecl(); 10438 if (auto *ME = dyn_cast<MemberExpr>(E)) 10439 return ME->getMemberDecl(); 10440 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 10441 return IRE->getDecl(); 10442 return nullptr; 10443 } 10444 10445 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 10446 /// operator @p Opc at location @c TokLoc. This routine only supports 10447 /// built-in operations; ActOnBinOp handles overloaded operators. 10448 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 10449 BinaryOperatorKind Opc, 10450 Expr *LHSExpr, Expr *RHSExpr) { 10451 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 10452 // The syntax only allows initializer lists on the RHS of assignment, 10453 // so we don't need to worry about accepting invalid code for 10454 // non-assignment operators. 10455 // C++11 5.17p9: 10456 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 10457 // of x = {} is x = T(). 10458 InitializationKind Kind = 10459 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 10460 InitializedEntity Entity = 10461 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 10462 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 10463 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 10464 if (Init.isInvalid()) 10465 return Init; 10466 RHSExpr = Init.get(); 10467 } 10468 10469 ExprResult LHS = LHSExpr, RHS = RHSExpr; 10470 QualType ResultTy; // Result type of the binary operator. 10471 // The following two variables are used for compound assignment operators 10472 QualType CompLHSTy; // Type of LHS after promotions for computation 10473 QualType CompResultTy; // Type of computation result 10474 ExprValueKind VK = VK_RValue; 10475 ExprObjectKind OK = OK_Ordinary; 10476 10477 if (!getLangOpts().CPlusPlus) { 10478 // C cannot handle TypoExpr nodes on either side of a binop because it 10479 // doesn't handle dependent types properly, so make sure any TypoExprs have 10480 // been dealt with before checking the operands. 10481 LHS = CorrectDelayedTyposInExpr(LHSExpr); 10482 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 10483 if (Opc != BO_Assign) 10484 return ExprResult(E); 10485 // Avoid correcting the RHS to the same Expr as the LHS. 10486 Decl *D = getDeclFromExpr(E); 10487 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 10488 }); 10489 if (!LHS.isUsable() || !RHS.isUsable()) 10490 return ExprError(); 10491 } 10492 10493 if (getLangOpts().OpenCL) { 10494 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 10495 // the ATOMIC_VAR_INIT macro. 10496 if (LHSExpr->getType()->isAtomicType() || 10497 RHSExpr->getType()->isAtomicType()) { 10498 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 10499 if (BO_Assign == Opc) 10500 Diag(OpLoc, diag::err_atomic_init_constant) << SR; 10501 else 10502 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 10503 return ExprError(); 10504 } 10505 } 10506 10507 switch (Opc) { 10508 case BO_Assign: 10509 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 10510 if (getLangOpts().CPlusPlus && 10511 LHS.get()->getObjectKind() != OK_ObjCProperty) { 10512 VK = LHS.get()->getValueKind(); 10513 OK = LHS.get()->getObjectKind(); 10514 } 10515 if (!ResultTy.isNull()) { 10516 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10517 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 10518 } 10519 RecordModifiableNonNullParam(*this, LHS.get()); 10520 break; 10521 case BO_PtrMemD: 10522 case BO_PtrMemI: 10523 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 10524 Opc == BO_PtrMemI); 10525 break; 10526 case BO_Mul: 10527 case BO_Div: 10528 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 10529 Opc == BO_Div); 10530 break; 10531 case BO_Rem: 10532 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 10533 break; 10534 case BO_Add: 10535 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 10536 break; 10537 case BO_Sub: 10538 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 10539 break; 10540 case BO_Shl: 10541 case BO_Shr: 10542 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 10543 break; 10544 case BO_LE: 10545 case BO_LT: 10546 case BO_GE: 10547 case BO_GT: 10548 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 10549 break; 10550 case BO_EQ: 10551 case BO_NE: 10552 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 10553 break; 10554 case BO_And: 10555 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 10556 case BO_Xor: 10557 case BO_Or: 10558 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 10559 break; 10560 case BO_LAnd: 10561 case BO_LOr: 10562 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 10563 break; 10564 case BO_MulAssign: 10565 case BO_DivAssign: 10566 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 10567 Opc == BO_DivAssign); 10568 CompLHSTy = CompResultTy; 10569 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10570 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10571 break; 10572 case BO_RemAssign: 10573 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 10574 CompLHSTy = CompResultTy; 10575 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10576 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10577 break; 10578 case BO_AddAssign: 10579 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 10580 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10581 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10582 break; 10583 case BO_SubAssign: 10584 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 10585 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10586 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10587 break; 10588 case BO_ShlAssign: 10589 case BO_ShrAssign: 10590 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 10591 CompLHSTy = CompResultTy; 10592 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10593 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10594 break; 10595 case BO_AndAssign: 10596 case BO_OrAssign: // fallthrough 10597 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10598 case BO_XorAssign: 10599 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 10600 CompLHSTy = CompResultTy; 10601 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10602 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10603 break; 10604 case BO_Comma: 10605 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 10606 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 10607 VK = RHS.get()->getValueKind(); 10608 OK = RHS.get()->getObjectKind(); 10609 } 10610 break; 10611 } 10612 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 10613 return ExprError(); 10614 10615 // Check for array bounds violations for both sides of the BinaryOperator 10616 CheckArrayAccess(LHS.get()); 10617 CheckArrayAccess(RHS.get()); 10618 10619 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 10620 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 10621 &Context.Idents.get("object_setClass"), 10622 SourceLocation(), LookupOrdinaryName); 10623 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 10624 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 10625 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 10626 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 10627 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 10628 FixItHint::CreateInsertion(RHSLocEnd, ")"); 10629 } 10630 else 10631 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 10632 } 10633 else if (const ObjCIvarRefExpr *OIRE = 10634 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 10635 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 10636 10637 if (CompResultTy.isNull()) 10638 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 10639 OK, OpLoc, FPFeatures.fp_contract); 10640 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 10641 OK_ObjCProperty) { 10642 VK = VK_LValue; 10643 OK = LHS.get()->getObjectKind(); 10644 } 10645 return new (Context) CompoundAssignOperator( 10646 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 10647 OpLoc, FPFeatures.fp_contract); 10648 } 10649 10650 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 10651 /// operators are mixed in a way that suggests that the programmer forgot that 10652 /// comparison operators have higher precedence. The most typical example of 10653 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 10654 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 10655 SourceLocation OpLoc, Expr *LHSExpr, 10656 Expr *RHSExpr) { 10657 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 10658 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 10659 10660 // Check that one of the sides is a comparison operator and the other isn't. 10661 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 10662 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 10663 if (isLeftComp == isRightComp) 10664 return; 10665 10666 // Bitwise operations are sometimes used as eager logical ops. 10667 // Don't diagnose this. 10668 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 10669 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 10670 if (isLeftBitwise || isRightBitwise) 10671 return; 10672 10673 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 10674 OpLoc) 10675 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 10676 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 10677 SourceRange ParensRange = isLeftComp ? 10678 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 10679 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 10680 10681 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 10682 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 10683 SuggestParentheses(Self, OpLoc, 10684 Self.PDiag(diag::note_precedence_silence) << OpStr, 10685 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 10686 SuggestParentheses(Self, OpLoc, 10687 Self.PDiag(diag::note_precedence_bitwise_first) 10688 << BinaryOperator::getOpcodeStr(Opc), 10689 ParensRange); 10690 } 10691 10692 /// \brief It accepts a '&&' expr that is inside a '||' one. 10693 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 10694 /// in parentheses. 10695 static void 10696 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 10697 BinaryOperator *Bop) { 10698 assert(Bop->getOpcode() == BO_LAnd); 10699 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 10700 << Bop->getSourceRange() << OpLoc; 10701 SuggestParentheses(Self, Bop->getOperatorLoc(), 10702 Self.PDiag(diag::note_precedence_silence) 10703 << Bop->getOpcodeStr(), 10704 Bop->getSourceRange()); 10705 } 10706 10707 /// \brief Returns true if the given expression can be evaluated as a constant 10708 /// 'true'. 10709 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 10710 bool Res; 10711 return !E->isValueDependent() && 10712 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 10713 } 10714 10715 /// \brief Returns true if the given expression can be evaluated as a constant 10716 /// 'false'. 10717 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 10718 bool Res; 10719 return !E->isValueDependent() && 10720 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 10721 } 10722 10723 /// \brief Look for '&&' in the left hand of a '||' expr. 10724 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 10725 Expr *LHSExpr, Expr *RHSExpr) { 10726 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 10727 if (Bop->getOpcode() == BO_LAnd) { 10728 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 10729 if (EvaluatesAsFalse(S, RHSExpr)) 10730 return; 10731 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 10732 if (!EvaluatesAsTrue(S, Bop->getLHS())) 10733 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 10734 } else if (Bop->getOpcode() == BO_LOr) { 10735 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 10736 // If it's "a || b && 1 || c" we didn't warn earlier for 10737 // "a || b && 1", but warn now. 10738 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 10739 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 10740 } 10741 } 10742 } 10743 } 10744 10745 /// \brief Look for '&&' in the right hand of a '||' expr. 10746 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 10747 Expr *LHSExpr, Expr *RHSExpr) { 10748 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 10749 if (Bop->getOpcode() == BO_LAnd) { 10750 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 10751 if (EvaluatesAsFalse(S, LHSExpr)) 10752 return; 10753 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 10754 if (!EvaluatesAsTrue(S, Bop->getRHS())) 10755 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 10756 } 10757 } 10758 } 10759 10760 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 10761 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 10762 /// the '&' expression in parentheses. 10763 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 10764 SourceLocation OpLoc, Expr *SubExpr) { 10765 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 10766 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 10767 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 10768 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 10769 << Bop->getSourceRange() << OpLoc; 10770 SuggestParentheses(S, Bop->getOperatorLoc(), 10771 S.PDiag(diag::note_precedence_silence) 10772 << Bop->getOpcodeStr(), 10773 Bop->getSourceRange()); 10774 } 10775 } 10776 } 10777 10778 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 10779 Expr *SubExpr, StringRef Shift) { 10780 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 10781 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 10782 StringRef Op = Bop->getOpcodeStr(); 10783 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 10784 << Bop->getSourceRange() << OpLoc << Shift << Op; 10785 SuggestParentheses(S, Bop->getOperatorLoc(), 10786 S.PDiag(diag::note_precedence_silence) << Op, 10787 Bop->getSourceRange()); 10788 } 10789 } 10790 } 10791 10792 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 10793 Expr *LHSExpr, Expr *RHSExpr) { 10794 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 10795 if (!OCE) 10796 return; 10797 10798 FunctionDecl *FD = OCE->getDirectCallee(); 10799 if (!FD || !FD->isOverloadedOperator()) 10800 return; 10801 10802 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 10803 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 10804 return; 10805 10806 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 10807 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 10808 << (Kind == OO_LessLess); 10809 SuggestParentheses(S, OCE->getOperatorLoc(), 10810 S.PDiag(diag::note_precedence_silence) 10811 << (Kind == OO_LessLess ? "<<" : ">>"), 10812 OCE->getSourceRange()); 10813 SuggestParentheses(S, OpLoc, 10814 S.PDiag(diag::note_evaluate_comparison_first), 10815 SourceRange(OCE->getArg(1)->getLocStart(), 10816 RHSExpr->getLocEnd())); 10817 } 10818 10819 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 10820 /// precedence. 10821 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 10822 SourceLocation OpLoc, Expr *LHSExpr, 10823 Expr *RHSExpr){ 10824 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 10825 if (BinaryOperator::isBitwiseOp(Opc)) 10826 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 10827 10828 // Diagnose "arg1 & arg2 | arg3" 10829 if ((Opc == BO_Or || Opc == BO_Xor) && 10830 !OpLoc.isMacroID()/* Don't warn in macros. */) { 10831 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 10832 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 10833 } 10834 10835 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 10836 // We don't warn for 'assert(a || b && "bad")' since this is safe. 10837 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 10838 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 10839 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 10840 } 10841 10842 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 10843 || Opc == BO_Shr) { 10844 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 10845 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 10846 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 10847 } 10848 10849 // Warn on overloaded shift operators and comparisons, such as: 10850 // cout << 5 == 4; 10851 if (BinaryOperator::isComparisonOp(Opc)) 10852 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 10853 } 10854 10855 // Binary Operators. 'Tok' is the token for the operator. 10856 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 10857 tok::TokenKind Kind, 10858 Expr *LHSExpr, Expr *RHSExpr) { 10859 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 10860 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 10861 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 10862 10863 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 10864 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 10865 10866 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 10867 } 10868 10869 /// Build an overloaded binary operator expression in the given scope. 10870 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 10871 BinaryOperatorKind Opc, 10872 Expr *LHS, Expr *RHS) { 10873 // Find all of the overloaded operators visible from this 10874 // point. We perform both an operator-name lookup from the local 10875 // scope and an argument-dependent lookup based on the types of 10876 // the arguments. 10877 UnresolvedSet<16> Functions; 10878 OverloadedOperatorKind OverOp 10879 = BinaryOperator::getOverloadedOperator(Opc); 10880 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 10881 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 10882 RHS->getType(), Functions); 10883 10884 // Build the (potentially-overloaded, potentially-dependent) 10885 // binary operation. 10886 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 10887 } 10888 10889 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 10890 BinaryOperatorKind Opc, 10891 Expr *LHSExpr, Expr *RHSExpr) { 10892 // We want to end up calling one of checkPseudoObjectAssignment 10893 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 10894 // both expressions are overloadable or either is type-dependent), 10895 // or CreateBuiltinBinOp (in any other case). We also want to get 10896 // any placeholder types out of the way. 10897 10898 // Handle pseudo-objects in the LHS. 10899 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 10900 // Assignments with a pseudo-object l-value need special analysis. 10901 if (pty->getKind() == BuiltinType::PseudoObject && 10902 BinaryOperator::isAssignmentOp(Opc)) 10903 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 10904 10905 // Don't resolve overloads if the other type is overloadable. 10906 if (pty->getKind() == BuiltinType::Overload) { 10907 // We can't actually test that if we still have a placeholder, 10908 // though. Fortunately, none of the exceptions we see in that 10909 // code below are valid when the LHS is an overload set. Note 10910 // that an overload set can be dependently-typed, but it never 10911 // instantiates to having an overloadable type. 10912 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 10913 if (resolvedRHS.isInvalid()) return ExprError(); 10914 RHSExpr = resolvedRHS.get(); 10915 10916 if (RHSExpr->isTypeDependent() || 10917 RHSExpr->getType()->isOverloadableType()) 10918 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10919 } 10920 10921 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 10922 if (LHS.isInvalid()) return ExprError(); 10923 LHSExpr = LHS.get(); 10924 } 10925 10926 // Handle pseudo-objects in the RHS. 10927 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 10928 // An overload in the RHS can potentially be resolved by the type 10929 // being assigned to. 10930 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 10931 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 10932 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10933 10934 if (LHSExpr->getType()->isOverloadableType()) 10935 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10936 10937 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 10938 } 10939 10940 // Don't resolve overloads if the other type is overloadable. 10941 if (pty->getKind() == BuiltinType::Overload && 10942 LHSExpr->getType()->isOverloadableType()) 10943 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10944 10945 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 10946 if (!resolvedRHS.isUsable()) return ExprError(); 10947 RHSExpr = resolvedRHS.get(); 10948 } 10949 10950 if (getLangOpts().CPlusPlus) { 10951 // If either expression is type-dependent, always build an 10952 // overloaded op. 10953 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 10954 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10955 10956 // Otherwise, build an overloaded op if either expression has an 10957 // overloadable type. 10958 if (LHSExpr->getType()->isOverloadableType() || 10959 RHSExpr->getType()->isOverloadableType()) 10960 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10961 } 10962 10963 // Build a built-in binary operation. 10964 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 10965 } 10966 10967 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 10968 UnaryOperatorKind Opc, 10969 Expr *InputExpr) { 10970 ExprResult Input = InputExpr; 10971 ExprValueKind VK = VK_RValue; 10972 ExprObjectKind OK = OK_Ordinary; 10973 QualType resultType; 10974 if (getLangOpts().OpenCL) { 10975 // The only legal unary operation for atomics is '&'. 10976 if (Opc != UO_AddrOf && InputExpr->getType()->isAtomicType()) { 10977 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10978 << InputExpr->getType() 10979 << Input.get()->getSourceRange()); 10980 } 10981 } 10982 switch (Opc) { 10983 case UO_PreInc: 10984 case UO_PreDec: 10985 case UO_PostInc: 10986 case UO_PostDec: 10987 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 10988 OpLoc, 10989 Opc == UO_PreInc || 10990 Opc == UO_PostInc, 10991 Opc == UO_PreInc || 10992 Opc == UO_PreDec); 10993 break; 10994 case UO_AddrOf: 10995 resultType = CheckAddressOfOperand(Input, OpLoc); 10996 RecordModifiableNonNullParam(*this, InputExpr); 10997 break; 10998 case UO_Deref: { 10999 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11000 if (Input.isInvalid()) return ExprError(); 11001 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 11002 break; 11003 } 11004 case UO_Plus: 11005 case UO_Minus: 11006 Input = UsualUnaryConversions(Input.get()); 11007 if (Input.isInvalid()) return ExprError(); 11008 resultType = Input.get()->getType(); 11009 if (resultType->isDependentType()) 11010 break; 11011 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 11012 break; 11013 else if (resultType->isVectorType() && 11014 // The z vector extensions don't allow + or - with bool vectors. 11015 (!Context.getLangOpts().ZVector || 11016 resultType->getAs<VectorType>()->getVectorKind() != 11017 VectorType::AltiVecBool)) 11018 break; 11019 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 11020 Opc == UO_Plus && 11021 resultType->isPointerType()) 11022 break; 11023 11024 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11025 << resultType << Input.get()->getSourceRange()); 11026 11027 case UO_Not: // bitwise complement 11028 Input = UsualUnaryConversions(Input.get()); 11029 if (Input.isInvalid()) 11030 return ExprError(); 11031 resultType = Input.get()->getType(); 11032 if (resultType->isDependentType()) 11033 break; 11034 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 11035 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 11036 // C99 does not support '~' for complex conjugation. 11037 Diag(OpLoc, diag::ext_integer_complement_complex) 11038 << resultType << Input.get()->getSourceRange(); 11039 else if (resultType->hasIntegerRepresentation()) 11040 break; 11041 else if (resultType->isExtVectorType()) { 11042 if (Context.getLangOpts().OpenCL) { 11043 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 11044 // on vector float types. 11045 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11046 if (!T->isIntegerType()) 11047 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11048 << resultType << Input.get()->getSourceRange()); 11049 } 11050 break; 11051 } else { 11052 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11053 << resultType << Input.get()->getSourceRange()); 11054 } 11055 break; 11056 11057 case UO_LNot: // logical negation 11058 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 11059 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 11060 if (Input.isInvalid()) return ExprError(); 11061 resultType = Input.get()->getType(); 11062 11063 // Though we still have to promote half FP to float... 11064 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 11065 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 11066 resultType = Context.FloatTy; 11067 } 11068 11069 if (resultType->isDependentType()) 11070 break; 11071 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 11072 // C99 6.5.3.3p1: ok, fallthrough; 11073 if (Context.getLangOpts().CPlusPlus) { 11074 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 11075 // operand contextually converted to bool. 11076 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 11077 ScalarTypeToBooleanCastKind(resultType)); 11078 } else if (Context.getLangOpts().OpenCL && 11079 Context.getLangOpts().OpenCLVersion < 120) { 11080 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11081 // operate on scalar float types. 11082 if (!resultType->isIntegerType()) 11083 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11084 << resultType << Input.get()->getSourceRange()); 11085 } 11086 } else if (resultType->isExtVectorType()) { 11087 if (Context.getLangOpts().OpenCL && 11088 Context.getLangOpts().OpenCLVersion < 120) { 11089 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 11090 // operate on vector float types. 11091 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 11092 if (!T->isIntegerType()) 11093 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11094 << resultType << Input.get()->getSourceRange()); 11095 } 11096 // Vector logical not returns the signed variant of the operand type. 11097 resultType = GetSignedVectorType(resultType); 11098 break; 11099 } else { 11100 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 11101 << resultType << Input.get()->getSourceRange()); 11102 } 11103 11104 // LNot always has type int. C99 6.5.3.3p5. 11105 // In C++, it's bool. C++ 5.3.1p8 11106 resultType = Context.getLogicalOperationType(); 11107 break; 11108 case UO_Real: 11109 case UO_Imag: 11110 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 11111 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 11112 // complex l-values to ordinary l-values and all other values to r-values. 11113 if (Input.isInvalid()) return ExprError(); 11114 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 11115 if (Input.get()->getValueKind() != VK_RValue && 11116 Input.get()->getObjectKind() == OK_Ordinary) 11117 VK = Input.get()->getValueKind(); 11118 } else if (!getLangOpts().CPlusPlus) { 11119 // In C, a volatile scalar is read by __imag. In C++, it is not. 11120 Input = DefaultLvalueConversion(Input.get()); 11121 } 11122 break; 11123 case UO_Extension: 11124 case UO_Coawait: 11125 resultType = Input.get()->getType(); 11126 VK = Input.get()->getValueKind(); 11127 OK = Input.get()->getObjectKind(); 11128 break; 11129 } 11130 if (resultType.isNull() || Input.isInvalid()) 11131 return ExprError(); 11132 11133 // Check for array bounds violations in the operand of the UnaryOperator, 11134 // except for the '*' and '&' operators that have to be handled specially 11135 // by CheckArrayAccess (as there are special cases like &array[arraysize] 11136 // that are explicitly defined as valid by the standard). 11137 if (Opc != UO_AddrOf && Opc != UO_Deref) 11138 CheckArrayAccess(Input.get()); 11139 11140 return new (Context) 11141 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 11142 } 11143 11144 /// \brief Determine whether the given expression is a qualified member 11145 /// access expression, of a form that could be turned into a pointer to member 11146 /// with the address-of operator. 11147 static bool isQualifiedMemberAccess(Expr *E) { 11148 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11149 if (!DRE->getQualifier()) 11150 return false; 11151 11152 ValueDecl *VD = DRE->getDecl(); 11153 if (!VD->isCXXClassMember()) 11154 return false; 11155 11156 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 11157 return true; 11158 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 11159 return Method->isInstance(); 11160 11161 return false; 11162 } 11163 11164 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11165 if (!ULE->getQualifier()) 11166 return false; 11167 11168 for (NamedDecl *D : ULE->decls()) { 11169 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 11170 if (Method->isInstance()) 11171 return true; 11172 } else { 11173 // Overload set does not contain methods. 11174 break; 11175 } 11176 } 11177 11178 return false; 11179 } 11180 11181 return false; 11182 } 11183 11184 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 11185 UnaryOperatorKind Opc, Expr *Input) { 11186 // First things first: handle placeholders so that the 11187 // overloaded-operator check considers the right type. 11188 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 11189 // Increment and decrement of pseudo-object references. 11190 if (pty->getKind() == BuiltinType::PseudoObject && 11191 UnaryOperator::isIncrementDecrementOp(Opc)) 11192 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 11193 11194 // extension is always a builtin operator. 11195 if (Opc == UO_Extension) 11196 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11197 11198 // & gets special logic for several kinds of placeholder. 11199 // The builtin code knows what to do. 11200 if (Opc == UO_AddrOf && 11201 (pty->getKind() == BuiltinType::Overload || 11202 pty->getKind() == BuiltinType::UnknownAny || 11203 pty->getKind() == BuiltinType::BoundMember)) 11204 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11205 11206 // Anything else needs to be handled now. 11207 ExprResult Result = CheckPlaceholderExpr(Input); 11208 if (Result.isInvalid()) return ExprError(); 11209 Input = Result.get(); 11210 } 11211 11212 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 11213 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 11214 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 11215 // Find all of the overloaded operators visible from this 11216 // point. We perform both an operator-name lookup from the local 11217 // scope and an argument-dependent lookup based on the types of 11218 // the arguments. 11219 UnresolvedSet<16> Functions; 11220 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 11221 if (S && OverOp != OO_None) 11222 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 11223 Functions); 11224 11225 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 11226 } 11227 11228 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11229 } 11230 11231 // Unary Operators. 'Tok' is the token for the operator. 11232 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 11233 tok::TokenKind Op, Expr *Input) { 11234 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 11235 } 11236 11237 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 11238 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 11239 LabelDecl *TheDecl) { 11240 TheDecl->markUsed(Context); 11241 // Create the AST node. The address of a label always has type 'void*'. 11242 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 11243 Context.getPointerType(Context.VoidTy)); 11244 } 11245 11246 /// Given the last statement in a statement-expression, check whether 11247 /// the result is a producing expression (like a call to an 11248 /// ns_returns_retained function) and, if so, rebuild it to hoist the 11249 /// release out of the full-expression. Otherwise, return null. 11250 /// Cannot fail. 11251 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 11252 // Should always be wrapped with one of these. 11253 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 11254 if (!cleanups) return nullptr; 11255 11256 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 11257 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 11258 return nullptr; 11259 11260 // Splice out the cast. This shouldn't modify any interesting 11261 // features of the statement. 11262 Expr *producer = cast->getSubExpr(); 11263 assert(producer->getType() == cast->getType()); 11264 assert(producer->getValueKind() == cast->getValueKind()); 11265 cleanups->setSubExpr(producer); 11266 return cleanups; 11267 } 11268 11269 void Sema::ActOnStartStmtExpr() { 11270 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 11271 } 11272 11273 void Sema::ActOnStmtExprError() { 11274 // Note that function is also called by TreeTransform when leaving a 11275 // StmtExpr scope without rebuilding anything. 11276 11277 DiscardCleanupsInEvaluationContext(); 11278 PopExpressionEvaluationContext(); 11279 } 11280 11281 ExprResult 11282 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 11283 SourceLocation RPLoc) { // "({..})" 11284 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 11285 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 11286 11287 if (hasAnyUnrecoverableErrorsInThisFunction()) 11288 DiscardCleanupsInEvaluationContext(); 11289 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 11290 PopExpressionEvaluationContext(); 11291 11292 // FIXME: there are a variety of strange constraints to enforce here, for 11293 // example, it is not possible to goto into a stmt expression apparently. 11294 // More semantic analysis is needed. 11295 11296 // If there are sub-stmts in the compound stmt, take the type of the last one 11297 // as the type of the stmtexpr. 11298 QualType Ty = Context.VoidTy; 11299 bool StmtExprMayBindToTemp = false; 11300 if (!Compound->body_empty()) { 11301 Stmt *LastStmt = Compound->body_back(); 11302 LabelStmt *LastLabelStmt = nullptr; 11303 // If LastStmt is a label, skip down through into the body. 11304 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 11305 LastLabelStmt = Label; 11306 LastStmt = Label->getSubStmt(); 11307 } 11308 11309 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 11310 // Do function/array conversion on the last expression, but not 11311 // lvalue-to-rvalue. However, initialize an unqualified type. 11312 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 11313 if (LastExpr.isInvalid()) 11314 return ExprError(); 11315 Ty = LastExpr.get()->getType().getUnqualifiedType(); 11316 11317 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 11318 // In ARC, if the final expression ends in a consume, splice 11319 // the consume out and bind it later. In the alternate case 11320 // (when dealing with a retainable type), the result 11321 // initialization will create a produce. In both cases the 11322 // result will be +1, and we'll need to balance that out with 11323 // a bind. 11324 if (Expr *rebuiltLastStmt 11325 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 11326 LastExpr = rebuiltLastStmt; 11327 } else { 11328 LastExpr = PerformCopyInitialization( 11329 InitializedEntity::InitializeResult(LPLoc, 11330 Ty, 11331 false), 11332 SourceLocation(), 11333 LastExpr); 11334 } 11335 11336 if (LastExpr.isInvalid()) 11337 return ExprError(); 11338 if (LastExpr.get() != nullptr) { 11339 if (!LastLabelStmt) 11340 Compound->setLastStmt(LastExpr.get()); 11341 else 11342 LastLabelStmt->setSubStmt(LastExpr.get()); 11343 StmtExprMayBindToTemp = true; 11344 } 11345 } 11346 } 11347 } 11348 11349 // FIXME: Check that expression type is complete/non-abstract; statement 11350 // expressions are not lvalues. 11351 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 11352 if (StmtExprMayBindToTemp) 11353 return MaybeBindToTemporary(ResStmtExpr); 11354 return ResStmtExpr; 11355 } 11356 11357 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 11358 TypeSourceInfo *TInfo, 11359 ArrayRef<OffsetOfComponent> Components, 11360 SourceLocation RParenLoc) { 11361 QualType ArgTy = TInfo->getType(); 11362 bool Dependent = ArgTy->isDependentType(); 11363 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 11364 11365 // We must have at least one component that refers to the type, and the first 11366 // one is known to be a field designator. Verify that the ArgTy represents 11367 // a struct/union/class. 11368 if (!Dependent && !ArgTy->isRecordType()) 11369 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 11370 << ArgTy << TypeRange); 11371 11372 // Type must be complete per C99 7.17p3 because a declaring a variable 11373 // with an incomplete type would be ill-formed. 11374 if (!Dependent 11375 && RequireCompleteType(BuiltinLoc, ArgTy, 11376 diag::err_offsetof_incomplete_type, TypeRange)) 11377 return ExprError(); 11378 11379 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 11380 // GCC extension, diagnose them. 11381 // FIXME: This diagnostic isn't actually visible because the location is in 11382 // a system header! 11383 if (Components.size() != 1) 11384 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 11385 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 11386 11387 bool DidWarnAboutNonPOD = false; 11388 QualType CurrentType = ArgTy; 11389 SmallVector<OffsetOfNode, 4> Comps; 11390 SmallVector<Expr*, 4> Exprs; 11391 for (const OffsetOfComponent &OC : Components) { 11392 if (OC.isBrackets) { 11393 // Offset of an array sub-field. TODO: Should we allow vector elements? 11394 if (!CurrentType->isDependentType()) { 11395 const ArrayType *AT = Context.getAsArrayType(CurrentType); 11396 if(!AT) 11397 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 11398 << CurrentType); 11399 CurrentType = AT->getElementType(); 11400 } else 11401 CurrentType = Context.DependentTy; 11402 11403 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 11404 if (IdxRval.isInvalid()) 11405 return ExprError(); 11406 Expr *Idx = IdxRval.get(); 11407 11408 // The expression must be an integral expression. 11409 // FIXME: An integral constant expression? 11410 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 11411 !Idx->getType()->isIntegerType()) 11412 return ExprError(Diag(Idx->getLocStart(), 11413 diag::err_typecheck_subscript_not_integer) 11414 << Idx->getSourceRange()); 11415 11416 // Record this array index. 11417 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 11418 Exprs.push_back(Idx); 11419 continue; 11420 } 11421 11422 // Offset of a field. 11423 if (CurrentType->isDependentType()) { 11424 // We have the offset of a field, but we can't look into the dependent 11425 // type. Just record the identifier of the field. 11426 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 11427 CurrentType = Context.DependentTy; 11428 continue; 11429 } 11430 11431 // We need to have a complete type to look into. 11432 if (RequireCompleteType(OC.LocStart, CurrentType, 11433 diag::err_offsetof_incomplete_type)) 11434 return ExprError(); 11435 11436 // Look for the designated field. 11437 const RecordType *RC = CurrentType->getAs<RecordType>(); 11438 if (!RC) 11439 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 11440 << CurrentType); 11441 RecordDecl *RD = RC->getDecl(); 11442 11443 // C++ [lib.support.types]p5: 11444 // The macro offsetof accepts a restricted set of type arguments in this 11445 // International Standard. type shall be a POD structure or a POD union 11446 // (clause 9). 11447 // C++11 [support.types]p4: 11448 // If type is not a standard-layout class (Clause 9), the results are 11449 // undefined. 11450 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 11451 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 11452 unsigned DiagID = 11453 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 11454 : diag::ext_offsetof_non_pod_type; 11455 11456 if (!IsSafe && !DidWarnAboutNonPOD && 11457 DiagRuntimeBehavior(BuiltinLoc, nullptr, 11458 PDiag(DiagID) 11459 << SourceRange(Components[0].LocStart, OC.LocEnd) 11460 << CurrentType)) 11461 DidWarnAboutNonPOD = true; 11462 } 11463 11464 // Look for the field. 11465 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 11466 LookupQualifiedName(R, RD); 11467 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 11468 IndirectFieldDecl *IndirectMemberDecl = nullptr; 11469 if (!MemberDecl) { 11470 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 11471 MemberDecl = IndirectMemberDecl->getAnonField(); 11472 } 11473 11474 if (!MemberDecl) 11475 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 11476 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 11477 OC.LocEnd)); 11478 11479 // C99 7.17p3: 11480 // (If the specified member is a bit-field, the behavior is undefined.) 11481 // 11482 // We diagnose this as an error. 11483 if (MemberDecl->isBitField()) { 11484 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 11485 << MemberDecl->getDeclName() 11486 << SourceRange(BuiltinLoc, RParenLoc); 11487 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 11488 return ExprError(); 11489 } 11490 11491 RecordDecl *Parent = MemberDecl->getParent(); 11492 if (IndirectMemberDecl) 11493 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 11494 11495 // If the member was found in a base class, introduce OffsetOfNodes for 11496 // the base class indirections. 11497 CXXBasePaths Paths; 11498 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 11499 Paths)) { 11500 if (Paths.getDetectedVirtual()) { 11501 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 11502 << MemberDecl->getDeclName() 11503 << SourceRange(BuiltinLoc, RParenLoc); 11504 return ExprError(); 11505 } 11506 11507 CXXBasePath &Path = Paths.front(); 11508 for (const CXXBasePathElement &B : Path) 11509 Comps.push_back(OffsetOfNode(B.Base)); 11510 } 11511 11512 if (IndirectMemberDecl) { 11513 for (auto *FI : IndirectMemberDecl->chain()) { 11514 assert(isa<FieldDecl>(FI)); 11515 Comps.push_back(OffsetOfNode(OC.LocStart, 11516 cast<FieldDecl>(FI), OC.LocEnd)); 11517 } 11518 } else 11519 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 11520 11521 CurrentType = MemberDecl->getType().getNonReferenceType(); 11522 } 11523 11524 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 11525 Comps, Exprs, RParenLoc); 11526 } 11527 11528 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 11529 SourceLocation BuiltinLoc, 11530 SourceLocation TypeLoc, 11531 ParsedType ParsedArgTy, 11532 ArrayRef<OffsetOfComponent> Components, 11533 SourceLocation RParenLoc) { 11534 11535 TypeSourceInfo *ArgTInfo; 11536 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 11537 if (ArgTy.isNull()) 11538 return ExprError(); 11539 11540 if (!ArgTInfo) 11541 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 11542 11543 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 11544 } 11545 11546 11547 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 11548 Expr *CondExpr, 11549 Expr *LHSExpr, Expr *RHSExpr, 11550 SourceLocation RPLoc) { 11551 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 11552 11553 ExprValueKind VK = VK_RValue; 11554 ExprObjectKind OK = OK_Ordinary; 11555 QualType resType; 11556 bool ValueDependent = false; 11557 bool CondIsTrue = false; 11558 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 11559 resType = Context.DependentTy; 11560 ValueDependent = true; 11561 } else { 11562 // The conditional expression is required to be a constant expression. 11563 llvm::APSInt condEval(32); 11564 ExprResult CondICE 11565 = VerifyIntegerConstantExpression(CondExpr, &condEval, 11566 diag::err_typecheck_choose_expr_requires_constant, false); 11567 if (CondICE.isInvalid()) 11568 return ExprError(); 11569 CondExpr = CondICE.get(); 11570 CondIsTrue = condEval.getZExtValue(); 11571 11572 // If the condition is > zero, then the AST type is the same as the LSHExpr. 11573 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 11574 11575 resType = ActiveExpr->getType(); 11576 ValueDependent = ActiveExpr->isValueDependent(); 11577 VK = ActiveExpr->getValueKind(); 11578 OK = ActiveExpr->getObjectKind(); 11579 } 11580 11581 return new (Context) 11582 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 11583 CondIsTrue, resType->isDependentType(), ValueDependent); 11584 } 11585 11586 //===----------------------------------------------------------------------===// 11587 // Clang Extensions. 11588 //===----------------------------------------------------------------------===// 11589 11590 /// ActOnBlockStart - This callback is invoked when a block literal is started. 11591 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 11592 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 11593 11594 if (LangOpts.CPlusPlus) { 11595 Decl *ManglingContextDecl; 11596 if (MangleNumberingContext *MCtx = 11597 getCurrentMangleNumberContext(Block->getDeclContext(), 11598 ManglingContextDecl)) { 11599 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 11600 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 11601 } 11602 } 11603 11604 PushBlockScope(CurScope, Block); 11605 CurContext->addDecl(Block); 11606 if (CurScope) 11607 PushDeclContext(CurScope, Block); 11608 else 11609 CurContext = Block; 11610 11611 getCurBlock()->HasImplicitReturnType = true; 11612 11613 // Enter a new evaluation context to insulate the block from any 11614 // cleanups from the enclosing full-expression. 11615 PushExpressionEvaluationContext(PotentiallyEvaluated); 11616 } 11617 11618 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 11619 Scope *CurScope) { 11620 assert(ParamInfo.getIdentifier() == nullptr && 11621 "block-id should have no identifier!"); 11622 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 11623 BlockScopeInfo *CurBlock = getCurBlock(); 11624 11625 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 11626 QualType T = Sig->getType(); 11627 11628 // FIXME: We should allow unexpanded parameter packs here, but that would, 11629 // in turn, make the block expression contain unexpanded parameter packs. 11630 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 11631 // Drop the parameters. 11632 FunctionProtoType::ExtProtoInfo EPI; 11633 EPI.HasTrailingReturn = false; 11634 EPI.TypeQuals |= DeclSpec::TQ_const; 11635 T = Context.getFunctionType(Context.DependentTy, None, EPI); 11636 Sig = Context.getTrivialTypeSourceInfo(T); 11637 } 11638 11639 // GetTypeForDeclarator always produces a function type for a block 11640 // literal signature. Furthermore, it is always a FunctionProtoType 11641 // unless the function was written with a typedef. 11642 assert(T->isFunctionType() && 11643 "GetTypeForDeclarator made a non-function block signature"); 11644 11645 // Look for an explicit signature in that function type. 11646 FunctionProtoTypeLoc ExplicitSignature; 11647 11648 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 11649 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 11650 11651 // Check whether that explicit signature was synthesized by 11652 // GetTypeForDeclarator. If so, don't save that as part of the 11653 // written signature. 11654 if (ExplicitSignature.getLocalRangeBegin() == 11655 ExplicitSignature.getLocalRangeEnd()) { 11656 // This would be much cheaper if we stored TypeLocs instead of 11657 // TypeSourceInfos. 11658 TypeLoc Result = ExplicitSignature.getReturnLoc(); 11659 unsigned Size = Result.getFullDataSize(); 11660 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 11661 Sig->getTypeLoc().initializeFullCopy(Result, Size); 11662 11663 ExplicitSignature = FunctionProtoTypeLoc(); 11664 } 11665 } 11666 11667 CurBlock->TheDecl->setSignatureAsWritten(Sig); 11668 CurBlock->FunctionType = T; 11669 11670 const FunctionType *Fn = T->getAs<FunctionType>(); 11671 QualType RetTy = Fn->getReturnType(); 11672 bool isVariadic = 11673 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 11674 11675 CurBlock->TheDecl->setIsVariadic(isVariadic); 11676 11677 // Context.DependentTy is used as a placeholder for a missing block 11678 // return type. TODO: what should we do with declarators like: 11679 // ^ * { ... } 11680 // If the answer is "apply template argument deduction".... 11681 if (RetTy != Context.DependentTy) { 11682 CurBlock->ReturnType = RetTy; 11683 CurBlock->TheDecl->setBlockMissingReturnType(false); 11684 CurBlock->HasImplicitReturnType = false; 11685 } 11686 11687 // Push block parameters from the declarator if we had them. 11688 SmallVector<ParmVarDecl*, 8> Params; 11689 if (ExplicitSignature) { 11690 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 11691 ParmVarDecl *Param = ExplicitSignature.getParam(I); 11692 if (Param->getIdentifier() == nullptr && 11693 !Param->isImplicit() && 11694 !Param->isInvalidDecl() && 11695 !getLangOpts().CPlusPlus) 11696 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 11697 Params.push_back(Param); 11698 } 11699 11700 // Fake up parameter variables if we have a typedef, like 11701 // ^ fntype { ... } 11702 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 11703 for (const auto &I : Fn->param_types()) { 11704 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 11705 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 11706 Params.push_back(Param); 11707 } 11708 } 11709 11710 // Set the parameters on the block decl. 11711 if (!Params.empty()) { 11712 CurBlock->TheDecl->setParams(Params); 11713 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 11714 CurBlock->TheDecl->param_end(), 11715 /*CheckParameterNames=*/false); 11716 } 11717 11718 // Finally we can process decl attributes. 11719 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 11720 11721 // Put the parameter variables in scope. 11722 for (auto AI : CurBlock->TheDecl->params()) { 11723 AI->setOwningFunction(CurBlock->TheDecl); 11724 11725 // If this has an identifier, add it to the scope stack. 11726 if (AI->getIdentifier()) { 11727 CheckShadow(CurBlock->TheScope, AI); 11728 11729 PushOnScopeChains(AI, CurBlock->TheScope); 11730 } 11731 } 11732 } 11733 11734 /// ActOnBlockError - If there is an error parsing a block, this callback 11735 /// is invoked to pop the information about the block from the action impl. 11736 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 11737 // Leave the expression-evaluation context. 11738 DiscardCleanupsInEvaluationContext(); 11739 PopExpressionEvaluationContext(); 11740 11741 // Pop off CurBlock, handle nested blocks. 11742 PopDeclContext(); 11743 PopFunctionScopeInfo(); 11744 } 11745 11746 /// ActOnBlockStmtExpr - This is called when the body of a block statement 11747 /// literal was successfully completed. ^(int x){...} 11748 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 11749 Stmt *Body, Scope *CurScope) { 11750 // If blocks are disabled, emit an error. 11751 if (!LangOpts.Blocks) 11752 Diag(CaretLoc, diag::err_blocks_disable); 11753 11754 // Leave the expression-evaluation context. 11755 if (hasAnyUnrecoverableErrorsInThisFunction()) 11756 DiscardCleanupsInEvaluationContext(); 11757 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 11758 PopExpressionEvaluationContext(); 11759 11760 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 11761 11762 if (BSI->HasImplicitReturnType) 11763 deduceClosureReturnType(*BSI); 11764 11765 PopDeclContext(); 11766 11767 QualType RetTy = Context.VoidTy; 11768 if (!BSI->ReturnType.isNull()) 11769 RetTy = BSI->ReturnType; 11770 11771 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 11772 QualType BlockTy; 11773 11774 // Set the captured variables on the block. 11775 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 11776 SmallVector<BlockDecl::Capture, 4> Captures; 11777 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 11778 if (Cap.isThisCapture()) 11779 continue; 11780 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 11781 Cap.isNested(), Cap.getInitExpr()); 11782 Captures.push_back(NewCap); 11783 } 11784 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 11785 11786 // If the user wrote a function type in some form, try to use that. 11787 if (!BSI->FunctionType.isNull()) { 11788 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 11789 11790 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 11791 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 11792 11793 // Turn protoless block types into nullary block types. 11794 if (isa<FunctionNoProtoType>(FTy)) { 11795 FunctionProtoType::ExtProtoInfo EPI; 11796 EPI.ExtInfo = Ext; 11797 BlockTy = Context.getFunctionType(RetTy, None, EPI); 11798 11799 // Otherwise, if we don't need to change anything about the function type, 11800 // preserve its sugar structure. 11801 } else if (FTy->getReturnType() == RetTy && 11802 (!NoReturn || FTy->getNoReturnAttr())) { 11803 BlockTy = BSI->FunctionType; 11804 11805 // Otherwise, make the minimal modifications to the function type. 11806 } else { 11807 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 11808 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11809 EPI.TypeQuals = 0; // FIXME: silently? 11810 EPI.ExtInfo = Ext; 11811 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 11812 } 11813 11814 // If we don't have a function type, just build one from nothing. 11815 } else { 11816 FunctionProtoType::ExtProtoInfo EPI; 11817 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 11818 BlockTy = Context.getFunctionType(RetTy, None, EPI); 11819 } 11820 11821 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 11822 BSI->TheDecl->param_end()); 11823 BlockTy = Context.getBlockPointerType(BlockTy); 11824 11825 // If needed, diagnose invalid gotos and switches in the block. 11826 if (getCurFunction()->NeedsScopeChecking() && 11827 !PP.isCodeCompletionEnabled()) 11828 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 11829 11830 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 11831 11832 // Try to apply the named return value optimization. We have to check again 11833 // if we can do this, though, because blocks keep return statements around 11834 // to deduce an implicit return type. 11835 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 11836 !BSI->TheDecl->isDependentContext()) 11837 computeNRVO(Body, BSI); 11838 11839 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 11840 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 11841 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 11842 11843 // If the block isn't obviously global, i.e. it captures anything at 11844 // all, then we need to do a few things in the surrounding context: 11845 if (Result->getBlockDecl()->hasCaptures()) { 11846 // First, this expression has a new cleanup object. 11847 ExprCleanupObjects.push_back(Result->getBlockDecl()); 11848 ExprNeedsCleanups = true; 11849 11850 // It also gets a branch-protected scope if any of the captured 11851 // variables needs destruction. 11852 for (const auto &CI : Result->getBlockDecl()->captures()) { 11853 const VarDecl *var = CI.getVariable(); 11854 if (var->getType().isDestructedType() != QualType::DK_none) { 11855 getCurFunction()->setHasBranchProtectedScope(); 11856 break; 11857 } 11858 } 11859 } 11860 11861 return Result; 11862 } 11863 11864 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 11865 SourceLocation RPLoc) { 11866 TypeSourceInfo *TInfo; 11867 GetTypeFromParser(Ty, &TInfo); 11868 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 11869 } 11870 11871 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 11872 Expr *E, TypeSourceInfo *TInfo, 11873 SourceLocation RPLoc) { 11874 Expr *OrigExpr = E; 11875 bool IsMS = false; 11876 11877 // CUDA device code does not support varargs. 11878 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 11879 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 11880 CUDAFunctionTarget T = IdentifyCUDATarget(F); 11881 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 11882 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device)); 11883 } 11884 } 11885 11886 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 11887 // as Microsoft ABI on an actual Microsoft platform, where 11888 // __builtin_ms_va_list and __builtin_va_list are the same.) 11889 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 11890 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 11891 QualType MSVaListType = Context.getBuiltinMSVaListType(); 11892 if (Context.hasSameType(MSVaListType, E->getType())) { 11893 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 11894 return ExprError(); 11895 IsMS = true; 11896 } 11897 } 11898 11899 // Get the va_list type 11900 QualType VaListType = Context.getBuiltinVaListType(); 11901 if (!IsMS) { 11902 if (VaListType->isArrayType()) { 11903 // Deal with implicit array decay; for example, on x86-64, 11904 // va_list is an array, but it's supposed to decay to 11905 // a pointer for va_arg. 11906 VaListType = Context.getArrayDecayedType(VaListType); 11907 // Make sure the input expression also decays appropriately. 11908 ExprResult Result = UsualUnaryConversions(E); 11909 if (Result.isInvalid()) 11910 return ExprError(); 11911 E = Result.get(); 11912 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 11913 // If va_list is a record type and we are compiling in C++ mode, 11914 // check the argument using reference binding. 11915 InitializedEntity Entity = InitializedEntity::InitializeParameter( 11916 Context, Context.getLValueReferenceType(VaListType), false); 11917 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 11918 if (Init.isInvalid()) 11919 return ExprError(); 11920 E = Init.getAs<Expr>(); 11921 } else { 11922 // Otherwise, the va_list argument must be an l-value because 11923 // it is modified by va_arg. 11924 if (!E->isTypeDependent() && 11925 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 11926 return ExprError(); 11927 } 11928 } 11929 11930 if (!IsMS && !E->isTypeDependent() && 11931 !Context.hasSameType(VaListType, E->getType())) 11932 return ExprError(Diag(E->getLocStart(), 11933 diag::err_first_argument_to_va_arg_not_of_type_va_list) 11934 << OrigExpr->getType() << E->getSourceRange()); 11935 11936 if (!TInfo->getType()->isDependentType()) { 11937 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 11938 diag::err_second_parameter_to_va_arg_incomplete, 11939 TInfo->getTypeLoc())) 11940 return ExprError(); 11941 11942 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 11943 TInfo->getType(), 11944 diag::err_second_parameter_to_va_arg_abstract, 11945 TInfo->getTypeLoc())) 11946 return ExprError(); 11947 11948 if (!TInfo->getType().isPODType(Context)) { 11949 Diag(TInfo->getTypeLoc().getBeginLoc(), 11950 TInfo->getType()->isObjCLifetimeType() 11951 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 11952 : diag::warn_second_parameter_to_va_arg_not_pod) 11953 << TInfo->getType() 11954 << TInfo->getTypeLoc().getSourceRange(); 11955 } 11956 11957 // Check for va_arg where arguments of the given type will be promoted 11958 // (i.e. this va_arg is guaranteed to have undefined behavior). 11959 QualType PromoteType; 11960 if (TInfo->getType()->isPromotableIntegerType()) { 11961 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 11962 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 11963 PromoteType = QualType(); 11964 } 11965 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 11966 PromoteType = Context.DoubleTy; 11967 if (!PromoteType.isNull()) 11968 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 11969 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 11970 << TInfo->getType() 11971 << PromoteType 11972 << TInfo->getTypeLoc().getSourceRange()); 11973 } 11974 11975 QualType T = TInfo->getType().getNonLValueExprType(Context); 11976 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 11977 } 11978 11979 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 11980 // The type of __null will be int or long, depending on the size of 11981 // pointers on the target. 11982 QualType Ty; 11983 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 11984 if (pw == Context.getTargetInfo().getIntWidth()) 11985 Ty = Context.IntTy; 11986 else if (pw == Context.getTargetInfo().getLongWidth()) 11987 Ty = Context.LongTy; 11988 else if (pw == Context.getTargetInfo().getLongLongWidth()) 11989 Ty = Context.LongLongTy; 11990 else { 11991 llvm_unreachable("I don't know size of pointer!"); 11992 } 11993 11994 return new (Context) GNUNullExpr(Ty, TokenLoc); 11995 } 11996 11997 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 11998 bool Diagnose) { 11999 if (!getLangOpts().ObjC1) 12000 return false; 12001 12002 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 12003 if (!PT) 12004 return false; 12005 12006 if (!PT->isObjCIdType()) { 12007 // Check if the destination is the 'NSString' interface. 12008 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 12009 if (!ID || !ID->getIdentifier()->isStr("NSString")) 12010 return false; 12011 } 12012 12013 // Ignore any parens, implicit casts (should only be 12014 // array-to-pointer decays), and not-so-opaque values. The last is 12015 // important for making this trigger for property assignments. 12016 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 12017 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 12018 if (OV->getSourceExpr()) 12019 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 12020 12021 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 12022 if (!SL || !SL->isAscii()) 12023 return false; 12024 if (Diagnose) 12025 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 12026 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 12027 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 12028 return true; 12029 } 12030 12031 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 12032 const Expr *SrcExpr) { 12033 if (!DstType->isFunctionPointerType() || 12034 !SrcExpr->getType()->isFunctionType()) 12035 return false; 12036 12037 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 12038 if (!DRE) 12039 return false; 12040 12041 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12042 if (!FD) 12043 return false; 12044 12045 return !S.checkAddressOfFunctionIsAvailable(FD, 12046 /*Complain=*/true, 12047 SrcExpr->getLocStart()); 12048 } 12049 12050 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 12051 SourceLocation Loc, 12052 QualType DstType, QualType SrcType, 12053 Expr *SrcExpr, AssignmentAction Action, 12054 bool *Complained) { 12055 if (Complained) 12056 *Complained = false; 12057 12058 // Decode the result (notice that AST's are still created for extensions). 12059 bool CheckInferredResultType = false; 12060 bool isInvalid = false; 12061 unsigned DiagKind = 0; 12062 FixItHint Hint; 12063 ConversionFixItGenerator ConvHints; 12064 bool MayHaveConvFixit = false; 12065 bool MayHaveFunctionDiff = false; 12066 const ObjCInterfaceDecl *IFace = nullptr; 12067 const ObjCProtocolDecl *PDecl = nullptr; 12068 12069 switch (ConvTy) { 12070 case Compatible: 12071 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 12072 return false; 12073 12074 case PointerToInt: 12075 DiagKind = diag::ext_typecheck_convert_pointer_int; 12076 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12077 MayHaveConvFixit = true; 12078 break; 12079 case IntToPointer: 12080 DiagKind = diag::ext_typecheck_convert_int_pointer; 12081 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12082 MayHaveConvFixit = true; 12083 break; 12084 case IncompatiblePointer: 12085 DiagKind = 12086 (Action == AA_Passing_CFAudited ? 12087 diag::err_arc_typecheck_convert_incompatible_pointer : 12088 diag::ext_typecheck_convert_incompatible_pointer); 12089 CheckInferredResultType = DstType->isObjCObjectPointerType() && 12090 SrcType->isObjCObjectPointerType(); 12091 if (Hint.isNull() && !CheckInferredResultType) { 12092 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12093 } 12094 else if (CheckInferredResultType) { 12095 SrcType = SrcType.getUnqualifiedType(); 12096 DstType = DstType.getUnqualifiedType(); 12097 } 12098 MayHaveConvFixit = true; 12099 break; 12100 case IncompatiblePointerSign: 12101 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 12102 break; 12103 case FunctionVoidPointer: 12104 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 12105 break; 12106 case IncompatiblePointerDiscardsQualifiers: { 12107 // Perform array-to-pointer decay if necessary. 12108 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 12109 12110 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 12111 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 12112 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 12113 DiagKind = diag::err_typecheck_incompatible_address_space; 12114 break; 12115 12116 12117 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 12118 DiagKind = diag::err_typecheck_incompatible_ownership; 12119 break; 12120 } 12121 12122 llvm_unreachable("unknown error case for discarding qualifiers!"); 12123 // fallthrough 12124 } 12125 case CompatiblePointerDiscardsQualifiers: 12126 // If the qualifiers lost were because we were applying the 12127 // (deprecated) C++ conversion from a string literal to a char* 12128 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 12129 // Ideally, this check would be performed in 12130 // checkPointerTypesForAssignment. However, that would require a 12131 // bit of refactoring (so that the second argument is an 12132 // expression, rather than a type), which should be done as part 12133 // of a larger effort to fix checkPointerTypesForAssignment for 12134 // C++ semantics. 12135 if (getLangOpts().CPlusPlus && 12136 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 12137 return false; 12138 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 12139 break; 12140 case IncompatibleNestedPointerQualifiers: 12141 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 12142 break; 12143 case IntToBlockPointer: 12144 DiagKind = diag::err_int_to_block_pointer; 12145 break; 12146 case IncompatibleBlockPointer: 12147 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 12148 break; 12149 case IncompatibleObjCQualifiedId: { 12150 if (SrcType->isObjCQualifiedIdType()) { 12151 const ObjCObjectPointerType *srcOPT = 12152 SrcType->getAs<ObjCObjectPointerType>(); 12153 for (auto *srcProto : srcOPT->quals()) { 12154 PDecl = srcProto; 12155 break; 12156 } 12157 if (const ObjCInterfaceType *IFaceT = 12158 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12159 IFace = IFaceT->getDecl(); 12160 } 12161 else if (DstType->isObjCQualifiedIdType()) { 12162 const ObjCObjectPointerType *dstOPT = 12163 DstType->getAs<ObjCObjectPointerType>(); 12164 for (auto *dstProto : dstOPT->quals()) { 12165 PDecl = dstProto; 12166 break; 12167 } 12168 if (const ObjCInterfaceType *IFaceT = 12169 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 12170 IFace = IFaceT->getDecl(); 12171 } 12172 DiagKind = diag::warn_incompatible_qualified_id; 12173 break; 12174 } 12175 case IncompatibleVectors: 12176 DiagKind = diag::warn_incompatible_vectors; 12177 break; 12178 case IncompatibleObjCWeakRef: 12179 DiagKind = diag::err_arc_weak_unavailable_assign; 12180 break; 12181 case Incompatible: 12182 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 12183 if (Complained) 12184 *Complained = true; 12185 return true; 12186 } 12187 12188 DiagKind = diag::err_typecheck_convert_incompatible; 12189 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12190 MayHaveConvFixit = true; 12191 isInvalid = true; 12192 MayHaveFunctionDiff = true; 12193 break; 12194 } 12195 12196 QualType FirstType, SecondType; 12197 switch (Action) { 12198 case AA_Assigning: 12199 case AA_Initializing: 12200 // The destination type comes first. 12201 FirstType = DstType; 12202 SecondType = SrcType; 12203 break; 12204 12205 case AA_Returning: 12206 case AA_Passing: 12207 case AA_Passing_CFAudited: 12208 case AA_Converting: 12209 case AA_Sending: 12210 case AA_Casting: 12211 // The source type comes first. 12212 FirstType = SrcType; 12213 SecondType = DstType; 12214 break; 12215 } 12216 12217 PartialDiagnostic FDiag = PDiag(DiagKind); 12218 if (Action == AA_Passing_CFAudited) 12219 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 12220 else 12221 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 12222 12223 // If we can fix the conversion, suggest the FixIts. 12224 assert(ConvHints.isNull() || Hint.isNull()); 12225 if (!ConvHints.isNull()) { 12226 for (FixItHint &H : ConvHints.Hints) 12227 FDiag << H; 12228 } else { 12229 FDiag << Hint; 12230 } 12231 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 12232 12233 if (MayHaveFunctionDiff) 12234 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 12235 12236 Diag(Loc, FDiag); 12237 if (DiagKind == diag::warn_incompatible_qualified_id && 12238 PDecl && IFace && !IFace->hasDefinition()) 12239 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id) 12240 << IFace->getName() << PDecl->getName(); 12241 12242 if (SecondType == Context.OverloadTy) 12243 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 12244 FirstType, /*TakingAddress=*/true); 12245 12246 if (CheckInferredResultType) 12247 EmitRelatedResultTypeNote(SrcExpr); 12248 12249 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 12250 EmitRelatedResultTypeNoteForReturn(DstType); 12251 12252 if (Complained) 12253 *Complained = true; 12254 return isInvalid; 12255 } 12256 12257 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12258 llvm::APSInt *Result) { 12259 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 12260 public: 12261 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12262 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 12263 } 12264 } Diagnoser; 12265 12266 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 12267 } 12268 12269 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12270 llvm::APSInt *Result, 12271 unsigned DiagID, 12272 bool AllowFold) { 12273 class IDDiagnoser : public VerifyICEDiagnoser { 12274 unsigned DiagID; 12275 12276 public: 12277 IDDiagnoser(unsigned DiagID) 12278 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 12279 12280 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12281 S.Diag(Loc, DiagID) << SR; 12282 } 12283 } Diagnoser(DiagID); 12284 12285 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 12286 } 12287 12288 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 12289 SourceRange SR) { 12290 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 12291 } 12292 12293 ExprResult 12294 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 12295 VerifyICEDiagnoser &Diagnoser, 12296 bool AllowFold) { 12297 SourceLocation DiagLoc = E->getLocStart(); 12298 12299 if (getLangOpts().CPlusPlus11) { 12300 // C++11 [expr.const]p5: 12301 // If an expression of literal class type is used in a context where an 12302 // integral constant expression is required, then that class type shall 12303 // have a single non-explicit conversion function to an integral or 12304 // unscoped enumeration type 12305 ExprResult Converted; 12306 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 12307 public: 12308 CXX11ConvertDiagnoser(bool Silent) 12309 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 12310 Silent, true) {} 12311 12312 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12313 QualType T) override { 12314 return S.Diag(Loc, diag::err_ice_not_integral) << T; 12315 } 12316 12317 SemaDiagnosticBuilder diagnoseIncomplete( 12318 Sema &S, SourceLocation Loc, QualType T) override { 12319 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 12320 } 12321 12322 SemaDiagnosticBuilder diagnoseExplicitConv( 12323 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12324 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 12325 } 12326 12327 SemaDiagnosticBuilder noteExplicitConv( 12328 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12329 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12330 << ConvTy->isEnumeralType() << ConvTy; 12331 } 12332 12333 SemaDiagnosticBuilder diagnoseAmbiguous( 12334 Sema &S, SourceLocation Loc, QualType T) override { 12335 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 12336 } 12337 12338 SemaDiagnosticBuilder noteAmbiguous( 12339 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12340 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12341 << ConvTy->isEnumeralType() << ConvTy; 12342 } 12343 12344 SemaDiagnosticBuilder diagnoseConversion( 12345 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12346 llvm_unreachable("conversion functions are permitted"); 12347 } 12348 } ConvertDiagnoser(Diagnoser.Suppress); 12349 12350 Converted = PerformContextualImplicitConversion(DiagLoc, E, 12351 ConvertDiagnoser); 12352 if (Converted.isInvalid()) 12353 return Converted; 12354 E = Converted.get(); 12355 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 12356 return ExprError(); 12357 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12358 // An ICE must be of integral or unscoped enumeration type. 12359 if (!Diagnoser.Suppress) 12360 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12361 return ExprError(); 12362 } 12363 12364 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 12365 // in the non-ICE case. 12366 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 12367 if (Result) 12368 *Result = E->EvaluateKnownConstInt(Context); 12369 return E; 12370 } 12371 12372 Expr::EvalResult EvalResult; 12373 SmallVector<PartialDiagnosticAt, 8> Notes; 12374 EvalResult.Diag = &Notes; 12375 12376 // Try to evaluate the expression, and produce diagnostics explaining why it's 12377 // not a constant expression as a side-effect. 12378 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 12379 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 12380 12381 // In C++11, we can rely on diagnostics being produced for any expression 12382 // which is not a constant expression. If no diagnostics were produced, then 12383 // this is a constant expression. 12384 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 12385 if (Result) 12386 *Result = EvalResult.Val.getInt(); 12387 return E; 12388 } 12389 12390 // If our only note is the usual "invalid subexpression" note, just point 12391 // the caret at its location rather than producing an essentially 12392 // redundant note. 12393 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12394 diag::note_invalid_subexpr_in_const_expr) { 12395 DiagLoc = Notes[0].first; 12396 Notes.clear(); 12397 } 12398 12399 if (!Folded || !AllowFold) { 12400 if (!Diagnoser.Suppress) { 12401 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12402 for (const PartialDiagnosticAt &Note : Notes) 12403 Diag(Note.first, Note.second); 12404 } 12405 12406 return ExprError(); 12407 } 12408 12409 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 12410 for (const PartialDiagnosticAt &Note : Notes) 12411 Diag(Note.first, Note.second); 12412 12413 if (Result) 12414 *Result = EvalResult.Val.getInt(); 12415 return E; 12416 } 12417 12418 namespace { 12419 // Handle the case where we conclude a expression which we speculatively 12420 // considered to be unevaluated is actually evaluated. 12421 class TransformToPE : public TreeTransform<TransformToPE> { 12422 typedef TreeTransform<TransformToPE> BaseTransform; 12423 12424 public: 12425 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 12426 12427 // Make sure we redo semantic analysis 12428 bool AlwaysRebuild() { return true; } 12429 12430 // Make sure we handle LabelStmts correctly. 12431 // FIXME: This does the right thing, but maybe we need a more general 12432 // fix to TreeTransform? 12433 StmtResult TransformLabelStmt(LabelStmt *S) { 12434 S->getDecl()->setStmt(nullptr); 12435 return BaseTransform::TransformLabelStmt(S); 12436 } 12437 12438 // We need to special-case DeclRefExprs referring to FieldDecls which 12439 // are not part of a member pointer formation; normal TreeTransforming 12440 // doesn't catch this case because of the way we represent them in the AST. 12441 // FIXME: This is a bit ugly; is it really the best way to handle this 12442 // case? 12443 // 12444 // Error on DeclRefExprs referring to FieldDecls. 12445 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 12446 if (isa<FieldDecl>(E->getDecl()) && 12447 !SemaRef.isUnevaluatedContext()) 12448 return SemaRef.Diag(E->getLocation(), 12449 diag::err_invalid_non_static_member_use) 12450 << E->getDecl() << E->getSourceRange(); 12451 12452 return BaseTransform::TransformDeclRefExpr(E); 12453 } 12454 12455 // Exception: filter out member pointer formation 12456 ExprResult TransformUnaryOperator(UnaryOperator *E) { 12457 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 12458 return E; 12459 12460 return BaseTransform::TransformUnaryOperator(E); 12461 } 12462 12463 ExprResult TransformLambdaExpr(LambdaExpr *E) { 12464 // Lambdas never need to be transformed. 12465 return E; 12466 } 12467 }; 12468 } 12469 12470 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 12471 assert(isUnevaluatedContext() && 12472 "Should only transform unevaluated expressions"); 12473 ExprEvalContexts.back().Context = 12474 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 12475 if (isUnevaluatedContext()) 12476 return E; 12477 return TransformToPE(*this).TransformExpr(E); 12478 } 12479 12480 void 12481 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12482 Decl *LambdaContextDecl, 12483 bool IsDecltype) { 12484 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), 12485 ExprNeedsCleanups, LambdaContextDecl, 12486 IsDecltype); 12487 ExprNeedsCleanups = false; 12488 if (!MaybeODRUseExprs.empty()) 12489 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 12490 } 12491 12492 void 12493 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12494 ReuseLambdaContextDecl_t, 12495 bool IsDecltype) { 12496 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 12497 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 12498 } 12499 12500 void Sema::PopExpressionEvaluationContext() { 12501 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 12502 unsigned NumTypos = Rec.NumTypos; 12503 12504 if (!Rec.Lambdas.empty()) { 12505 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12506 unsigned D; 12507 if (Rec.isUnevaluated()) { 12508 // C++11 [expr.prim.lambda]p2: 12509 // A lambda-expression shall not appear in an unevaluated operand 12510 // (Clause 5). 12511 D = diag::err_lambda_unevaluated_operand; 12512 } else { 12513 // C++1y [expr.const]p2: 12514 // A conditional-expression e is a core constant expression unless the 12515 // evaluation of e, following the rules of the abstract machine, would 12516 // evaluate [...] a lambda-expression. 12517 D = diag::err_lambda_in_constant_expression; 12518 } 12519 for (const auto *L : Rec.Lambdas) 12520 Diag(L->getLocStart(), D); 12521 } else { 12522 // Mark the capture expressions odr-used. This was deferred 12523 // during lambda expression creation. 12524 for (auto *Lambda : Rec.Lambdas) { 12525 for (auto *C : Lambda->capture_inits()) 12526 MarkDeclarationsReferencedInExpr(C); 12527 } 12528 } 12529 } 12530 12531 // When are coming out of an unevaluated context, clear out any 12532 // temporaries that we may have created as part of the evaluation of 12533 // the expression in that context: they aren't relevant because they 12534 // will never be constructed. 12535 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12536 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 12537 ExprCleanupObjects.end()); 12538 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 12539 CleanupVarDeclMarking(); 12540 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 12541 // Otherwise, merge the contexts together. 12542 } else { 12543 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 12544 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 12545 Rec.SavedMaybeODRUseExprs.end()); 12546 } 12547 12548 // Pop the current expression evaluation context off the stack. 12549 ExprEvalContexts.pop_back(); 12550 12551 if (!ExprEvalContexts.empty()) 12552 ExprEvalContexts.back().NumTypos += NumTypos; 12553 else 12554 assert(NumTypos == 0 && "There are outstanding typos after popping the " 12555 "last ExpressionEvaluationContextRecord"); 12556 } 12557 12558 void Sema::DiscardCleanupsInEvaluationContext() { 12559 ExprCleanupObjects.erase( 12560 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 12561 ExprCleanupObjects.end()); 12562 ExprNeedsCleanups = false; 12563 MaybeODRUseExprs.clear(); 12564 } 12565 12566 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 12567 if (!E->getType()->isVariablyModifiedType()) 12568 return E; 12569 return TransformToPotentiallyEvaluated(E); 12570 } 12571 12572 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 12573 // Do not mark anything as "used" within a dependent context; wait for 12574 // an instantiation. 12575 if (SemaRef.CurContext->isDependentContext()) 12576 return false; 12577 12578 switch (SemaRef.ExprEvalContexts.back().Context) { 12579 case Sema::Unevaluated: 12580 case Sema::UnevaluatedAbstract: 12581 // We are in an expression that is not potentially evaluated; do nothing. 12582 // (Depending on how you read the standard, we actually do need to do 12583 // something here for null pointer constants, but the standard's 12584 // definition of a null pointer constant is completely crazy.) 12585 return false; 12586 12587 case Sema::ConstantEvaluated: 12588 case Sema::PotentiallyEvaluated: 12589 // We are in a potentially evaluated expression (or a constant-expression 12590 // in C++03); we need to do implicit template instantiation, implicitly 12591 // define class members, and mark most declarations as used. 12592 return true; 12593 12594 case Sema::PotentiallyEvaluatedIfUsed: 12595 // Referenced declarations will only be used if the construct in the 12596 // containing expression is used. 12597 return false; 12598 } 12599 llvm_unreachable("Invalid context"); 12600 } 12601 12602 /// \brief Mark a function referenced, and check whether it is odr-used 12603 /// (C++ [basic.def.odr]p2, C99 6.9p3) 12604 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 12605 bool OdrUse) { 12606 assert(Func && "No function?"); 12607 12608 Func->setReferenced(); 12609 12610 // C++11 [basic.def.odr]p3: 12611 // A function whose name appears as a potentially-evaluated expression is 12612 // odr-used if it is the unique lookup result or the selected member of a 12613 // set of overloaded functions [...]. 12614 // 12615 // We (incorrectly) mark overload resolution as an unevaluated context, so we 12616 // can just check that here. Skip the rest of this function if we've already 12617 // marked the function as used. 12618 if (Func->isUsed(/*CheckUsedAttr=*/false) || 12619 !IsPotentiallyEvaluatedContext(*this)) { 12620 // C++11 [temp.inst]p3: 12621 // Unless a function template specialization has been explicitly 12622 // instantiated or explicitly specialized, the function template 12623 // specialization is implicitly instantiated when the specialization is 12624 // referenced in a context that requires a function definition to exist. 12625 // 12626 // We consider constexpr function templates to be referenced in a context 12627 // that requires a definition to exist whenever they are referenced. 12628 // 12629 // FIXME: This instantiates constexpr functions too frequently. If this is 12630 // really an unevaluated context (and we're not just in the definition of a 12631 // function template or overload resolution or other cases which we 12632 // incorrectly consider to be unevaluated contexts), and we're not in a 12633 // subexpression which we actually need to evaluate (for instance, a 12634 // template argument, array bound or an expression in a braced-init-list), 12635 // we are not permitted to instantiate this constexpr function definition. 12636 // 12637 // FIXME: This also implicitly defines special members too frequently. They 12638 // are only supposed to be implicitly defined if they are odr-used, but they 12639 // are not odr-used from constant expressions in unevaluated contexts. 12640 // However, they cannot be referenced if they are deleted, and they are 12641 // deleted whenever the implicit definition of the special member would 12642 // fail. 12643 if (!Func->isConstexpr() || Func->getBody()) 12644 return; 12645 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 12646 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 12647 return; 12648 } 12649 12650 // Note that this declaration has been used. 12651 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 12652 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 12653 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 12654 if (Constructor->isDefaultConstructor()) { 12655 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 12656 return; 12657 DefineImplicitDefaultConstructor(Loc, Constructor); 12658 } else if (Constructor->isCopyConstructor()) { 12659 DefineImplicitCopyConstructor(Loc, Constructor); 12660 } else if (Constructor->isMoveConstructor()) { 12661 DefineImplicitMoveConstructor(Loc, Constructor); 12662 } 12663 } else if (Constructor->getInheritedConstructor()) { 12664 DefineInheritingConstructor(Loc, Constructor); 12665 } 12666 } else if (CXXDestructorDecl *Destructor = 12667 dyn_cast<CXXDestructorDecl>(Func)) { 12668 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 12669 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 12670 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 12671 return; 12672 DefineImplicitDestructor(Loc, Destructor); 12673 } 12674 if (Destructor->isVirtual() && getLangOpts().AppleKext) 12675 MarkVTableUsed(Loc, Destructor->getParent()); 12676 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 12677 if (MethodDecl->isOverloadedOperator() && 12678 MethodDecl->getOverloadedOperator() == OO_Equal) { 12679 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 12680 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 12681 if (MethodDecl->isCopyAssignmentOperator()) 12682 DefineImplicitCopyAssignment(Loc, MethodDecl); 12683 else 12684 DefineImplicitMoveAssignment(Loc, MethodDecl); 12685 } 12686 } else if (isa<CXXConversionDecl>(MethodDecl) && 12687 MethodDecl->getParent()->isLambda()) { 12688 CXXConversionDecl *Conversion = 12689 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 12690 if (Conversion->isLambdaToBlockPointerConversion()) 12691 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 12692 else 12693 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 12694 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 12695 MarkVTableUsed(Loc, MethodDecl->getParent()); 12696 } 12697 12698 // Recursive functions should be marked when used from another function. 12699 // FIXME: Is this really right? 12700 if (CurContext == Func) return; 12701 12702 // Resolve the exception specification for any function which is 12703 // used: CodeGen will need it. 12704 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 12705 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 12706 ResolveExceptionSpec(Loc, FPT); 12707 12708 if (!OdrUse) return; 12709 12710 // Implicit instantiation of function templates and member functions of 12711 // class templates. 12712 if (Func->isImplicitlyInstantiable()) { 12713 bool AlreadyInstantiated = false; 12714 SourceLocation PointOfInstantiation = Loc; 12715 if (FunctionTemplateSpecializationInfo *SpecInfo 12716 = Func->getTemplateSpecializationInfo()) { 12717 if (SpecInfo->getPointOfInstantiation().isInvalid()) 12718 SpecInfo->setPointOfInstantiation(Loc); 12719 else if (SpecInfo->getTemplateSpecializationKind() 12720 == TSK_ImplicitInstantiation) { 12721 AlreadyInstantiated = true; 12722 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 12723 } 12724 } else if (MemberSpecializationInfo *MSInfo 12725 = Func->getMemberSpecializationInfo()) { 12726 if (MSInfo->getPointOfInstantiation().isInvalid()) 12727 MSInfo->setPointOfInstantiation(Loc); 12728 else if (MSInfo->getTemplateSpecializationKind() 12729 == TSK_ImplicitInstantiation) { 12730 AlreadyInstantiated = true; 12731 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 12732 } 12733 } 12734 12735 if (!AlreadyInstantiated || Func->isConstexpr()) { 12736 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 12737 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 12738 ActiveTemplateInstantiations.size()) 12739 PendingLocalImplicitInstantiations.push_back( 12740 std::make_pair(Func, PointOfInstantiation)); 12741 else if (Func->isConstexpr()) 12742 // Do not defer instantiations of constexpr functions, to avoid the 12743 // expression evaluator needing to call back into Sema if it sees a 12744 // call to such a function. 12745 InstantiateFunctionDefinition(PointOfInstantiation, Func); 12746 else { 12747 PendingInstantiations.push_back(std::make_pair(Func, 12748 PointOfInstantiation)); 12749 // Notify the consumer that a function was implicitly instantiated. 12750 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 12751 } 12752 } 12753 } else { 12754 // Walk redefinitions, as some of them may be instantiable. 12755 for (auto i : Func->redecls()) { 12756 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 12757 MarkFunctionReferenced(Loc, i); 12758 } 12759 } 12760 12761 // Keep track of used but undefined functions. 12762 if (!Func->isDefined()) { 12763 if (mightHaveNonExternalLinkage(Func)) 12764 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 12765 else if (Func->getMostRecentDecl()->isInlined() && 12766 !LangOpts.GNUInline && 12767 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 12768 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 12769 } 12770 12771 // Normally the most current decl is marked used while processing the use and 12772 // any subsequent decls are marked used by decl merging. This fails with 12773 // template instantiation since marking can happen at the end of the file 12774 // and, because of the two phase lookup, this function is called with at 12775 // decl in the middle of a decl chain. We loop to maintain the invariant 12776 // that once a decl is used, all decls after it are also used. 12777 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) { 12778 F->markUsed(Context); 12779 if (F == Func) 12780 break; 12781 } 12782 } 12783 12784 static void 12785 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 12786 VarDecl *var, DeclContext *DC) { 12787 DeclContext *VarDC = var->getDeclContext(); 12788 12789 // If the parameter still belongs to the translation unit, then 12790 // we're actually just using one parameter in the declaration of 12791 // the next. 12792 if (isa<ParmVarDecl>(var) && 12793 isa<TranslationUnitDecl>(VarDC)) 12794 return; 12795 12796 // For C code, don't diagnose about capture if we're not actually in code 12797 // right now; it's impossible to write a non-constant expression outside of 12798 // function context, so we'll get other (more useful) diagnostics later. 12799 // 12800 // For C++, things get a bit more nasty... it would be nice to suppress this 12801 // diagnostic for certain cases like using a local variable in an array bound 12802 // for a member of a local class, but the correct predicate is not obvious. 12803 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 12804 return; 12805 12806 if (isa<CXXMethodDecl>(VarDC) && 12807 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 12808 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 12809 << var->getIdentifier(); 12810 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 12811 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 12812 << var->getIdentifier() << fn->getDeclName(); 12813 } else if (isa<BlockDecl>(VarDC)) { 12814 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 12815 << var->getIdentifier(); 12816 } else { 12817 // FIXME: Is there any other context where a local variable can be 12818 // declared? 12819 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 12820 << var->getIdentifier(); 12821 } 12822 12823 S.Diag(var->getLocation(), diag::note_entity_declared_at) 12824 << var->getIdentifier(); 12825 12826 // FIXME: Add additional diagnostic info about class etc. which prevents 12827 // capture. 12828 } 12829 12830 12831 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 12832 bool &SubCapturesAreNested, 12833 QualType &CaptureType, 12834 QualType &DeclRefType) { 12835 // Check whether we've already captured it. 12836 if (CSI->CaptureMap.count(Var)) { 12837 // If we found a capture, any subcaptures are nested. 12838 SubCapturesAreNested = true; 12839 12840 // Retrieve the capture type for this variable. 12841 CaptureType = CSI->getCapture(Var).getCaptureType(); 12842 12843 // Compute the type of an expression that refers to this variable. 12844 DeclRefType = CaptureType.getNonReferenceType(); 12845 12846 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 12847 // are mutable in the sense that user can change their value - they are 12848 // private instances of the captured declarations. 12849 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 12850 if (Cap.isCopyCapture() && 12851 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 12852 !(isa<CapturedRegionScopeInfo>(CSI) && 12853 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 12854 DeclRefType.addConst(); 12855 return true; 12856 } 12857 return false; 12858 } 12859 12860 // Only block literals, captured statements, and lambda expressions can 12861 // capture; other scopes don't work. 12862 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 12863 SourceLocation Loc, 12864 const bool Diagnose, Sema &S) { 12865 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 12866 return getLambdaAwareParentOfDeclContext(DC); 12867 else if (Var->hasLocalStorage()) { 12868 if (Diagnose) 12869 diagnoseUncapturableValueReference(S, Loc, Var, DC); 12870 } 12871 return nullptr; 12872 } 12873 12874 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 12875 // certain types of variables (unnamed, variably modified types etc.) 12876 // so check for eligibility. 12877 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 12878 SourceLocation Loc, 12879 const bool Diagnose, Sema &S) { 12880 12881 bool IsBlock = isa<BlockScopeInfo>(CSI); 12882 bool IsLambda = isa<LambdaScopeInfo>(CSI); 12883 12884 // Lambdas are not allowed to capture unnamed variables 12885 // (e.g. anonymous unions). 12886 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 12887 // assuming that's the intent. 12888 if (IsLambda && !Var->getDeclName()) { 12889 if (Diagnose) { 12890 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 12891 S.Diag(Var->getLocation(), diag::note_declared_at); 12892 } 12893 return false; 12894 } 12895 12896 // Prohibit variably-modified types in blocks; they're difficult to deal with. 12897 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 12898 if (Diagnose) { 12899 S.Diag(Loc, diag::err_ref_vm_type); 12900 S.Diag(Var->getLocation(), diag::note_previous_decl) 12901 << Var->getDeclName(); 12902 } 12903 return false; 12904 } 12905 // Prohibit structs with flexible array members too. 12906 // We cannot capture what is in the tail end of the struct. 12907 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 12908 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 12909 if (Diagnose) { 12910 if (IsBlock) 12911 S.Diag(Loc, diag::err_ref_flexarray_type); 12912 else 12913 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 12914 << Var->getDeclName(); 12915 S.Diag(Var->getLocation(), diag::note_previous_decl) 12916 << Var->getDeclName(); 12917 } 12918 return false; 12919 } 12920 } 12921 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 12922 // Lambdas and captured statements are not allowed to capture __block 12923 // variables; they don't support the expected semantics. 12924 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 12925 if (Diagnose) { 12926 S.Diag(Loc, diag::err_capture_block_variable) 12927 << Var->getDeclName() << !IsLambda; 12928 S.Diag(Var->getLocation(), diag::note_previous_decl) 12929 << Var->getDeclName(); 12930 } 12931 return false; 12932 } 12933 12934 return true; 12935 } 12936 12937 // Returns true if the capture by block was successful. 12938 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 12939 SourceLocation Loc, 12940 const bool BuildAndDiagnose, 12941 QualType &CaptureType, 12942 QualType &DeclRefType, 12943 const bool Nested, 12944 Sema &S) { 12945 Expr *CopyExpr = nullptr; 12946 bool ByRef = false; 12947 12948 // Blocks are not allowed to capture arrays. 12949 if (CaptureType->isArrayType()) { 12950 if (BuildAndDiagnose) { 12951 S.Diag(Loc, diag::err_ref_array_type); 12952 S.Diag(Var->getLocation(), diag::note_previous_decl) 12953 << Var->getDeclName(); 12954 } 12955 return false; 12956 } 12957 12958 // Forbid the block-capture of autoreleasing variables. 12959 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 12960 if (BuildAndDiagnose) { 12961 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 12962 << /*block*/ 0; 12963 S.Diag(Var->getLocation(), diag::note_previous_decl) 12964 << Var->getDeclName(); 12965 } 12966 return false; 12967 } 12968 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 12969 if (HasBlocksAttr || CaptureType->isReferenceType()) { 12970 // Block capture by reference does not change the capture or 12971 // declaration reference types. 12972 ByRef = true; 12973 } else { 12974 // Block capture by copy introduces 'const'. 12975 CaptureType = CaptureType.getNonReferenceType().withConst(); 12976 DeclRefType = CaptureType; 12977 12978 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 12979 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 12980 // The capture logic needs the destructor, so make sure we mark it. 12981 // Usually this is unnecessary because most local variables have 12982 // their destructors marked at declaration time, but parameters are 12983 // an exception because it's technically only the call site that 12984 // actually requires the destructor. 12985 if (isa<ParmVarDecl>(Var)) 12986 S.FinalizeVarWithDestructor(Var, Record); 12987 12988 // Enter a new evaluation context to insulate the copy 12989 // full-expression. 12990 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 12991 12992 // According to the blocks spec, the capture of a variable from 12993 // the stack requires a const copy constructor. This is not true 12994 // of the copy/move done to move a __block variable to the heap. 12995 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 12996 DeclRefType.withConst(), 12997 VK_LValue, Loc); 12998 12999 ExprResult Result 13000 = S.PerformCopyInitialization( 13001 InitializedEntity::InitializeBlock(Var->getLocation(), 13002 CaptureType, false), 13003 Loc, DeclRef); 13004 13005 // Build a full-expression copy expression if initialization 13006 // succeeded and used a non-trivial constructor. Recover from 13007 // errors by pretending that the copy isn't necessary. 13008 if (!Result.isInvalid() && 13009 !cast<CXXConstructExpr>(Result.get())->getConstructor() 13010 ->isTrivial()) { 13011 Result = S.MaybeCreateExprWithCleanups(Result); 13012 CopyExpr = Result.get(); 13013 } 13014 } 13015 } 13016 } 13017 13018 // Actually capture the variable. 13019 if (BuildAndDiagnose) 13020 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 13021 SourceLocation(), CaptureType, CopyExpr); 13022 13023 return true; 13024 13025 } 13026 13027 13028 /// \brief Capture the given variable in the captured region. 13029 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 13030 VarDecl *Var, 13031 SourceLocation Loc, 13032 const bool BuildAndDiagnose, 13033 QualType &CaptureType, 13034 QualType &DeclRefType, 13035 const bool RefersToCapturedVariable, 13036 Sema &S) { 13037 13038 // By default, capture variables by reference. 13039 bool ByRef = true; 13040 // Using an LValue reference type is consistent with Lambdas (see below). 13041 if (S.getLangOpts().OpenMP) { 13042 ByRef = S.IsOpenMPCapturedByRef(Var, RSI); 13043 if (S.IsOpenMPCapturedDecl(Var)) 13044 DeclRefType = DeclRefType.getUnqualifiedType(); 13045 } 13046 13047 if (ByRef) 13048 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13049 else 13050 CaptureType = DeclRefType; 13051 13052 Expr *CopyExpr = nullptr; 13053 if (BuildAndDiagnose) { 13054 // The current implementation assumes that all variables are captured 13055 // by references. Since there is no capture by copy, no expression 13056 // evaluation will be needed. 13057 RecordDecl *RD = RSI->TheRecordDecl; 13058 13059 FieldDecl *Field 13060 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 13061 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 13062 nullptr, false, ICIS_NoInit); 13063 Field->setImplicit(true); 13064 Field->setAccess(AS_private); 13065 RD->addDecl(Field); 13066 13067 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 13068 DeclRefType, VK_LValue, Loc); 13069 Var->setReferenced(true); 13070 Var->markUsed(S.Context); 13071 } 13072 13073 // Actually capture the variable. 13074 if (BuildAndDiagnose) 13075 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 13076 SourceLocation(), CaptureType, CopyExpr); 13077 13078 13079 return true; 13080 } 13081 13082 /// \brief Create a field within the lambda class for the variable 13083 /// being captured. 13084 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, VarDecl *Var, 13085 QualType FieldType, QualType DeclRefType, 13086 SourceLocation Loc, 13087 bool RefersToCapturedVariable) { 13088 CXXRecordDecl *Lambda = LSI->Lambda; 13089 13090 // Build the non-static data member. 13091 FieldDecl *Field 13092 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 13093 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 13094 nullptr, false, ICIS_NoInit); 13095 Field->setImplicit(true); 13096 Field->setAccess(AS_private); 13097 Lambda->addDecl(Field); 13098 } 13099 13100 /// \brief Capture the given variable in the lambda. 13101 static bool captureInLambda(LambdaScopeInfo *LSI, 13102 VarDecl *Var, 13103 SourceLocation Loc, 13104 const bool BuildAndDiagnose, 13105 QualType &CaptureType, 13106 QualType &DeclRefType, 13107 const bool RefersToCapturedVariable, 13108 const Sema::TryCaptureKind Kind, 13109 SourceLocation EllipsisLoc, 13110 const bool IsTopScope, 13111 Sema &S) { 13112 13113 // Determine whether we are capturing by reference or by value. 13114 bool ByRef = false; 13115 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 13116 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 13117 } else { 13118 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 13119 } 13120 13121 // Compute the type of the field that will capture this variable. 13122 if (ByRef) { 13123 // C++11 [expr.prim.lambda]p15: 13124 // An entity is captured by reference if it is implicitly or 13125 // explicitly captured but not captured by copy. It is 13126 // unspecified whether additional unnamed non-static data 13127 // members are declared in the closure type for entities 13128 // captured by reference. 13129 // 13130 // FIXME: It is not clear whether we want to build an lvalue reference 13131 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 13132 // to do the former, while EDG does the latter. Core issue 1249 will 13133 // clarify, but for now we follow GCC because it's a more permissive and 13134 // easily defensible position. 13135 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 13136 } else { 13137 // C++11 [expr.prim.lambda]p14: 13138 // For each entity captured by copy, an unnamed non-static 13139 // data member is declared in the closure type. The 13140 // declaration order of these members is unspecified. The type 13141 // of such a data member is the type of the corresponding 13142 // captured entity if the entity is not a reference to an 13143 // object, or the referenced type otherwise. [Note: If the 13144 // captured entity is a reference to a function, the 13145 // corresponding data member is also a reference to a 13146 // function. - end note ] 13147 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 13148 if (!RefType->getPointeeType()->isFunctionType()) 13149 CaptureType = RefType->getPointeeType(); 13150 } 13151 13152 // Forbid the lambda copy-capture of autoreleasing variables. 13153 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 13154 if (BuildAndDiagnose) { 13155 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 13156 S.Diag(Var->getLocation(), diag::note_previous_decl) 13157 << Var->getDeclName(); 13158 } 13159 return false; 13160 } 13161 13162 // Make sure that by-copy captures are of a complete and non-abstract type. 13163 if (BuildAndDiagnose) { 13164 if (!CaptureType->isDependentType() && 13165 S.RequireCompleteType(Loc, CaptureType, 13166 diag::err_capture_of_incomplete_type, 13167 Var->getDeclName())) 13168 return false; 13169 13170 if (S.RequireNonAbstractType(Loc, CaptureType, 13171 diag::err_capture_of_abstract_type)) 13172 return false; 13173 } 13174 } 13175 13176 // Capture this variable in the lambda. 13177 if (BuildAndDiagnose) 13178 addAsFieldToClosureType(S, LSI, Var, CaptureType, DeclRefType, Loc, 13179 RefersToCapturedVariable); 13180 13181 // Compute the type of a reference to this captured variable. 13182 if (ByRef) 13183 DeclRefType = CaptureType.getNonReferenceType(); 13184 else { 13185 // C++ [expr.prim.lambda]p5: 13186 // The closure type for a lambda-expression has a public inline 13187 // function call operator [...]. This function call operator is 13188 // declared const (9.3.1) if and only if the lambda-expression’s 13189 // parameter-declaration-clause is not followed by mutable. 13190 DeclRefType = CaptureType.getNonReferenceType(); 13191 if (!LSI->Mutable && !CaptureType->isReferenceType()) 13192 DeclRefType.addConst(); 13193 } 13194 13195 // Add the capture. 13196 if (BuildAndDiagnose) 13197 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 13198 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 13199 13200 return true; 13201 } 13202 13203 bool Sema::tryCaptureVariable( 13204 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 13205 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 13206 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 13207 // An init-capture is notionally from the context surrounding its 13208 // declaration, but its parent DC is the lambda class. 13209 DeclContext *VarDC = Var->getDeclContext(); 13210 if (Var->isInitCapture()) 13211 VarDC = VarDC->getParent(); 13212 13213 DeclContext *DC = CurContext; 13214 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 13215 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 13216 // We need to sync up the Declaration Context with the 13217 // FunctionScopeIndexToStopAt 13218 if (FunctionScopeIndexToStopAt) { 13219 unsigned FSIndex = FunctionScopes.size() - 1; 13220 while (FSIndex != MaxFunctionScopesIndex) { 13221 DC = getLambdaAwareParentOfDeclContext(DC); 13222 --FSIndex; 13223 } 13224 } 13225 13226 13227 // If the variable is declared in the current context, there is no need to 13228 // capture it. 13229 if (VarDC == DC) return true; 13230 13231 // Capture global variables if it is required to use private copy of this 13232 // variable. 13233 bool IsGlobal = !Var->hasLocalStorage(); 13234 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var))) 13235 return true; 13236 13237 // Walk up the stack to determine whether we can capture the variable, 13238 // performing the "simple" checks that don't depend on type. We stop when 13239 // we've either hit the declared scope of the variable or find an existing 13240 // capture of that variable. We start from the innermost capturing-entity 13241 // (the DC) and ensure that all intervening capturing-entities 13242 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 13243 // declcontext can either capture the variable or have already captured 13244 // the variable. 13245 CaptureType = Var->getType(); 13246 DeclRefType = CaptureType.getNonReferenceType(); 13247 bool Nested = false; 13248 bool Explicit = (Kind != TryCapture_Implicit); 13249 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 13250 unsigned OpenMPLevel = 0; 13251 do { 13252 // Only block literals, captured statements, and lambda expressions can 13253 // capture; other scopes don't work. 13254 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 13255 ExprLoc, 13256 BuildAndDiagnose, 13257 *this); 13258 // We need to check for the parent *first* because, if we *have* 13259 // private-captured a global variable, we need to recursively capture it in 13260 // intermediate blocks, lambdas, etc. 13261 if (!ParentDC) { 13262 if (IsGlobal) { 13263 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 13264 break; 13265 } 13266 return true; 13267 } 13268 13269 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 13270 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 13271 13272 13273 // Check whether we've already captured it. 13274 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 13275 DeclRefType)) 13276 break; 13277 // If we are instantiating a generic lambda call operator body, 13278 // we do not want to capture new variables. What was captured 13279 // during either a lambdas transformation or initial parsing 13280 // should be used. 13281 if (isGenericLambdaCallOperatorSpecialization(DC)) { 13282 if (BuildAndDiagnose) { 13283 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13284 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 13285 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13286 Diag(Var->getLocation(), diag::note_previous_decl) 13287 << Var->getDeclName(); 13288 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 13289 } else 13290 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 13291 } 13292 return true; 13293 } 13294 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13295 // certain types of variables (unnamed, variably modified types etc.) 13296 // so check for eligibility. 13297 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 13298 return true; 13299 13300 // Try to capture variable-length arrays types. 13301 if (Var->getType()->isVariablyModifiedType()) { 13302 // We're going to walk down into the type and look for VLA 13303 // expressions. 13304 QualType QTy = Var->getType(); 13305 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 13306 QTy = PVD->getOriginalType(); 13307 captureVariablyModifiedType(Context, QTy, CSI); 13308 } 13309 13310 if (getLangOpts().OpenMP) { 13311 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13312 // OpenMP private variables should not be captured in outer scope, so 13313 // just break here. Similarly, global variables that are captured in a 13314 // target region should not be captured outside the scope of the region. 13315 if (RSI->CapRegionKind == CR_OpenMP) { 13316 auto isTargetCap = isOpenMPTargetCapturedDecl(Var, OpenMPLevel); 13317 // When we detect target captures we are looking from inside the 13318 // target region, therefore we need to propagate the capture from the 13319 // enclosing region. Therefore, the capture is not initially nested. 13320 if (isTargetCap) 13321 FunctionScopesIndex--; 13322 13323 if (isTargetCap || isOpenMPPrivateDecl(Var, OpenMPLevel)) { 13324 Nested = !isTargetCap; 13325 DeclRefType = DeclRefType.getUnqualifiedType(); 13326 CaptureType = Context.getLValueReferenceType(DeclRefType); 13327 break; 13328 } 13329 ++OpenMPLevel; 13330 } 13331 } 13332 } 13333 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 13334 // No capture-default, and this is not an explicit capture 13335 // so cannot capture this variable. 13336 if (BuildAndDiagnose) { 13337 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13338 Diag(Var->getLocation(), diag::note_previous_decl) 13339 << Var->getDeclName(); 13340 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 13341 diag::note_lambda_decl); 13342 // FIXME: If we error out because an outer lambda can not implicitly 13343 // capture a variable that an inner lambda explicitly captures, we 13344 // should have the inner lambda do the explicit capture - because 13345 // it makes for cleaner diagnostics later. This would purely be done 13346 // so that the diagnostic does not misleadingly claim that a variable 13347 // can not be captured by a lambda implicitly even though it is captured 13348 // explicitly. Suggestion: 13349 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 13350 // at the function head 13351 // - cache the StartingDeclContext - this must be a lambda 13352 // - captureInLambda in the innermost lambda the variable. 13353 } 13354 return true; 13355 } 13356 13357 FunctionScopesIndex--; 13358 DC = ParentDC; 13359 Explicit = false; 13360 } while (!VarDC->Equals(DC)); 13361 13362 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 13363 // computing the type of the capture at each step, checking type-specific 13364 // requirements, and adding captures if requested. 13365 // If the variable had already been captured previously, we start capturing 13366 // at the lambda nested within that one. 13367 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 13368 ++I) { 13369 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 13370 13371 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 13372 if (!captureInBlock(BSI, Var, ExprLoc, 13373 BuildAndDiagnose, CaptureType, 13374 DeclRefType, Nested, *this)) 13375 return true; 13376 Nested = true; 13377 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13378 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 13379 BuildAndDiagnose, CaptureType, 13380 DeclRefType, Nested, *this)) 13381 return true; 13382 Nested = true; 13383 } else { 13384 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13385 if (!captureInLambda(LSI, Var, ExprLoc, 13386 BuildAndDiagnose, CaptureType, 13387 DeclRefType, Nested, Kind, EllipsisLoc, 13388 /*IsTopScope*/I == N - 1, *this)) 13389 return true; 13390 Nested = true; 13391 } 13392 } 13393 return false; 13394 } 13395 13396 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 13397 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 13398 QualType CaptureType; 13399 QualType DeclRefType; 13400 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 13401 /*BuildAndDiagnose=*/true, CaptureType, 13402 DeclRefType, nullptr); 13403 } 13404 13405 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 13406 QualType CaptureType; 13407 QualType DeclRefType; 13408 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13409 /*BuildAndDiagnose=*/false, CaptureType, 13410 DeclRefType, nullptr); 13411 } 13412 13413 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 13414 QualType CaptureType; 13415 QualType DeclRefType; 13416 13417 // Determine whether we can capture this variable. 13418 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13419 /*BuildAndDiagnose=*/false, CaptureType, 13420 DeclRefType, nullptr)) 13421 return QualType(); 13422 13423 return DeclRefType; 13424 } 13425 13426 13427 13428 // If either the type of the variable or the initializer is dependent, 13429 // return false. Otherwise, determine whether the variable is a constant 13430 // expression. Use this if you need to know if a variable that might or 13431 // might not be dependent is truly a constant expression. 13432 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 13433 ASTContext &Context) { 13434 13435 if (Var->getType()->isDependentType()) 13436 return false; 13437 const VarDecl *DefVD = nullptr; 13438 Var->getAnyInitializer(DefVD); 13439 if (!DefVD) 13440 return false; 13441 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 13442 Expr *Init = cast<Expr>(Eval->Value); 13443 if (Init->isValueDependent()) 13444 return false; 13445 return IsVariableAConstantExpression(Var, Context); 13446 } 13447 13448 13449 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 13450 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 13451 // an object that satisfies the requirements for appearing in a 13452 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 13453 // is immediately applied." This function handles the lvalue-to-rvalue 13454 // conversion part. 13455 MaybeODRUseExprs.erase(E->IgnoreParens()); 13456 13457 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 13458 // to a variable that is a constant expression, and if so, identify it as 13459 // a reference to a variable that does not involve an odr-use of that 13460 // variable. 13461 if (LambdaScopeInfo *LSI = getCurLambda()) { 13462 Expr *SansParensExpr = E->IgnoreParens(); 13463 VarDecl *Var = nullptr; 13464 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 13465 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 13466 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 13467 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 13468 13469 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 13470 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 13471 } 13472 } 13473 13474 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 13475 Res = CorrectDelayedTyposInExpr(Res); 13476 13477 if (!Res.isUsable()) 13478 return Res; 13479 13480 // If a constant-expression is a reference to a variable where we delay 13481 // deciding whether it is an odr-use, just assume we will apply the 13482 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 13483 // (a non-type template argument), we have special handling anyway. 13484 UpdateMarkingForLValueToRValue(Res.get()); 13485 return Res; 13486 } 13487 13488 void Sema::CleanupVarDeclMarking() { 13489 for (Expr *E : MaybeODRUseExprs) { 13490 VarDecl *Var; 13491 SourceLocation Loc; 13492 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13493 Var = cast<VarDecl>(DRE->getDecl()); 13494 Loc = DRE->getLocation(); 13495 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13496 Var = cast<VarDecl>(ME->getMemberDecl()); 13497 Loc = ME->getMemberLoc(); 13498 } else { 13499 llvm_unreachable("Unexpected expression"); 13500 } 13501 13502 MarkVarDeclODRUsed(Var, Loc, *this, 13503 /*MaxFunctionScopeIndex Pointer*/ nullptr); 13504 } 13505 13506 MaybeODRUseExprs.clear(); 13507 } 13508 13509 13510 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 13511 VarDecl *Var, Expr *E) { 13512 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 13513 "Invalid Expr argument to DoMarkVarDeclReferenced"); 13514 Var->setReferenced(); 13515 13516 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 13517 bool MarkODRUsed = true; 13518 13519 // If the context is not potentially evaluated, this is not an odr-use and 13520 // does not trigger instantiation. 13521 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 13522 if (SemaRef.isUnevaluatedContext()) 13523 return; 13524 13525 // If we don't yet know whether this context is going to end up being an 13526 // evaluated context, and we're referencing a variable from an enclosing 13527 // scope, add a potential capture. 13528 // 13529 // FIXME: Is this necessary? These contexts are only used for default 13530 // arguments, where local variables can't be used. 13531 const bool RefersToEnclosingScope = 13532 (SemaRef.CurContext != Var->getDeclContext() && 13533 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 13534 if (RefersToEnclosingScope) { 13535 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 13536 // If a variable could potentially be odr-used, defer marking it so 13537 // until we finish analyzing the full expression for any 13538 // lvalue-to-rvalue 13539 // or discarded value conversions that would obviate odr-use. 13540 // Add it to the list of potential captures that will be analyzed 13541 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 13542 // unless the variable is a reference that was initialized by a constant 13543 // expression (this will never need to be captured or odr-used). 13544 assert(E && "Capture variable should be used in an expression."); 13545 if (!Var->getType()->isReferenceType() || 13546 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 13547 LSI->addPotentialCapture(E->IgnoreParens()); 13548 } 13549 } 13550 13551 if (!isTemplateInstantiation(TSK)) 13552 return; 13553 13554 // Instantiate, but do not mark as odr-used, variable templates. 13555 MarkODRUsed = false; 13556 } 13557 13558 VarTemplateSpecializationDecl *VarSpec = 13559 dyn_cast<VarTemplateSpecializationDecl>(Var); 13560 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 13561 "Can't instantiate a partial template specialization."); 13562 13563 // Perform implicit instantiation of static data members, static data member 13564 // templates of class templates, and variable template specializations. Delay 13565 // instantiations of variable templates, except for those that could be used 13566 // in a constant expression. 13567 if (isTemplateInstantiation(TSK)) { 13568 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 13569 13570 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 13571 if (Var->getPointOfInstantiation().isInvalid()) { 13572 // This is a modification of an existing AST node. Notify listeners. 13573 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 13574 L->StaticDataMemberInstantiated(Var); 13575 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 13576 // Don't bother trying to instantiate it again, unless we might need 13577 // its initializer before we get to the end of the TU. 13578 TryInstantiating = false; 13579 } 13580 13581 if (Var->getPointOfInstantiation().isInvalid()) 13582 Var->setTemplateSpecializationKind(TSK, Loc); 13583 13584 if (TryInstantiating) { 13585 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 13586 bool InstantiationDependent = false; 13587 bool IsNonDependent = 13588 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 13589 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 13590 : true; 13591 13592 // Do not instantiate specializations that are still type-dependent. 13593 if (IsNonDependent) { 13594 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 13595 // Do not defer instantiations of variables which could be used in a 13596 // constant expression. 13597 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 13598 } else { 13599 SemaRef.PendingInstantiations 13600 .push_back(std::make_pair(Var, PointOfInstantiation)); 13601 } 13602 } 13603 } 13604 } 13605 13606 if(!MarkODRUsed) return; 13607 13608 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 13609 // the requirements for appearing in a constant expression (5.19) and, if 13610 // it is an object, the lvalue-to-rvalue conversion (4.1) 13611 // is immediately applied." We check the first part here, and 13612 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 13613 // Note that we use the C++11 definition everywhere because nothing in 13614 // C++03 depends on whether we get the C++03 version correct. The second 13615 // part does not apply to references, since they are not objects. 13616 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 13617 // A reference initialized by a constant expression can never be 13618 // odr-used, so simply ignore it. 13619 if (!Var->getType()->isReferenceType()) 13620 SemaRef.MaybeODRUseExprs.insert(E); 13621 } else 13622 MarkVarDeclODRUsed(Var, Loc, SemaRef, 13623 /*MaxFunctionScopeIndex ptr*/ nullptr); 13624 } 13625 13626 /// \brief Mark a variable referenced, and check whether it is odr-used 13627 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 13628 /// used directly for normal expressions referring to VarDecl. 13629 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 13630 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 13631 } 13632 13633 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 13634 Decl *D, Expr *E, bool OdrUse) { 13635 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 13636 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 13637 return; 13638 } 13639 13640 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse); 13641 13642 // If this is a call to a method via a cast, also mark the method in the 13643 // derived class used in case codegen can devirtualize the call. 13644 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 13645 if (!ME) 13646 return; 13647 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 13648 if (!MD) 13649 return; 13650 // Only attempt to devirtualize if this is truly a virtual call. 13651 bool IsVirtualCall = MD->isVirtual() && 13652 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 13653 if (!IsVirtualCall) 13654 return; 13655 const Expr *Base = ME->getBase(); 13656 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 13657 if (!MostDerivedClassDecl) 13658 return; 13659 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 13660 if (!DM || DM->isPure()) 13661 return; 13662 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse); 13663 } 13664 13665 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 13666 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 13667 // TODO: update this with DR# once a defect report is filed. 13668 // C++11 defect. The address of a pure member should not be an ODR use, even 13669 // if it's a qualified reference. 13670 bool OdrUse = true; 13671 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 13672 if (Method->isVirtual()) 13673 OdrUse = false; 13674 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 13675 } 13676 13677 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 13678 void Sema::MarkMemberReferenced(MemberExpr *E) { 13679 // C++11 [basic.def.odr]p2: 13680 // A non-overloaded function whose name appears as a potentially-evaluated 13681 // expression or a member of a set of candidate functions, if selected by 13682 // overload resolution when referred to from a potentially-evaluated 13683 // expression, is odr-used, unless it is a pure virtual function and its 13684 // name is not explicitly qualified. 13685 bool OdrUse = true; 13686 if (E->performsVirtualDispatch(getLangOpts())) { 13687 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 13688 if (Method->isPure()) 13689 OdrUse = false; 13690 } 13691 SourceLocation Loc = E->getMemberLoc().isValid() ? 13692 E->getMemberLoc() : E->getLocStart(); 13693 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse); 13694 } 13695 13696 /// \brief Perform marking for a reference to an arbitrary declaration. It 13697 /// marks the declaration referenced, and performs odr-use checking for 13698 /// functions and variables. This method should not be used when building a 13699 /// normal expression which refers to a variable. 13700 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) { 13701 if (OdrUse) { 13702 if (auto *VD = dyn_cast<VarDecl>(D)) { 13703 MarkVariableReferenced(Loc, VD); 13704 return; 13705 } 13706 } 13707 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 13708 MarkFunctionReferenced(Loc, FD, OdrUse); 13709 return; 13710 } 13711 D->setReferenced(); 13712 } 13713 13714 namespace { 13715 // Mark all of the declarations referenced 13716 // FIXME: Not fully implemented yet! We need to have a better understanding 13717 // of when we're entering 13718 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 13719 Sema &S; 13720 SourceLocation Loc; 13721 13722 public: 13723 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 13724 13725 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 13726 13727 bool TraverseTemplateArgument(const TemplateArgument &Arg); 13728 bool TraverseRecordType(RecordType *T); 13729 }; 13730 } 13731 13732 bool MarkReferencedDecls::TraverseTemplateArgument( 13733 const TemplateArgument &Arg) { 13734 if (Arg.getKind() == TemplateArgument::Declaration) { 13735 if (Decl *D = Arg.getAsDecl()) 13736 S.MarkAnyDeclReferenced(Loc, D, true); 13737 } 13738 13739 return Inherited::TraverseTemplateArgument(Arg); 13740 } 13741 13742 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 13743 if (ClassTemplateSpecializationDecl *Spec 13744 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 13745 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 13746 return TraverseTemplateArguments(Args.data(), Args.size()); 13747 } 13748 13749 return true; 13750 } 13751 13752 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 13753 MarkReferencedDecls Marker(*this, Loc); 13754 Marker.TraverseType(Context.getCanonicalType(T)); 13755 } 13756 13757 namespace { 13758 /// \brief Helper class that marks all of the declarations referenced by 13759 /// potentially-evaluated subexpressions as "referenced". 13760 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 13761 Sema &S; 13762 bool SkipLocalVariables; 13763 13764 public: 13765 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 13766 13767 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 13768 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 13769 13770 void VisitDeclRefExpr(DeclRefExpr *E) { 13771 // If we were asked not to visit local variables, don't. 13772 if (SkipLocalVariables) { 13773 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 13774 if (VD->hasLocalStorage()) 13775 return; 13776 } 13777 13778 S.MarkDeclRefReferenced(E); 13779 } 13780 13781 void VisitMemberExpr(MemberExpr *E) { 13782 S.MarkMemberReferenced(E); 13783 Inherited::VisitMemberExpr(E); 13784 } 13785 13786 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 13787 S.MarkFunctionReferenced(E->getLocStart(), 13788 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 13789 Visit(E->getSubExpr()); 13790 } 13791 13792 void VisitCXXNewExpr(CXXNewExpr *E) { 13793 if (E->getOperatorNew()) 13794 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 13795 if (E->getOperatorDelete()) 13796 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 13797 Inherited::VisitCXXNewExpr(E); 13798 } 13799 13800 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 13801 if (E->getOperatorDelete()) 13802 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 13803 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 13804 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 13805 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 13806 S.MarkFunctionReferenced(E->getLocStart(), 13807 S.LookupDestructor(Record)); 13808 } 13809 13810 Inherited::VisitCXXDeleteExpr(E); 13811 } 13812 13813 void VisitCXXConstructExpr(CXXConstructExpr *E) { 13814 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 13815 Inherited::VisitCXXConstructExpr(E); 13816 } 13817 13818 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 13819 Visit(E->getExpr()); 13820 } 13821 13822 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 13823 Inherited::VisitImplicitCastExpr(E); 13824 13825 if (E->getCastKind() == CK_LValueToRValue) 13826 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 13827 } 13828 }; 13829 } 13830 13831 /// \brief Mark any declarations that appear within this expression or any 13832 /// potentially-evaluated subexpressions as "referenced". 13833 /// 13834 /// \param SkipLocalVariables If true, don't mark local variables as 13835 /// 'referenced'. 13836 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 13837 bool SkipLocalVariables) { 13838 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 13839 } 13840 13841 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 13842 /// of the program being compiled. 13843 /// 13844 /// This routine emits the given diagnostic when the code currently being 13845 /// type-checked is "potentially evaluated", meaning that there is a 13846 /// possibility that the code will actually be executable. Code in sizeof() 13847 /// expressions, code used only during overload resolution, etc., are not 13848 /// potentially evaluated. This routine will suppress such diagnostics or, 13849 /// in the absolutely nutty case of potentially potentially evaluated 13850 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 13851 /// later. 13852 /// 13853 /// This routine should be used for all diagnostics that describe the run-time 13854 /// behavior of a program, such as passing a non-POD value through an ellipsis. 13855 /// Failure to do so will likely result in spurious diagnostics or failures 13856 /// during overload resolution or within sizeof/alignof/typeof/typeid. 13857 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 13858 const PartialDiagnostic &PD) { 13859 switch (ExprEvalContexts.back().Context) { 13860 case Unevaluated: 13861 case UnevaluatedAbstract: 13862 // The argument will never be evaluated, so don't complain. 13863 break; 13864 13865 case ConstantEvaluated: 13866 // Relevant diagnostics should be produced by constant evaluation. 13867 break; 13868 13869 case PotentiallyEvaluated: 13870 case PotentiallyEvaluatedIfUsed: 13871 if (Statement && getCurFunctionOrMethodDecl()) { 13872 FunctionScopes.back()->PossiblyUnreachableDiags. 13873 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 13874 } 13875 else 13876 Diag(Loc, PD); 13877 13878 return true; 13879 } 13880 13881 return false; 13882 } 13883 13884 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 13885 CallExpr *CE, FunctionDecl *FD) { 13886 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 13887 return false; 13888 13889 // If we're inside a decltype's expression, don't check for a valid return 13890 // type or construct temporaries until we know whether this is the last call. 13891 if (ExprEvalContexts.back().IsDecltype) { 13892 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 13893 return false; 13894 } 13895 13896 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 13897 FunctionDecl *FD; 13898 CallExpr *CE; 13899 13900 public: 13901 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 13902 : FD(FD), CE(CE) { } 13903 13904 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 13905 if (!FD) { 13906 S.Diag(Loc, diag::err_call_incomplete_return) 13907 << T << CE->getSourceRange(); 13908 return; 13909 } 13910 13911 S.Diag(Loc, diag::err_call_function_incomplete_return) 13912 << CE->getSourceRange() << FD->getDeclName() << T; 13913 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 13914 << FD->getDeclName(); 13915 } 13916 } Diagnoser(FD, CE); 13917 13918 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 13919 return true; 13920 13921 return false; 13922 } 13923 13924 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 13925 // will prevent this condition from triggering, which is what we want. 13926 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 13927 SourceLocation Loc; 13928 13929 unsigned diagnostic = diag::warn_condition_is_assignment; 13930 bool IsOrAssign = false; 13931 13932 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 13933 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 13934 return; 13935 13936 IsOrAssign = Op->getOpcode() == BO_OrAssign; 13937 13938 // Greylist some idioms by putting them into a warning subcategory. 13939 if (ObjCMessageExpr *ME 13940 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 13941 Selector Sel = ME->getSelector(); 13942 13943 // self = [<foo> init...] 13944 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 13945 diagnostic = diag::warn_condition_is_idiomatic_assignment; 13946 13947 // <foo> = [<bar> nextObject] 13948 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 13949 diagnostic = diag::warn_condition_is_idiomatic_assignment; 13950 } 13951 13952 Loc = Op->getOperatorLoc(); 13953 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 13954 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 13955 return; 13956 13957 IsOrAssign = Op->getOperator() == OO_PipeEqual; 13958 Loc = Op->getOperatorLoc(); 13959 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 13960 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 13961 else { 13962 // Not an assignment. 13963 return; 13964 } 13965 13966 Diag(Loc, diagnostic) << E->getSourceRange(); 13967 13968 SourceLocation Open = E->getLocStart(); 13969 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 13970 Diag(Loc, diag::note_condition_assign_silence) 13971 << FixItHint::CreateInsertion(Open, "(") 13972 << FixItHint::CreateInsertion(Close, ")"); 13973 13974 if (IsOrAssign) 13975 Diag(Loc, diag::note_condition_or_assign_to_comparison) 13976 << FixItHint::CreateReplacement(Loc, "!="); 13977 else 13978 Diag(Loc, diag::note_condition_assign_to_comparison) 13979 << FixItHint::CreateReplacement(Loc, "=="); 13980 } 13981 13982 /// \brief Redundant parentheses over an equality comparison can indicate 13983 /// that the user intended an assignment used as condition. 13984 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 13985 // Don't warn if the parens came from a macro. 13986 SourceLocation parenLoc = ParenE->getLocStart(); 13987 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 13988 return; 13989 // Don't warn for dependent expressions. 13990 if (ParenE->isTypeDependent()) 13991 return; 13992 13993 Expr *E = ParenE->IgnoreParens(); 13994 13995 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 13996 if (opE->getOpcode() == BO_EQ && 13997 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 13998 == Expr::MLV_Valid) { 13999 SourceLocation Loc = opE->getOperatorLoc(); 14000 14001 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 14002 SourceRange ParenERange = ParenE->getSourceRange(); 14003 Diag(Loc, diag::note_equality_comparison_silence) 14004 << FixItHint::CreateRemoval(ParenERange.getBegin()) 14005 << FixItHint::CreateRemoval(ParenERange.getEnd()); 14006 Diag(Loc, diag::note_equality_comparison_to_assign) 14007 << FixItHint::CreateReplacement(Loc, "="); 14008 } 14009 } 14010 14011 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 14012 DiagnoseAssignmentAsCondition(E); 14013 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 14014 DiagnoseEqualityWithExtraParens(parenE); 14015 14016 ExprResult result = CheckPlaceholderExpr(E); 14017 if (result.isInvalid()) return ExprError(); 14018 E = result.get(); 14019 14020 if (!E->isTypeDependent()) { 14021 if (getLangOpts().CPlusPlus) 14022 return CheckCXXBooleanCondition(E); // C++ 6.4p4 14023 14024 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 14025 if (ERes.isInvalid()) 14026 return ExprError(); 14027 E = ERes.get(); 14028 14029 QualType T = E->getType(); 14030 if (!T->isScalarType()) { // C99 6.8.4.1p1 14031 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 14032 << T << E->getSourceRange(); 14033 return ExprError(); 14034 } 14035 CheckBoolLikeConversion(E, Loc); 14036 } 14037 14038 return E; 14039 } 14040 14041 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 14042 Expr *SubExpr) { 14043 if (!SubExpr) 14044 return ExprError(); 14045 14046 return CheckBooleanCondition(SubExpr, Loc); 14047 } 14048 14049 namespace { 14050 /// A visitor for rebuilding a call to an __unknown_any expression 14051 /// to have an appropriate type. 14052 struct RebuildUnknownAnyFunction 14053 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 14054 14055 Sema &S; 14056 14057 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 14058 14059 ExprResult VisitStmt(Stmt *S) { 14060 llvm_unreachable("unexpected statement!"); 14061 } 14062 14063 ExprResult VisitExpr(Expr *E) { 14064 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 14065 << E->getSourceRange(); 14066 return ExprError(); 14067 } 14068 14069 /// Rebuild an expression which simply semantically wraps another 14070 /// expression which it shares the type and value kind of. 14071 template <class T> ExprResult rebuildSugarExpr(T *E) { 14072 ExprResult SubResult = Visit(E->getSubExpr()); 14073 if (SubResult.isInvalid()) return ExprError(); 14074 14075 Expr *SubExpr = SubResult.get(); 14076 E->setSubExpr(SubExpr); 14077 E->setType(SubExpr->getType()); 14078 E->setValueKind(SubExpr->getValueKind()); 14079 assert(E->getObjectKind() == OK_Ordinary); 14080 return E; 14081 } 14082 14083 ExprResult VisitParenExpr(ParenExpr *E) { 14084 return rebuildSugarExpr(E); 14085 } 14086 14087 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14088 return rebuildSugarExpr(E); 14089 } 14090 14091 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14092 ExprResult SubResult = Visit(E->getSubExpr()); 14093 if (SubResult.isInvalid()) return ExprError(); 14094 14095 Expr *SubExpr = SubResult.get(); 14096 E->setSubExpr(SubExpr); 14097 E->setType(S.Context.getPointerType(SubExpr->getType())); 14098 assert(E->getValueKind() == VK_RValue); 14099 assert(E->getObjectKind() == OK_Ordinary); 14100 return E; 14101 } 14102 14103 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 14104 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 14105 14106 E->setType(VD->getType()); 14107 14108 assert(E->getValueKind() == VK_RValue); 14109 if (S.getLangOpts().CPlusPlus && 14110 !(isa<CXXMethodDecl>(VD) && 14111 cast<CXXMethodDecl>(VD)->isInstance())) 14112 E->setValueKind(VK_LValue); 14113 14114 return E; 14115 } 14116 14117 ExprResult VisitMemberExpr(MemberExpr *E) { 14118 return resolveDecl(E, E->getMemberDecl()); 14119 } 14120 14121 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14122 return resolveDecl(E, E->getDecl()); 14123 } 14124 }; 14125 } 14126 14127 /// Given a function expression of unknown-any type, try to rebuild it 14128 /// to have a function type. 14129 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 14130 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 14131 if (Result.isInvalid()) return ExprError(); 14132 return S.DefaultFunctionArrayConversion(Result.get()); 14133 } 14134 14135 namespace { 14136 /// A visitor for rebuilding an expression of type __unknown_anytype 14137 /// into one which resolves the type directly on the referring 14138 /// expression. Strict preservation of the original source 14139 /// structure is not a goal. 14140 struct RebuildUnknownAnyExpr 14141 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 14142 14143 Sema &S; 14144 14145 /// The current destination type. 14146 QualType DestType; 14147 14148 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 14149 : S(S), DestType(CastType) {} 14150 14151 ExprResult VisitStmt(Stmt *S) { 14152 llvm_unreachable("unexpected statement!"); 14153 } 14154 14155 ExprResult VisitExpr(Expr *E) { 14156 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14157 << E->getSourceRange(); 14158 return ExprError(); 14159 } 14160 14161 ExprResult VisitCallExpr(CallExpr *E); 14162 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 14163 14164 /// Rebuild an expression which simply semantically wraps another 14165 /// expression which it shares the type and value kind of. 14166 template <class T> ExprResult rebuildSugarExpr(T *E) { 14167 ExprResult SubResult = Visit(E->getSubExpr()); 14168 if (SubResult.isInvalid()) return ExprError(); 14169 Expr *SubExpr = SubResult.get(); 14170 E->setSubExpr(SubExpr); 14171 E->setType(SubExpr->getType()); 14172 E->setValueKind(SubExpr->getValueKind()); 14173 assert(E->getObjectKind() == OK_Ordinary); 14174 return E; 14175 } 14176 14177 ExprResult VisitParenExpr(ParenExpr *E) { 14178 return rebuildSugarExpr(E); 14179 } 14180 14181 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14182 return rebuildSugarExpr(E); 14183 } 14184 14185 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14186 const PointerType *Ptr = DestType->getAs<PointerType>(); 14187 if (!Ptr) { 14188 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 14189 << E->getSourceRange(); 14190 return ExprError(); 14191 } 14192 assert(E->getValueKind() == VK_RValue); 14193 assert(E->getObjectKind() == OK_Ordinary); 14194 E->setType(DestType); 14195 14196 // Build the sub-expression as if it were an object of the pointee type. 14197 DestType = Ptr->getPointeeType(); 14198 ExprResult SubResult = Visit(E->getSubExpr()); 14199 if (SubResult.isInvalid()) return ExprError(); 14200 E->setSubExpr(SubResult.get()); 14201 return E; 14202 } 14203 14204 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 14205 14206 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 14207 14208 ExprResult VisitMemberExpr(MemberExpr *E) { 14209 return resolveDecl(E, E->getMemberDecl()); 14210 } 14211 14212 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14213 return resolveDecl(E, E->getDecl()); 14214 } 14215 }; 14216 } 14217 14218 /// Rebuilds a call expression which yielded __unknown_anytype. 14219 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 14220 Expr *CalleeExpr = E->getCallee(); 14221 14222 enum FnKind { 14223 FK_MemberFunction, 14224 FK_FunctionPointer, 14225 FK_BlockPointer 14226 }; 14227 14228 FnKind Kind; 14229 QualType CalleeType = CalleeExpr->getType(); 14230 if (CalleeType == S.Context.BoundMemberTy) { 14231 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 14232 Kind = FK_MemberFunction; 14233 CalleeType = Expr::findBoundMemberType(CalleeExpr); 14234 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 14235 CalleeType = Ptr->getPointeeType(); 14236 Kind = FK_FunctionPointer; 14237 } else { 14238 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 14239 Kind = FK_BlockPointer; 14240 } 14241 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 14242 14243 // Verify that this is a legal result type of a function. 14244 if (DestType->isArrayType() || DestType->isFunctionType()) { 14245 unsigned diagID = diag::err_func_returning_array_function; 14246 if (Kind == FK_BlockPointer) 14247 diagID = diag::err_block_returning_array_function; 14248 14249 S.Diag(E->getExprLoc(), diagID) 14250 << DestType->isFunctionType() << DestType; 14251 return ExprError(); 14252 } 14253 14254 // Otherwise, go ahead and set DestType as the call's result. 14255 E->setType(DestType.getNonLValueExprType(S.Context)); 14256 E->setValueKind(Expr::getValueKindForType(DestType)); 14257 assert(E->getObjectKind() == OK_Ordinary); 14258 14259 // Rebuild the function type, replacing the result type with DestType. 14260 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 14261 if (Proto) { 14262 // __unknown_anytype(...) is a special case used by the debugger when 14263 // it has no idea what a function's signature is. 14264 // 14265 // We want to build this call essentially under the K&R 14266 // unprototyped rules, but making a FunctionNoProtoType in C++ 14267 // would foul up all sorts of assumptions. However, we cannot 14268 // simply pass all arguments as variadic arguments, nor can we 14269 // portably just call the function under a non-variadic type; see 14270 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 14271 // However, it turns out that in practice it is generally safe to 14272 // call a function declared as "A foo(B,C,D);" under the prototype 14273 // "A foo(B,C,D,...);". The only known exception is with the 14274 // Windows ABI, where any variadic function is implicitly cdecl 14275 // regardless of its normal CC. Therefore we change the parameter 14276 // types to match the types of the arguments. 14277 // 14278 // This is a hack, but it is far superior to moving the 14279 // corresponding target-specific code from IR-gen to Sema/AST. 14280 14281 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 14282 SmallVector<QualType, 8> ArgTypes; 14283 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 14284 ArgTypes.reserve(E->getNumArgs()); 14285 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 14286 Expr *Arg = E->getArg(i); 14287 QualType ArgType = Arg->getType(); 14288 if (E->isLValue()) { 14289 ArgType = S.Context.getLValueReferenceType(ArgType); 14290 } else if (E->isXValue()) { 14291 ArgType = S.Context.getRValueReferenceType(ArgType); 14292 } 14293 ArgTypes.push_back(ArgType); 14294 } 14295 ParamTypes = ArgTypes; 14296 } 14297 DestType = S.Context.getFunctionType(DestType, ParamTypes, 14298 Proto->getExtProtoInfo()); 14299 } else { 14300 DestType = S.Context.getFunctionNoProtoType(DestType, 14301 FnType->getExtInfo()); 14302 } 14303 14304 // Rebuild the appropriate pointer-to-function type. 14305 switch (Kind) { 14306 case FK_MemberFunction: 14307 // Nothing to do. 14308 break; 14309 14310 case FK_FunctionPointer: 14311 DestType = S.Context.getPointerType(DestType); 14312 break; 14313 14314 case FK_BlockPointer: 14315 DestType = S.Context.getBlockPointerType(DestType); 14316 break; 14317 } 14318 14319 // Finally, we can recurse. 14320 ExprResult CalleeResult = Visit(CalleeExpr); 14321 if (!CalleeResult.isUsable()) return ExprError(); 14322 E->setCallee(CalleeResult.get()); 14323 14324 // Bind a temporary if necessary. 14325 return S.MaybeBindToTemporary(E); 14326 } 14327 14328 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 14329 // Verify that this is a legal result type of a call. 14330 if (DestType->isArrayType() || DestType->isFunctionType()) { 14331 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 14332 << DestType->isFunctionType() << DestType; 14333 return ExprError(); 14334 } 14335 14336 // Rewrite the method result type if available. 14337 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 14338 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 14339 Method->setReturnType(DestType); 14340 } 14341 14342 // Change the type of the message. 14343 E->setType(DestType.getNonReferenceType()); 14344 E->setValueKind(Expr::getValueKindForType(DestType)); 14345 14346 return S.MaybeBindToTemporary(E); 14347 } 14348 14349 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 14350 // The only case we should ever see here is a function-to-pointer decay. 14351 if (E->getCastKind() == CK_FunctionToPointerDecay) { 14352 assert(E->getValueKind() == VK_RValue); 14353 assert(E->getObjectKind() == OK_Ordinary); 14354 14355 E->setType(DestType); 14356 14357 // Rebuild the sub-expression as the pointee (function) type. 14358 DestType = DestType->castAs<PointerType>()->getPointeeType(); 14359 14360 ExprResult Result = Visit(E->getSubExpr()); 14361 if (!Result.isUsable()) return ExprError(); 14362 14363 E->setSubExpr(Result.get()); 14364 return E; 14365 } else if (E->getCastKind() == CK_LValueToRValue) { 14366 assert(E->getValueKind() == VK_RValue); 14367 assert(E->getObjectKind() == OK_Ordinary); 14368 14369 assert(isa<BlockPointerType>(E->getType())); 14370 14371 E->setType(DestType); 14372 14373 // The sub-expression has to be a lvalue reference, so rebuild it as such. 14374 DestType = S.Context.getLValueReferenceType(DestType); 14375 14376 ExprResult Result = Visit(E->getSubExpr()); 14377 if (!Result.isUsable()) return ExprError(); 14378 14379 E->setSubExpr(Result.get()); 14380 return E; 14381 } else { 14382 llvm_unreachable("Unhandled cast type!"); 14383 } 14384 } 14385 14386 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 14387 ExprValueKind ValueKind = VK_LValue; 14388 QualType Type = DestType; 14389 14390 // We know how to make this work for certain kinds of decls: 14391 14392 // - functions 14393 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 14394 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 14395 DestType = Ptr->getPointeeType(); 14396 ExprResult Result = resolveDecl(E, VD); 14397 if (Result.isInvalid()) return ExprError(); 14398 return S.ImpCastExprToType(Result.get(), Type, 14399 CK_FunctionToPointerDecay, VK_RValue); 14400 } 14401 14402 if (!Type->isFunctionType()) { 14403 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 14404 << VD << E->getSourceRange(); 14405 return ExprError(); 14406 } 14407 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 14408 // We must match the FunctionDecl's type to the hack introduced in 14409 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 14410 // type. See the lengthy commentary in that routine. 14411 QualType FDT = FD->getType(); 14412 const FunctionType *FnType = FDT->castAs<FunctionType>(); 14413 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 14414 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 14415 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 14416 SourceLocation Loc = FD->getLocation(); 14417 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 14418 FD->getDeclContext(), 14419 Loc, Loc, FD->getNameInfo().getName(), 14420 DestType, FD->getTypeSourceInfo(), 14421 SC_None, false/*isInlineSpecified*/, 14422 FD->hasPrototype(), 14423 false/*isConstexprSpecified*/); 14424 14425 if (FD->getQualifier()) 14426 NewFD->setQualifierInfo(FD->getQualifierLoc()); 14427 14428 SmallVector<ParmVarDecl*, 16> Params; 14429 for (const auto &AI : FT->param_types()) { 14430 ParmVarDecl *Param = 14431 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 14432 Param->setScopeInfo(0, Params.size()); 14433 Params.push_back(Param); 14434 } 14435 NewFD->setParams(Params); 14436 DRE->setDecl(NewFD); 14437 VD = DRE->getDecl(); 14438 } 14439 } 14440 14441 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 14442 if (MD->isInstance()) { 14443 ValueKind = VK_RValue; 14444 Type = S.Context.BoundMemberTy; 14445 } 14446 14447 // Function references aren't l-values in C. 14448 if (!S.getLangOpts().CPlusPlus) 14449 ValueKind = VK_RValue; 14450 14451 // - variables 14452 } else if (isa<VarDecl>(VD)) { 14453 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 14454 Type = RefTy->getPointeeType(); 14455 } else if (Type->isFunctionType()) { 14456 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 14457 << VD << E->getSourceRange(); 14458 return ExprError(); 14459 } 14460 14461 // - nothing else 14462 } else { 14463 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 14464 << VD << E->getSourceRange(); 14465 return ExprError(); 14466 } 14467 14468 // Modifying the declaration like this is friendly to IR-gen but 14469 // also really dangerous. 14470 VD->setType(DestType); 14471 E->setType(Type); 14472 E->setValueKind(ValueKind); 14473 return E; 14474 } 14475 14476 /// Check a cast of an unknown-any type. We intentionally only 14477 /// trigger this for C-style casts. 14478 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 14479 Expr *CastExpr, CastKind &CastKind, 14480 ExprValueKind &VK, CXXCastPath &Path) { 14481 // Rewrite the casted expression from scratch. 14482 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 14483 if (!result.isUsable()) return ExprError(); 14484 14485 CastExpr = result.get(); 14486 VK = CastExpr->getValueKind(); 14487 CastKind = CK_NoOp; 14488 14489 return CastExpr; 14490 } 14491 14492 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 14493 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 14494 } 14495 14496 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 14497 Expr *arg, QualType ¶mType) { 14498 // If the syntactic form of the argument is not an explicit cast of 14499 // any sort, just do default argument promotion. 14500 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 14501 if (!castArg) { 14502 ExprResult result = DefaultArgumentPromotion(arg); 14503 if (result.isInvalid()) return ExprError(); 14504 paramType = result.get()->getType(); 14505 return result; 14506 } 14507 14508 // Otherwise, use the type that was written in the explicit cast. 14509 assert(!arg->hasPlaceholderType()); 14510 paramType = castArg->getTypeAsWritten(); 14511 14512 // Copy-initialize a parameter of that type. 14513 InitializedEntity entity = 14514 InitializedEntity::InitializeParameter(Context, paramType, 14515 /*consumed*/ false); 14516 return PerformCopyInitialization(entity, callLoc, arg); 14517 } 14518 14519 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 14520 Expr *orig = E; 14521 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 14522 while (true) { 14523 E = E->IgnoreParenImpCasts(); 14524 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 14525 E = call->getCallee(); 14526 diagID = diag::err_uncasted_call_of_unknown_any; 14527 } else { 14528 break; 14529 } 14530 } 14531 14532 SourceLocation loc; 14533 NamedDecl *d; 14534 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 14535 loc = ref->getLocation(); 14536 d = ref->getDecl(); 14537 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 14538 loc = mem->getMemberLoc(); 14539 d = mem->getMemberDecl(); 14540 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 14541 diagID = diag::err_uncasted_call_of_unknown_any; 14542 loc = msg->getSelectorStartLoc(); 14543 d = msg->getMethodDecl(); 14544 if (!d) { 14545 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 14546 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 14547 << orig->getSourceRange(); 14548 return ExprError(); 14549 } 14550 } else { 14551 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14552 << E->getSourceRange(); 14553 return ExprError(); 14554 } 14555 14556 S.Diag(loc, diagID) << d << orig->getSourceRange(); 14557 14558 // Never recoverable. 14559 return ExprError(); 14560 } 14561 14562 /// Check for operands with placeholder types and complain if found. 14563 /// Returns true if there was an error and no recovery was possible. 14564 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 14565 if (!getLangOpts().CPlusPlus) { 14566 // C cannot handle TypoExpr nodes on either side of a binop because it 14567 // doesn't handle dependent types properly, so make sure any TypoExprs have 14568 // been dealt with before checking the operands. 14569 ExprResult Result = CorrectDelayedTyposInExpr(E); 14570 if (!Result.isUsable()) return ExprError(); 14571 E = Result.get(); 14572 } 14573 14574 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 14575 if (!placeholderType) return E; 14576 14577 switch (placeholderType->getKind()) { 14578 14579 // Overloaded expressions. 14580 case BuiltinType::Overload: { 14581 // Try to resolve a single function template specialization. 14582 // This is obligatory. 14583 ExprResult result = E; 14584 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 14585 return result; 14586 14587 // If that failed, try to recover with a call. 14588 } else { 14589 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 14590 /*complain*/ true); 14591 return result; 14592 } 14593 } 14594 14595 // Bound member functions. 14596 case BuiltinType::BoundMember: { 14597 ExprResult result = E; 14598 const Expr *BME = E->IgnoreParens(); 14599 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 14600 // Try to give a nicer diagnostic if it is a bound member that we recognize. 14601 if (isa<CXXPseudoDestructorExpr>(BME)) { 14602 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 14603 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 14604 if (ME->getMemberNameInfo().getName().getNameKind() == 14605 DeclarationName::CXXDestructorName) 14606 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 14607 } 14608 tryToRecoverWithCall(result, PD, 14609 /*complain*/ true); 14610 return result; 14611 } 14612 14613 // ARC unbridged casts. 14614 case BuiltinType::ARCUnbridgedCast: { 14615 Expr *realCast = stripARCUnbridgedCast(E); 14616 diagnoseARCUnbridgedCast(realCast); 14617 return realCast; 14618 } 14619 14620 // Expressions of unknown type. 14621 case BuiltinType::UnknownAny: 14622 return diagnoseUnknownAnyExpr(*this, E); 14623 14624 // Pseudo-objects. 14625 case BuiltinType::PseudoObject: 14626 return checkPseudoObjectRValue(E); 14627 14628 case BuiltinType::BuiltinFn: { 14629 // Accept __noop without parens by implicitly converting it to a call expr. 14630 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 14631 if (DRE) { 14632 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 14633 if (FD->getBuiltinID() == Builtin::BI__noop) { 14634 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 14635 CK_BuiltinFnToFnPtr).get(); 14636 return new (Context) CallExpr(Context, E, None, Context.IntTy, 14637 VK_RValue, SourceLocation()); 14638 } 14639 } 14640 14641 Diag(E->getLocStart(), diag::err_builtin_fn_use); 14642 return ExprError(); 14643 } 14644 14645 // Expressions of unknown type. 14646 case BuiltinType::OMPArraySection: 14647 Diag(E->getLocStart(), diag::err_omp_array_section_use); 14648 return ExprError(); 14649 14650 // Everything else should be impossible. 14651 #define BUILTIN_TYPE(Id, SingletonId) \ 14652 case BuiltinType::Id: 14653 #define PLACEHOLDER_TYPE(Id, SingletonId) 14654 #include "clang/AST/BuiltinTypes.def" 14655 break; 14656 } 14657 14658 llvm_unreachable("invalid placeholder type!"); 14659 } 14660 14661 bool Sema::CheckCaseExpression(Expr *E) { 14662 if (E->isTypeDependent()) 14663 return true; 14664 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 14665 return E->getType()->isIntegralOrEnumerationType(); 14666 return false; 14667 } 14668 14669 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 14670 ExprResult 14671 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 14672 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 14673 "Unknown Objective-C Boolean value!"); 14674 QualType BoolT = Context.ObjCBuiltinBoolTy; 14675 if (!Context.getBOOLDecl()) { 14676 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 14677 Sema::LookupOrdinaryName); 14678 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 14679 NamedDecl *ND = Result.getFoundDecl(); 14680 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 14681 Context.setBOOLDecl(TD); 14682 } 14683 } 14684 if (Context.getBOOLDecl()) 14685 BoolT = Context.getBOOLType(); 14686 return new (Context) 14687 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 14688 } 14689