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 "TreeTransform.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/RecursiveASTVisitor.h" 28 #include "clang/AST/TypeLoc.h" 29 #include "clang/Basic/FixedPoint.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/Overload.h" 42 #include "clang/Sema/ParsedTemplate.h" 43 #include "clang/Sema/Scope.h" 44 #include "clang/Sema/ScopeInfo.h" 45 #include "clang/Sema/SemaFixItUtils.h" 46 #include "clang/Sema/SemaInternal.h" 47 #include "clang/Sema/Template.h" 48 #include "llvm/Support/ConvertUTF.h" 49 using namespace clang; 50 using namespace sema; 51 52 /// Determine whether the use of this declaration is valid, without 53 /// emitting diagnostics. 54 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 55 // See if this is an auto-typed variable whose initializer we are parsing. 56 if (ParsingInitForAutoVars.count(D)) 57 return false; 58 59 // See if this is a deleted function. 60 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 61 if (FD->isDeleted()) 62 return false; 63 64 // If the function has a deduced return type, and we can't deduce it, 65 // then we can't use it either. 66 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 67 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 68 return false; 69 } 70 71 // See if this function is unavailable. 72 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 73 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 74 return false; 75 76 return true; 77 } 78 79 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 80 // Warn if this is used but marked unused. 81 if (const auto *A = D->getAttr<UnusedAttr>()) { 82 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 83 // should diagnose them. 84 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 85 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 86 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 87 if (DC && !DC->hasAttr<UnusedAttr>()) 88 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 89 } 90 } 91 } 92 93 /// Emit a note explaining that this function is deleted. 94 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 95 assert(Decl->isDeleted()); 96 97 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 98 99 if (Method && Method->isDeleted() && Method->isDefaulted()) { 100 // If the method was explicitly defaulted, point at that declaration. 101 if (!Method->isImplicit()) 102 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 103 104 // Try to diagnose why this special member function was implicitly 105 // deleted. This might fail, if that reason no longer applies. 106 CXXSpecialMember CSM = getSpecialMember(Method); 107 if (CSM != CXXInvalid) 108 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 109 110 return; 111 } 112 113 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 114 if (Ctor && Ctor->isInheritingConstructor()) 115 return NoteDeletedInheritingConstructor(Ctor); 116 117 Diag(Decl->getLocation(), diag::note_availability_specified_here) 118 << Decl << true; 119 } 120 121 /// Determine whether a FunctionDecl was ever declared with an 122 /// explicit storage class. 123 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 124 for (auto I : D->redecls()) { 125 if (I->getStorageClass() != SC_None) 126 return true; 127 } 128 return false; 129 } 130 131 /// Check whether we're in an extern inline function and referring to a 132 /// variable or function with internal linkage (C11 6.7.4p3). 133 /// 134 /// This is only a warning because we used to silently accept this code, but 135 /// in many cases it will not behave correctly. This is not enabled in C++ mode 136 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 137 /// and so while there may still be user mistakes, most of the time we can't 138 /// prove that there are errors. 139 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 140 const NamedDecl *D, 141 SourceLocation Loc) { 142 // This is disabled under C++; there are too many ways for this to fire in 143 // contexts where the warning is a false positive, or where it is technically 144 // correct but benign. 145 if (S.getLangOpts().CPlusPlus) 146 return; 147 148 // Check if this is an inlined function or method. 149 FunctionDecl *Current = S.getCurFunctionDecl(); 150 if (!Current) 151 return; 152 if (!Current->isInlined()) 153 return; 154 if (!Current->isExternallyVisible()) 155 return; 156 157 // Check if the decl has internal linkage. 158 if (D->getFormalLinkage() != InternalLinkage) 159 return; 160 161 // Downgrade from ExtWarn to Extension if 162 // (1) the supposedly external inline function is in the main file, 163 // and probably won't be included anywhere else. 164 // (2) the thing we're referencing is a pure function. 165 // (3) the thing we're referencing is another inline function. 166 // This last can give us false negatives, but it's better than warning on 167 // wrappers for simple C library functions. 168 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 169 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 170 if (!DowngradeWarning && UsedFn) 171 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 172 173 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 174 : diag::ext_internal_in_extern_inline) 175 << /*IsVar=*/!UsedFn << D; 176 177 S.MaybeSuggestAddingStaticToDecl(Current); 178 179 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 180 << D; 181 } 182 183 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 184 const FunctionDecl *First = Cur->getFirstDecl(); 185 186 // Suggest "static" on the function, if possible. 187 if (!hasAnyExplicitStorageClass(First)) { 188 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 189 Diag(DeclBegin, diag::note_convert_inline_to_static) 190 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 191 } 192 } 193 194 /// Determine whether the use of this declaration is valid, and 195 /// emit any corresponding diagnostics. 196 /// 197 /// This routine diagnoses various problems with referencing 198 /// declarations that can occur when using a declaration. For example, 199 /// it might warn if a deprecated or unavailable declaration is being 200 /// used, or produce an error (and return true) if a C++0x deleted 201 /// function is being used. 202 /// 203 /// \returns true if there was an error (this declaration cannot be 204 /// referenced), false otherwise. 205 /// 206 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 207 const ObjCInterfaceDecl *UnknownObjCClass, 208 bool ObjCPropertyAccess, 209 bool AvoidPartialAvailabilityChecks, 210 ObjCInterfaceDecl *ClassReceiver) { 211 SourceLocation Loc = Locs.front(); 212 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 213 // If there were any diagnostics suppressed by template argument deduction, 214 // emit them now. 215 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 216 if (Pos != SuppressedDiagnostics.end()) { 217 for (const PartialDiagnosticAt &Suppressed : Pos->second) 218 Diag(Suppressed.first, Suppressed.second); 219 220 // Clear out the list of suppressed diagnostics, so that we don't emit 221 // them again for this specialization. However, we don't obsolete this 222 // entry from the table, because we want to avoid ever emitting these 223 // diagnostics again. 224 Pos->second.clear(); 225 } 226 227 // C++ [basic.start.main]p3: 228 // The function 'main' shall not be used within a program. 229 if (cast<FunctionDecl>(D)->isMain()) 230 Diag(Loc, diag::ext_main_used); 231 } 232 233 // See if this is an auto-typed variable whose initializer we are parsing. 234 if (ParsingInitForAutoVars.count(D)) { 235 if (isa<BindingDecl>(D)) { 236 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 237 << D->getDeclName(); 238 } else { 239 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 240 << D->getDeclName() << cast<VarDecl>(D)->getType(); 241 } 242 return true; 243 } 244 245 // See if this is a deleted function. 246 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 247 if (FD->isDeleted()) { 248 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 249 if (Ctor && Ctor->isInheritingConstructor()) 250 Diag(Loc, diag::err_deleted_inherited_ctor_use) 251 << Ctor->getParent() 252 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 253 else 254 Diag(Loc, diag::err_deleted_function_use); 255 NoteDeletedFunction(FD); 256 return true; 257 } 258 259 // If the function has a deduced return type, and we can't deduce it, 260 // then we can't use it either. 261 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 262 DeduceReturnType(FD, Loc)) 263 return true; 264 265 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 266 return true; 267 } 268 269 auto getReferencedObjCProp = [](const NamedDecl *D) -> 270 const ObjCPropertyDecl * { 271 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 272 return MD->findPropertyDecl(); 273 return nullptr; 274 }; 275 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 276 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 277 return true; 278 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 279 return true; 280 } 281 282 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 283 // Only the variables omp_in and omp_out are allowed in the combiner. 284 // Only the variables omp_priv and omp_orig are allowed in the 285 // initializer-clause. 286 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 287 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 288 isa<VarDecl>(D)) { 289 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 290 << getCurFunction()->HasOMPDeclareReductionCombiner; 291 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 292 return true; 293 } 294 295 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 296 AvoidPartialAvailabilityChecks, ClassReceiver); 297 298 DiagnoseUnusedOfDecl(*this, D, Loc); 299 300 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 301 302 return false; 303 } 304 305 /// Retrieve the message suffix that should be added to a 306 /// diagnostic complaining about the given function being deleted or 307 /// unavailable. 308 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 309 std::string Message; 310 if (FD->getAvailability(&Message)) 311 return ": " + Message; 312 313 return std::string(); 314 } 315 316 /// DiagnoseSentinelCalls - This routine checks whether a call or 317 /// message-send is to a declaration with the sentinel attribute, and 318 /// if so, it checks that the requirements of the sentinel are 319 /// satisfied. 320 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 321 ArrayRef<Expr *> Args) { 322 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 323 if (!attr) 324 return; 325 326 // The number of formal parameters of the declaration. 327 unsigned numFormalParams; 328 329 // The kind of declaration. This is also an index into a %select in 330 // the diagnostic. 331 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 332 333 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 334 numFormalParams = MD->param_size(); 335 calleeType = CT_Method; 336 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 337 numFormalParams = FD->param_size(); 338 calleeType = CT_Function; 339 } else if (isa<VarDecl>(D)) { 340 QualType type = cast<ValueDecl>(D)->getType(); 341 const FunctionType *fn = nullptr; 342 if (const PointerType *ptr = type->getAs<PointerType>()) { 343 fn = ptr->getPointeeType()->getAs<FunctionType>(); 344 if (!fn) return; 345 calleeType = CT_Function; 346 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 347 fn = ptr->getPointeeType()->castAs<FunctionType>(); 348 calleeType = CT_Block; 349 } else { 350 return; 351 } 352 353 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 354 numFormalParams = proto->getNumParams(); 355 } else { 356 numFormalParams = 0; 357 } 358 } else { 359 return; 360 } 361 362 // "nullPos" is the number of formal parameters at the end which 363 // effectively count as part of the variadic arguments. This is 364 // useful if you would prefer to not have *any* formal parameters, 365 // but the language forces you to have at least one. 366 unsigned nullPos = attr->getNullPos(); 367 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 368 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 369 370 // The number of arguments which should follow the sentinel. 371 unsigned numArgsAfterSentinel = attr->getSentinel(); 372 373 // If there aren't enough arguments for all the formal parameters, 374 // the sentinel, and the args after the sentinel, complain. 375 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 376 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 377 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 378 return; 379 } 380 381 // Otherwise, find the sentinel expression. 382 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 383 if (!sentinelExpr) return; 384 if (sentinelExpr->isValueDependent()) return; 385 if (Context.isSentinelNullExpr(sentinelExpr)) return; 386 387 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 388 // or 'NULL' if those are actually defined in the context. Only use 389 // 'nil' for ObjC methods, where it's much more likely that the 390 // variadic arguments form a list of object pointers. 391 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 392 std::string NullValue; 393 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 394 NullValue = "nil"; 395 else if (getLangOpts().CPlusPlus11) 396 NullValue = "nullptr"; 397 else if (PP.isMacroDefined("NULL")) 398 NullValue = "NULL"; 399 else 400 NullValue = "(void*) 0"; 401 402 if (MissingNilLoc.isInvalid()) 403 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 404 else 405 Diag(MissingNilLoc, diag::warn_missing_sentinel) 406 << int(calleeType) 407 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 408 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 409 } 410 411 SourceRange Sema::getExprRange(Expr *E) const { 412 return E ? E->getSourceRange() : SourceRange(); 413 } 414 415 //===----------------------------------------------------------------------===// 416 // Standard Promotions and Conversions 417 //===----------------------------------------------------------------------===// 418 419 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 420 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 421 // Handle any placeholder expressions which made it here. 422 if (E->getType()->isPlaceholderType()) { 423 ExprResult result = CheckPlaceholderExpr(E); 424 if (result.isInvalid()) return ExprError(); 425 E = result.get(); 426 } 427 428 QualType Ty = E->getType(); 429 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 430 431 if (Ty->isFunctionType()) { 432 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 433 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 434 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 435 return ExprError(); 436 437 E = ImpCastExprToType(E, Context.getPointerType(Ty), 438 CK_FunctionToPointerDecay).get(); 439 } else if (Ty->isArrayType()) { 440 // In C90 mode, arrays only promote to pointers if the array expression is 441 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 442 // type 'array of type' is converted to an expression that has type 'pointer 443 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 444 // that has type 'array of type' ...". The relevant change is "an lvalue" 445 // (C90) to "an expression" (C99). 446 // 447 // C++ 4.2p1: 448 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 449 // T" can be converted to an rvalue of type "pointer to T". 450 // 451 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 452 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 453 CK_ArrayToPointerDecay).get(); 454 } 455 return E; 456 } 457 458 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 459 // Check to see if we are dereferencing a null pointer. If so, 460 // and if not volatile-qualified, this is undefined behavior that the 461 // optimizer will delete, so warn about it. People sometimes try to use this 462 // to get a deterministic trap and are surprised by clang's behavior. This 463 // only handles the pattern "*null", which is a very syntactic check. 464 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 465 if (UO->getOpcode() == UO_Deref && 466 UO->getSubExpr()->IgnoreParenCasts()-> 467 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 468 !UO->getType().isVolatileQualified()) { 469 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 470 S.PDiag(diag::warn_indirection_through_null) 471 << UO->getSubExpr()->getSourceRange()); 472 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 473 S.PDiag(diag::note_indirection_through_null)); 474 } 475 } 476 477 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 478 SourceLocation AssignLoc, 479 const Expr* RHS) { 480 const ObjCIvarDecl *IV = OIRE->getDecl(); 481 if (!IV) 482 return; 483 484 DeclarationName MemberName = IV->getDeclName(); 485 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 486 if (!Member || !Member->isStr("isa")) 487 return; 488 489 const Expr *Base = OIRE->getBase(); 490 QualType BaseType = Base->getType(); 491 if (OIRE->isArrow()) 492 BaseType = BaseType->getPointeeType(); 493 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 494 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 495 ObjCInterfaceDecl *ClassDeclared = nullptr; 496 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 497 if (!ClassDeclared->getSuperClass() 498 && (*ClassDeclared->ivar_begin()) == IV) { 499 if (RHS) { 500 NamedDecl *ObjectSetClass = 501 S.LookupSingleName(S.TUScope, 502 &S.Context.Idents.get("object_setClass"), 503 SourceLocation(), S.LookupOrdinaryName); 504 if (ObjectSetClass) { 505 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 506 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 507 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 508 "object_setClass(") 509 << FixItHint::CreateReplacement( 510 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 511 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 512 } 513 else 514 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 515 } else { 516 NamedDecl *ObjectGetClass = 517 S.LookupSingleName(S.TUScope, 518 &S.Context.Idents.get("object_getClass"), 519 SourceLocation(), S.LookupOrdinaryName); 520 if (ObjectGetClass) 521 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 522 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 523 "object_getClass(") 524 << FixItHint::CreateReplacement( 525 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 526 else 527 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 528 } 529 S.Diag(IV->getLocation(), diag::note_ivar_decl); 530 } 531 } 532 } 533 534 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 535 // Handle any placeholder expressions which made it here. 536 if (E->getType()->isPlaceholderType()) { 537 ExprResult result = CheckPlaceholderExpr(E); 538 if (result.isInvalid()) return ExprError(); 539 E = result.get(); 540 } 541 542 // C++ [conv.lval]p1: 543 // A glvalue of a non-function, non-array type T can be 544 // converted to a prvalue. 545 if (!E->isGLValue()) return E; 546 547 QualType T = E->getType(); 548 assert(!T.isNull() && "r-value conversion on typeless expression?"); 549 550 // We don't want to throw lvalue-to-rvalue casts on top of 551 // expressions of certain types in C++. 552 if (getLangOpts().CPlusPlus && 553 (E->getType() == Context.OverloadTy || 554 T->isDependentType() || 555 T->isRecordType())) 556 return E; 557 558 // The C standard is actually really unclear on this point, and 559 // DR106 tells us what the result should be but not why. It's 560 // generally best to say that void types just doesn't undergo 561 // lvalue-to-rvalue at all. Note that expressions of unqualified 562 // 'void' type are never l-values, but qualified void can be. 563 if (T->isVoidType()) 564 return E; 565 566 // OpenCL usually rejects direct accesses to values of 'half' type. 567 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 568 T->isHalfType()) { 569 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 570 << 0 << T; 571 return ExprError(); 572 } 573 574 CheckForNullPointerDereference(*this, E); 575 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 576 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 577 &Context.Idents.get("object_getClass"), 578 SourceLocation(), LookupOrdinaryName); 579 if (ObjectGetClass) 580 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 581 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 582 << FixItHint::CreateReplacement( 583 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 584 else 585 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 586 } 587 else if (const ObjCIvarRefExpr *OIRE = 588 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 589 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 590 591 // C++ [conv.lval]p1: 592 // [...] If T is a non-class type, the type of the prvalue is the 593 // cv-unqualified version of T. Otherwise, the type of the 594 // rvalue is T. 595 // 596 // C99 6.3.2.1p2: 597 // If the lvalue has qualified type, the value has the unqualified 598 // version of the type of the lvalue; otherwise, the value has the 599 // type of the lvalue. 600 if (T.hasQualifiers()) 601 T = T.getUnqualifiedType(); 602 603 // Under the MS ABI, lock down the inheritance model now. 604 if (T->isMemberPointerType() && 605 Context.getTargetInfo().getCXXABI().isMicrosoft()) 606 (void)isCompleteType(E->getExprLoc(), T); 607 608 UpdateMarkingForLValueToRValue(E); 609 610 // Loading a __weak object implicitly retains the value, so we need a cleanup to 611 // balance that. 612 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 613 Cleanup.setExprNeedsCleanups(true); 614 615 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 616 nullptr, VK_RValue); 617 618 // C11 6.3.2.1p2: 619 // ... if the lvalue has atomic type, the value has the non-atomic version 620 // of the type of the lvalue ... 621 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 622 T = Atomic->getValueType().getUnqualifiedType(); 623 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 624 nullptr, VK_RValue); 625 } 626 627 return Res; 628 } 629 630 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 631 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 632 if (Res.isInvalid()) 633 return ExprError(); 634 Res = DefaultLvalueConversion(Res.get()); 635 if (Res.isInvalid()) 636 return ExprError(); 637 return Res; 638 } 639 640 /// CallExprUnaryConversions - a special case of an unary conversion 641 /// performed on a function designator of a call expression. 642 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 643 QualType Ty = E->getType(); 644 ExprResult Res = E; 645 // Only do implicit cast for a function type, but not for a pointer 646 // to function type. 647 if (Ty->isFunctionType()) { 648 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 649 CK_FunctionToPointerDecay).get(); 650 if (Res.isInvalid()) 651 return ExprError(); 652 } 653 Res = DefaultLvalueConversion(Res.get()); 654 if (Res.isInvalid()) 655 return ExprError(); 656 return Res.get(); 657 } 658 659 /// UsualUnaryConversions - Performs various conversions that are common to most 660 /// operators (C99 6.3). The conversions of array and function types are 661 /// sometimes suppressed. For example, the array->pointer conversion doesn't 662 /// apply if the array is an argument to the sizeof or address (&) operators. 663 /// In these instances, this routine should *not* be called. 664 ExprResult Sema::UsualUnaryConversions(Expr *E) { 665 // First, convert to an r-value. 666 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 667 if (Res.isInvalid()) 668 return ExprError(); 669 E = Res.get(); 670 671 QualType Ty = E->getType(); 672 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 673 674 // Half FP have to be promoted to float unless it is natively supported 675 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 676 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 677 678 // Try to perform integral promotions if the object has a theoretically 679 // promotable type. 680 if (Ty->isIntegralOrUnscopedEnumerationType()) { 681 // C99 6.3.1.1p2: 682 // 683 // The following may be used in an expression wherever an int or 684 // unsigned int may be used: 685 // - an object or expression with an integer type whose integer 686 // conversion rank is less than or equal to the rank of int 687 // and unsigned int. 688 // - A bit-field of type _Bool, int, signed int, or unsigned int. 689 // 690 // If an int can represent all values of the original type, the 691 // value is converted to an int; otherwise, it is converted to an 692 // unsigned int. These are called the integer promotions. All 693 // other types are unchanged by the integer promotions. 694 695 QualType PTy = Context.isPromotableBitField(E); 696 if (!PTy.isNull()) { 697 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 698 return E; 699 } 700 if (Ty->isPromotableIntegerType()) { 701 QualType PT = Context.getPromotedIntegerType(Ty); 702 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 703 return E; 704 } 705 } 706 return E; 707 } 708 709 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 710 /// do not have a prototype. Arguments that have type float or __fp16 711 /// are promoted to double. All other argument types are converted by 712 /// UsualUnaryConversions(). 713 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 714 QualType Ty = E->getType(); 715 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 716 717 ExprResult Res = UsualUnaryConversions(E); 718 if (Res.isInvalid()) 719 return ExprError(); 720 E = Res.get(); 721 722 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 723 // promote to double. 724 // Note that default argument promotion applies only to float (and 725 // half/fp16); it does not apply to _Float16. 726 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 727 if (BTy && (BTy->getKind() == BuiltinType::Half || 728 BTy->getKind() == BuiltinType::Float)) { 729 if (getLangOpts().OpenCL && 730 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 731 if (BTy->getKind() == BuiltinType::Half) { 732 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 733 } 734 } else { 735 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 736 } 737 } 738 739 // C++ performs lvalue-to-rvalue conversion as a default argument 740 // promotion, even on class types, but note: 741 // C++11 [conv.lval]p2: 742 // When an lvalue-to-rvalue conversion occurs in an unevaluated 743 // operand or a subexpression thereof the value contained in the 744 // referenced object is not accessed. Otherwise, if the glvalue 745 // has a class type, the conversion copy-initializes a temporary 746 // of type T from the glvalue and the result of the conversion 747 // is a prvalue for the temporary. 748 // FIXME: add some way to gate this entire thing for correctness in 749 // potentially potentially evaluated contexts. 750 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 751 ExprResult Temp = PerformCopyInitialization( 752 InitializedEntity::InitializeTemporary(E->getType()), 753 E->getExprLoc(), E); 754 if (Temp.isInvalid()) 755 return ExprError(); 756 E = Temp.get(); 757 } 758 759 return E; 760 } 761 762 /// Determine the degree of POD-ness for an expression. 763 /// Incomplete types are considered POD, since this check can be performed 764 /// when we're in an unevaluated context. 765 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 766 if (Ty->isIncompleteType()) { 767 // C++11 [expr.call]p7: 768 // After these conversions, if the argument does not have arithmetic, 769 // enumeration, pointer, pointer to member, or class type, the program 770 // is ill-formed. 771 // 772 // Since we've already performed array-to-pointer and function-to-pointer 773 // decay, the only such type in C++ is cv void. This also handles 774 // initializer lists as variadic arguments. 775 if (Ty->isVoidType()) 776 return VAK_Invalid; 777 778 if (Ty->isObjCObjectType()) 779 return VAK_Invalid; 780 return VAK_Valid; 781 } 782 783 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 784 return VAK_Invalid; 785 786 if (Ty.isCXX98PODType(Context)) 787 return VAK_Valid; 788 789 // C++11 [expr.call]p7: 790 // Passing a potentially-evaluated argument of class type (Clause 9) 791 // having a non-trivial copy constructor, a non-trivial move constructor, 792 // or a non-trivial destructor, with no corresponding parameter, 793 // is conditionally-supported with implementation-defined semantics. 794 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 795 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 796 if (!Record->hasNonTrivialCopyConstructor() && 797 !Record->hasNonTrivialMoveConstructor() && 798 !Record->hasNonTrivialDestructor()) 799 return VAK_ValidInCXX11; 800 801 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 802 return VAK_Valid; 803 804 if (Ty->isObjCObjectType()) 805 return VAK_Invalid; 806 807 if (getLangOpts().MSVCCompat) 808 return VAK_MSVCUndefined; 809 810 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 811 // permitted to reject them. We should consider doing so. 812 return VAK_Undefined; 813 } 814 815 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 816 // Don't allow one to pass an Objective-C interface to a vararg. 817 const QualType &Ty = E->getType(); 818 VarArgKind VAK = isValidVarArgType(Ty); 819 820 // Complain about passing non-POD types through varargs. 821 switch (VAK) { 822 case VAK_ValidInCXX11: 823 DiagRuntimeBehavior( 824 E->getBeginLoc(), nullptr, 825 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 826 LLVM_FALLTHROUGH; 827 case VAK_Valid: 828 if (Ty->isRecordType()) { 829 // This is unlikely to be what the user intended. If the class has a 830 // 'c_str' member function, the user probably meant to call that. 831 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 832 PDiag(diag::warn_pass_class_arg_to_vararg) 833 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 834 } 835 break; 836 837 case VAK_Undefined: 838 case VAK_MSVCUndefined: 839 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 840 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 841 << getLangOpts().CPlusPlus11 << Ty << CT); 842 break; 843 844 case VAK_Invalid: 845 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 846 Diag(E->getBeginLoc(), 847 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 848 << Ty << CT; 849 else if (Ty->isObjCObjectType()) 850 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 851 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 852 << Ty << CT); 853 else 854 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 855 << isa<InitListExpr>(E) << Ty << CT; 856 break; 857 } 858 } 859 860 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 861 /// will create a trap if the resulting type is not a POD type. 862 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 863 FunctionDecl *FDecl) { 864 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 865 // Strip the unbridged-cast placeholder expression off, if applicable. 866 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 867 (CT == VariadicMethod || 868 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 869 E = stripARCUnbridgedCast(E); 870 871 // Otherwise, do normal placeholder checking. 872 } else { 873 ExprResult ExprRes = CheckPlaceholderExpr(E); 874 if (ExprRes.isInvalid()) 875 return ExprError(); 876 E = ExprRes.get(); 877 } 878 } 879 880 ExprResult ExprRes = DefaultArgumentPromotion(E); 881 if (ExprRes.isInvalid()) 882 return ExprError(); 883 E = ExprRes.get(); 884 885 // Diagnostics regarding non-POD argument types are 886 // emitted along with format string checking in Sema::CheckFunctionCall(). 887 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 888 // Turn this into a trap. 889 CXXScopeSpec SS; 890 SourceLocation TemplateKWLoc; 891 UnqualifiedId Name; 892 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 893 E->getBeginLoc()); 894 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 895 Name, true, false); 896 if (TrapFn.isInvalid()) 897 return ExprError(); 898 899 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 900 None, E->getEndLoc()); 901 if (Call.isInvalid()) 902 return ExprError(); 903 904 ExprResult Comma = 905 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 906 if (Comma.isInvalid()) 907 return ExprError(); 908 return Comma.get(); 909 } 910 911 if (!getLangOpts().CPlusPlus && 912 RequireCompleteType(E->getExprLoc(), E->getType(), 913 diag::err_call_incomplete_argument)) 914 return ExprError(); 915 916 return E; 917 } 918 919 /// Converts an integer to complex float type. Helper function of 920 /// UsualArithmeticConversions() 921 /// 922 /// \return false if the integer expression is an integer type and is 923 /// successfully converted to the complex type. 924 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 925 ExprResult &ComplexExpr, 926 QualType IntTy, 927 QualType ComplexTy, 928 bool SkipCast) { 929 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 930 if (SkipCast) return false; 931 if (IntTy->isIntegerType()) { 932 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 933 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 934 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 935 CK_FloatingRealToComplex); 936 } else { 937 assert(IntTy->isComplexIntegerType()); 938 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 939 CK_IntegralComplexToFloatingComplex); 940 } 941 return false; 942 } 943 944 /// Handle arithmetic conversion with complex types. Helper function of 945 /// UsualArithmeticConversions() 946 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 947 ExprResult &RHS, QualType LHSType, 948 QualType RHSType, 949 bool IsCompAssign) { 950 // if we have an integer operand, the result is the complex type. 951 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 952 /*skipCast*/false)) 953 return LHSType; 954 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 955 /*skipCast*/IsCompAssign)) 956 return RHSType; 957 958 // This handles complex/complex, complex/float, or float/complex. 959 // When both operands are complex, the shorter operand is converted to the 960 // type of the longer, and that is the type of the result. This corresponds 961 // to what is done when combining two real floating-point operands. 962 // The fun begins when size promotion occur across type domains. 963 // From H&S 6.3.4: When one operand is complex and the other is a real 964 // floating-point type, the less precise type is converted, within it's 965 // real or complex domain, to the precision of the other type. For example, 966 // when combining a "long double" with a "double _Complex", the 967 // "double _Complex" is promoted to "long double _Complex". 968 969 // Compute the rank of the two types, regardless of whether they are complex. 970 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 971 972 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 973 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 974 QualType LHSElementType = 975 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 976 QualType RHSElementType = 977 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 978 979 QualType ResultType = S.Context.getComplexType(LHSElementType); 980 if (Order < 0) { 981 // Promote the precision of the LHS if not an assignment. 982 ResultType = S.Context.getComplexType(RHSElementType); 983 if (!IsCompAssign) { 984 if (LHSComplexType) 985 LHS = 986 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 987 else 988 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 989 } 990 } else if (Order > 0) { 991 // Promote the precision of the RHS. 992 if (RHSComplexType) 993 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 994 else 995 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 996 } 997 return ResultType; 998 } 999 1000 /// Handle arithmetic conversion from integer to float. Helper function 1001 /// of UsualArithmeticConversions() 1002 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1003 ExprResult &IntExpr, 1004 QualType FloatTy, QualType IntTy, 1005 bool ConvertFloat, bool ConvertInt) { 1006 if (IntTy->isIntegerType()) { 1007 if (ConvertInt) 1008 // Convert intExpr to the lhs floating point type. 1009 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1010 CK_IntegralToFloating); 1011 return FloatTy; 1012 } 1013 1014 // Convert both sides to the appropriate complex float. 1015 assert(IntTy->isComplexIntegerType()); 1016 QualType result = S.Context.getComplexType(FloatTy); 1017 1018 // _Complex int -> _Complex float 1019 if (ConvertInt) 1020 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1021 CK_IntegralComplexToFloatingComplex); 1022 1023 // float -> _Complex float 1024 if (ConvertFloat) 1025 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1026 CK_FloatingRealToComplex); 1027 1028 return result; 1029 } 1030 1031 /// Handle arithmethic conversion with floating point types. Helper 1032 /// function of UsualArithmeticConversions() 1033 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1034 ExprResult &RHS, QualType LHSType, 1035 QualType RHSType, bool IsCompAssign) { 1036 bool LHSFloat = LHSType->isRealFloatingType(); 1037 bool RHSFloat = RHSType->isRealFloatingType(); 1038 1039 // If we have two real floating types, convert the smaller operand 1040 // to the bigger result. 1041 if (LHSFloat && RHSFloat) { 1042 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1043 if (order > 0) { 1044 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1045 return LHSType; 1046 } 1047 1048 assert(order < 0 && "illegal float comparison"); 1049 if (!IsCompAssign) 1050 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1051 return RHSType; 1052 } 1053 1054 if (LHSFloat) { 1055 // Half FP has to be promoted to float unless it is natively supported 1056 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1057 LHSType = S.Context.FloatTy; 1058 1059 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1060 /*convertFloat=*/!IsCompAssign, 1061 /*convertInt=*/ true); 1062 } 1063 assert(RHSFloat); 1064 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1065 /*convertInt=*/ true, 1066 /*convertFloat=*/!IsCompAssign); 1067 } 1068 1069 /// Diagnose attempts to convert between __float128 and long double if 1070 /// there is no support for such conversion. Helper function of 1071 /// UsualArithmeticConversions(). 1072 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1073 QualType RHSType) { 1074 /* No issue converting if at least one of the types is not a floating point 1075 type or the two types have the same rank. 1076 */ 1077 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1078 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1079 return false; 1080 1081 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1082 "The remaining types must be floating point types."); 1083 1084 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1085 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1086 1087 QualType LHSElemType = LHSComplex ? 1088 LHSComplex->getElementType() : LHSType; 1089 QualType RHSElemType = RHSComplex ? 1090 RHSComplex->getElementType() : RHSType; 1091 1092 // No issue if the two types have the same representation 1093 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1094 &S.Context.getFloatTypeSemantics(RHSElemType)) 1095 return false; 1096 1097 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1098 RHSElemType == S.Context.LongDoubleTy); 1099 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1100 RHSElemType == S.Context.Float128Ty); 1101 1102 // We've handled the situation where __float128 and long double have the same 1103 // representation. We allow all conversions for all possible long double types 1104 // except PPC's double double. 1105 return Float128AndLongDouble && 1106 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1107 &llvm::APFloat::PPCDoubleDouble()); 1108 } 1109 1110 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1111 1112 namespace { 1113 /// These helper callbacks are placed in an anonymous namespace to 1114 /// permit their use as function template parameters. 1115 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1116 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1117 } 1118 1119 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1120 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1121 CK_IntegralComplexCast); 1122 } 1123 } 1124 1125 /// Handle integer arithmetic conversions. Helper function of 1126 /// UsualArithmeticConversions() 1127 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1128 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1129 ExprResult &RHS, QualType LHSType, 1130 QualType RHSType, bool IsCompAssign) { 1131 // The rules for this case are in C99 6.3.1.8 1132 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1133 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1134 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1135 if (LHSSigned == RHSSigned) { 1136 // Same signedness; use the higher-ranked type 1137 if (order >= 0) { 1138 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1139 return LHSType; 1140 } else if (!IsCompAssign) 1141 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1142 return RHSType; 1143 } else if (order != (LHSSigned ? 1 : -1)) { 1144 // The unsigned type has greater than or equal rank to the 1145 // signed type, so use the unsigned type 1146 if (RHSSigned) { 1147 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1148 return LHSType; 1149 } else if (!IsCompAssign) 1150 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1151 return RHSType; 1152 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1153 // The two types are different widths; if we are here, that 1154 // means the signed type is larger than the unsigned type, so 1155 // use the signed type. 1156 if (LHSSigned) { 1157 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1158 return LHSType; 1159 } else if (!IsCompAssign) 1160 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1161 return RHSType; 1162 } else { 1163 // The signed type is higher-ranked than the unsigned type, 1164 // but isn't actually any bigger (like unsigned int and long 1165 // on most 32-bit systems). Use the unsigned type corresponding 1166 // to the signed type. 1167 QualType result = 1168 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1169 RHS = (*doRHSCast)(S, RHS.get(), result); 1170 if (!IsCompAssign) 1171 LHS = (*doLHSCast)(S, LHS.get(), result); 1172 return result; 1173 } 1174 } 1175 1176 /// Handle conversions with GCC complex int extension. Helper function 1177 /// of UsualArithmeticConversions() 1178 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1179 ExprResult &RHS, QualType LHSType, 1180 QualType RHSType, 1181 bool IsCompAssign) { 1182 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1183 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1184 1185 if (LHSComplexInt && RHSComplexInt) { 1186 QualType LHSEltType = LHSComplexInt->getElementType(); 1187 QualType RHSEltType = RHSComplexInt->getElementType(); 1188 QualType ScalarType = 1189 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1190 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1191 1192 return S.Context.getComplexType(ScalarType); 1193 } 1194 1195 if (LHSComplexInt) { 1196 QualType LHSEltType = LHSComplexInt->getElementType(); 1197 QualType ScalarType = 1198 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1199 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1200 QualType ComplexType = S.Context.getComplexType(ScalarType); 1201 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1202 CK_IntegralRealToComplex); 1203 1204 return ComplexType; 1205 } 1206 1207 assert(RHSComplexInt); 1208 1209 QualType RHSEltType = RHSComplexInt->getElementType(); 1210 QualType ScalarType = 1211 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1212 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1213 QualType ComplexType = S.Context.getComplexType(ScalarType); 1214 1215 if (!IsCompAssign) 1216 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1217 CK_IntegralRealToComplex); 1218 return ComplexType; 1219 } 1220 1221 /// UsualArithmeticConversions - Performs various conversions that are common to 1222 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1223 /// routine returns the first non-arithmetic type found. The client is 1224 /// responsible for emitting appropriate error diagnostics. 1225 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1226 bool IsCompAssign) { 1227 if (!IsCompAssign) { 1228 LHS = UsualUnaryConversions(LHS.get()); 1229 if (LHS.isInvalid()) 1230 return QualType(); 1231 } 1232 1233 RHS = UsualUnaryConversions(RHS.get()); 1234 if (RHS.isInvalid()) 1235 return QualType(); 1236 1237 // For conversion purposes, we ignore any qualifiers. 1238 // For example, "const float" and "float" are equivalent. 1239 QualType LHSType = 1240 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1241 QualType RHSType = 1242 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1243 1244 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1245 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1246 LHSType = AtomicLHS->getValueType(); 1247 1248 // If both types are identical, no conversion is needed. 1249 if (LHSType == RHSType) 1250 return LHSType; 1251 1252 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1253 // The caller can deal with this (e.g. pointer + int). 1254 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1255 return QualType(); 1256 1257 // Apply unary and bitfield promotions to the LHS's type. 1258 QualType LHSUnpromotedType = LHSType; 1259 if (LHSType->isPromotableIntegerType()) 1260 LHSType = Context.getPromotedIntegerType(LHSType); 1261 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1262 if (!LHSBitfieldPromoteTy.isNull()) 1263 LHSType = LHSBitfieldPromoteTy; 1264 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1265 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1266 1267 // If both types are identical, no conversion is needed. 1268 if (LHSType == RHSType) 1269 return LHSType; 1270 1271 // At this point, we have two different arithmetic types. 1272 1273 // Diagnose attempts to convert between __float128 and long double where 1274 // such conversions currently can't be handled. 1275 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1276 return QualType(); 1277 1278 // Handle complex types first (C99 6.3.1.8p1). 1279 if (LHSType->isComplexType() || RHSType->isComplexType()) 1280 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1281 IsCompAssign); 1282 1283 // Now handle "real" floating types (i.e. float, double, long double). 1284 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1285 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1286 IsCompAssign); 1287 1288 // Handle GCC complex int extension. 1289 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1290 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1291 IsCompAssign); 1292 1293 // Finally, we have two differing integer types. 1294 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1295 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1296 } 1297 1298 1299 //===----------------------------------------------------------------------===// 1300 // Semantic Analysis for various Expression Types 1301 //===----------------------------------------------------------------------===// 1302 1303 1304 ExprResult 1305 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1306 SourceLocation DefaultLoc, 1307 SourceLocation RParenLoc, 1308 Expr *ControllingExpr, 1309 ArrayRef<ParsedType> ArgTypes, 1310 ArrayRef<Expr *> ArgExprs) { 1311 unsigned NumAssocs = ArgTypes.size(); 1312 assert(NumAssocs == ArgExprs.size()); 1313 1314 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1315 for (unsigned i = 0; i < NumAssocs; ++i) { 1316 if (ArgTypes[i]) 1317 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1318 else 1319 Types[i] = nullptr; 1320 } 1321 1322 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1323 ControllingExpr, 1324 llvm::makeArrayRef(Types, NumAssocs), 1325 ArgExprs); 1326 delete [] Types; 1327 return ER; 1328 } 1329 1330 ExprResult 1331 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1332 SourceLocation DefaultLoc, 1333 SourceLocation RParenLoc, 1334 Expr *ControllingExpr, 1335 ArrayRef<TypeSourceInfo *> Types, 1336 ArrayRef<Expr *> Exprs) { 1337 unsigned NumAssocs = Types.size(); 1338 assert(NumAssocs == Exprs.size()); 1339 1340 // Decay and strip qualifiers for the controlling expression type, and handle 1341 // placeholder type replacement. See committee discussion from WG14 DR423. 1342 { 1343 EnterExpressionEvaluationContext Unevaluated( 1344 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1345 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1346 if (R.isInvalid()) 1347 return ExprError(); 1348 ControllingExpr = R.get(); 1349 } 1350 1351 // The controlling expression is an unevaluated operand, so side effects are 1352 // likely unintended. 1353 if (!inTemplateInstantiation() && 1354 ControllingExpr->HasSideEffects(Context, false)) 1355 Diag(ControllingExpr->getExprLoc(), 1356 diag::warn_side_effects_unevaluated_context); 1357 1358 bool TypeErrorFound = false, 1359 IsResultDependent = ControllingExpr->isTypeDependent(), 1360 ContainsUnexpandedParameterPack 1361 = ControllingExpr->containsUnexpandedParameterPack(); 1362 1363 for (unsigned i = 0; i < NumAssocs; ++i) { 1364 if (Exprs[i]->containsUnexpandedParameterPack()) 1365 ContainsUnexpandedParameterPack = true; 1366 1367 if (Types[i]) { 1368 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1369 ContainsUnexpandedParameterPack = true; 1370 1371 if (Types[i]->getType()->isDependentType()) { 1372 IsResultDependent = true; 1373 } else { 1374 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1375 // complete object type other than a variably modified type." 1376 unsigned D = 0; 1377 if (Types[i]->getType()->isIncompleteType()) 1378 D = diag::err_assoc_type_incomplete; 1379 else if (!Types[i]->getType()->isObjectType()) 1380 D = diag::err_assoc_type_nonobject; 1381 else if (Types[i]->getType()->isVariablyModifiedType()) 1382 D = diag::err_assoc_type_variably_modified; 1383 1384 if (D != 0) { 1385 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1386 << Types[i]->getTypeLoc().getSourceRange() 1387 << Types[i]->getType(); 1388 TypeErrorFound = true; 1389 } 1390 1391 // C11 6.5.1.1p2 "No two generic associations in the same generic 1392 // selection shall specify compatible types." 1393 for (unsigned j = i+1; j < NumAssocs; ++j) 1394 if (Types[j] && !Types[j]->getType()->isDependentType() && 1395 Context.typesAreCompatible(Types[i]->getType(), 1396 Types[j]->getType())) { 1397 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1398 diag::err_assoc_compatible_types) 1399 << Types[j]->getTypeLoc().getSourceRange() 1400 << Types[j]->getType() 1401 << Types[i]->getType(); 1402 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1403 diag::note_compat_assoc) 1404 << Types[i]->getTypeLoc().getSourceRange() 1405 << Types[i]->getType(); 1406 TypeErrorFound = true; 1407 } 1408 } 1409 } 1410 } 1411 if (TypeErrorFound) 1412 return ExprError(); 1413 1414 // If we determined that the generic selection is result-dependent, don't 1415 // try to compute the result expression. 1416 if (IsResultDependent) 1417 return new (Context) GenericSelectionExpr( 1418 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1419 ContainsUnexpandedParameterPack); 1420 1421 SmallVector<unsigned, 1> CompatIndices; 1422 unsigned DefaultIndex = -1U; 1423 for (unsigned i = 0; i < NumAssocs; ++i) { 1424 if (!Types[i]) 1425 DefaultIndex = i; 1426 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1427 Types[i]->getType())) 1428 CompatIndices.push_back(i); 1429 } 1430 1431 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1432 // type compatible with at most one of the types named in its generic 1433 // association list." 1434 if (CompatIndices.size() > 1) { 1435 // We strip parens here because the controlling expression is typically 1436 // parenthesized in macro definitions. 1437 ControllingExpr = ControllingExpr->IgnoreParens(); 1438 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1439 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1440 << (unsigned)CompatIndices.size(); 1441 for (unsigned I : CompatIndices) { 1442 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1443 diag::note_compat_assoc) 1444 << Types[I]->getTypeLoc().getSourceRange() 1445 << Types[I]->getType(); 1446 } 1447 return ExprError(); 1448 } 1449 1450 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1451 // its controlling expression shall have type compatible with exactly one of 1452 // the types named in its generic association list." 1453 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1454 // We strip parens here because the controlling expression is typically 1455 // parenthesized in macro definitions. 1456 ControllingExpr = ControllingExpr->IgnoreParens(); 1457 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1458 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1459 return ExprError(); 1460 } 1461 1462 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1463 // type name that is compatible with the type of the controlling expression, 1464 // then the result expression of the generic selection is the expression 1465 // in that generic association. Otherwise, the result expression of the 1466 // generic selection is the expression in the default generic association." 1467 unsigned ResultIndex = 1468 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1469 1470 return new (Context) GenericSelectionExpr( 1471 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1472 ContainsUnexpandedParameterPack, ResultIndex); 1473 } 1474 1475 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1476 /// location of the token and the offset of the ud-suffix within it. 1477 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1478 unsigned Offset) { 1479 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1480 S.getLangOpts()); 1481 } 1482 1483 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1484 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1485 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1486 IdentifierInfo *UDSuffix, 1487 SourceLocation UDSuffixLoc, 1488 ArrayRef<Expr*> Args, 1489 SourceLocation LitEndLoc) { 1490 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1491 1492 QualType ArgTy[2]; 1493 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1494 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1495 if (ArgTy[ArgIdx]->isArrayType()) 1496 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1497 } 1498 1499 DeclarationName OpName = 1500 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1501 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1502 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1503 1504 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1505 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1506 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1507 /*AllowStringTemplate*/ false, 1508 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1509 return ExprError(); 1510 1511 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1512 } 1513 1514 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1515 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1516 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1517 /// multiple tokens. However, the common case is that StringToks points to one 1518 /// string. 1519 /// 1520 ExprResult 1521 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1522 assert(!StringToks.empty() && "Must have at least one string!"); 1523 1524 StringLiteralParser Literal(StringToks, PP); 1525 if (Literal.hadError) 1526 return ExprError(); 1527 1528 SmallVector<SourceLocation, 4> StringTokLocs; 1529 for (const Token &Tok : StringToks) 1530 StringTokLocs.push_back(Tok.getLocation()); 1531 1532 QualType CharTy = Context.CharTy; 1533 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1534 if (Literal.isWide()) { 1535 CharTy = Context.getWideCharType(); 1536 Kind = StringLiteral::Wide; 1537 } else if (Literal.isUTF8()) { 1538 if (getLangOpts().Char8) 1539 CharTy = Context.Char8Ty; 1540 Kind = StringLiteral::UTF8; 1541 } else if (Literal.isUTF16()) { 1542 CharTy = Context.Char16Ty; 1543 Kind = StringLiteral::UTF16; 1544 } else if (Literal.isUTF32()) { 1545 CharTy = Context.Char32Ty; 1546 Kind = StringLiteral::UTF32; 1547 } else if (Literal.isPascal()) { 1548 CharTy = Context.UnsignedCharTy; 1549 } 1550 1551 QualType CharTyConst = CharTy; 1552 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1553 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1554 CharTyConst.addConst(); 1555 1556 CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst); 1557 1558 // Get an array type for the string, according to C99 6.4.5. This includes 1559 // the nul terminator character as well as the string length for pascal 1560 // strings. 1561 QualType StrTy = Context.getConstantArrayType( 1562 CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1), 1563 ArrayType::Normal, 0); 1564 1565 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1566 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1567 Kind, Literal.Pascal, StrTy, 1568 &StringTokLocs[0], 1569 StringTokLocs.size()); 1570 if (Literal.getUDSuffix().empty()) 1571 return Lit; 1572 1573 // We're building a user-defined literal. 1574 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1575 SourceLocation UDSuffixLoc = 1576 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1577 Literal.getUDSuffixOffset()); 1578 1579 // Make sure we're allowed user-defined literals here. 1580 if (!UDLScope) 1581 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1582 1583 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1584 // operator "" X (str, len) 1585 QualType SizeType = Context.getSizeType(); 1586 1587 DeclarationName OpName = 1588 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1589 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1590 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1591 1592 QualType ArgTy[] = { 1593 Context.getArrayDecayedType(StrTy), SizeType 1594 }; 1595 1596 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1597 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1598 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1599 /*AllowStringTemplate*/ true, 1600 /*DiagnoseMissing*/ true)) { 1601 1602 case LOLR_Cooked: { 1603 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1604 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1605 StringTokLocs[0]); 1606 Expr *Args[] = { Lit, LenArg }; 1607 1608 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1609 } 1610 1611 case LOLR_StringTemplate: { 1612 TemplateArgumentListInfo ExplicitArgs; 1613 1614 unsigned CharBits = Context.getIntWidth(CharTy); 1615 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1616 llvm::APSInt Value(CharBits, CharIsUnsigned); 1617 1618 TemplateArgument TypeArg(CharTy); 1619 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1620 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1621 1622 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1623 Value = Lit->getCodeUnit(I); 1624 TemplateArgument Arg(Context, Value, CharTy); 1625 TemplateArgumentLocInfo ArgInfo; 1626 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1627 } 1628 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1629 &ExplicitArgs); 1630 } 1631 case LOLR_Raw: 1632 case LOLR_Template: 1633 case LOLR_ErrorNoDiagnostic: 1634 llvm_unreachable("unexpected literal operator lookup result"); 1635 case LOLR_Error: 1636 return ExprError(); 1637 } 1638 llvm_unreachable("unexpected literal operator lookup result"); 1639 } 1640 1641 ExprResult 1642 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1643 SourceLocation Loc, 1644 const CXXScopeSpec *SS) { 1645 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1646 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1647 } 1648 1649 /// BuildDeclRefExpr - Build an expression that references a 1650 /// declaration that does not require a closure capture. 1651 ExprResult 1652 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1653 const DeclarationNameInfo &NameInfo, 1654 const CXXScopeSpec *SS, NamedDecl *FoundD, 1655 const TemplateArgumentListInfo *TemplateArgs) { 1656 bool RefersToCapturedVariable = 1657 isa<VarDecl>(D) && 1658 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1659 1660 DeclRefExpr *E; 1661 if (isa<VarTemplateSpecializationDecl>(D)) { 1662 VarTemplateSpecializationDecl *VarSpec = 1663 cast<VarTemplateSpecializationDecl>(D); 1664 1665 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1666 : NestedNameSpecifierLoc(), 1667 VarSpec->getTemplateKeywordLoc(), D, 1668 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1669 FoundD, TemplateArgs); 1670 } else { 1671 assert(!TemplateArgs && "No template arguments for non-variable" 1672 " template specialization references"); 1673 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1674 : NestedNameSpecifierLoc(), 1675 SourceLocation(), D, RefersToCapturedVariable, 1676 NameInfo, Ty, VK, FoundD); 1677 } 1678 1679 MarkDeclRefReferenced(E); 1680 1681 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1682 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1683 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1684 getCurFunction()->recordUseOfWeak(E); 1685 1686 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1687 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1688 FD = IFD->getAnonField(); 1689 if (FD) { 1690 UnusedPrivateFields.remove(FD); 1691 // Just in case we're building an illegal pointer-to-member. 1692 if (FD->isBitField()) 1693 E->setObjectKind(OK_BitField); 1694 } 1695 1696 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1697 // designates a bit-field. 1698 if (auto *BD = dyn_cast<BindingDecl>(D)) 1699 if (auto *BE = BD->getBinding()) 1700 E->setObjectKind(BE->getObjectKind()); 1701 1702 return E; 1703 } 1704 1705 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1706 /// possibly a list of template arguments. 1707 /// 1708 /// If this produces template arguments, it is permitted to call 1709 /// DecomposeTemplateName. 1710 /// 1711 /// This actually loses a lot of source location information for 1712 /// non-standard name kinds; we should consider preserving that in 1713 /// some way. 1714 void 1715 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1716 TemplateArgumentListInfo &Buffer, 1717 DeclarationNameInfo &NameInfo, 1718 const TemplateArgumentListInfo *&TemplateArgs) { 1719 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1720 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1721 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1722 1723 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1724 Id.TemplateId->NumArgs); 1725 translateTemplateArguments(TemplateArgsPtr, Buffer); 1726 1727 TemplateName TName = Id.TemplateId->Template.get(); 1728 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1729 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1730 TemplateArgs = &Buffer; 1731 } else { 1732 NameInfo = GetNameFromUnqualifiedId(Id); 1733 TemplateArgs = nullptr; 1734 } 1735 } 1736 1737 static void emitEmptyLookupTypoDiagnostic( 1738 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1739 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1740 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1741 DeclContext *Ctx = 1742 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1743 if (!TC) { 1744 // Emit a special diagnostic for failed member lookups. 1745 // FIXME: computing the declaration context might fail here (?) 1746 if (Ctx) 1747 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1748 << SS.getRange(); 1749 else 1750 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1751 return; 1752 } 1753 1754 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1755 bool DroppedSpecifier = 1756 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1757 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1758 ? diag::note_implicit_param_decl 1759 : diag::note_previous_decl; 1760 if (!Ctx) 1761 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1762 SemaRef.PDiag(NoteID)); 1763 else 1764 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1765 << Typo << Ctx << DroppedSpecifier 1766 << SS.getRange(), 1767 SemaRef.PDiag(NoteID)); 1768 } 1769 1770 /// Diagnose an empty lookup. 1771 /// 1772 /// \return false if new lookup candidates were found 1773 bool 1774 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1775 std::unique_ptr<CorrectionCandidateCallback> CCC, 1776 TemplateArgumentListInfo *ExplicitTemplateArgs, 1777 ArrayRef<Expr *> Args, TypoExpr **Out) { 1778 DeclarationName Name = R.getLookupName(); 1779 1780 unsigned diagnostic = diag::err_undeclared_var_use; 1781 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1782 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1783 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1784 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1785 diagnostic = diag::err_undeclared_use; 1786 diagnostic_suggest = diag::err_undeclared_use_suggest; 1787 } 1788 1789 // If the original lookup was an unqualified lookup, fake an 1790 // unqualified lookup. This is useful when (for example) the 1791 // original lookup would not have found something because it was a 1792 // dependent name. 1793 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1794 while (DC) { 1795 if (isa<CXXRecordDecl>(DC)) { 1796 LookupQualifiedName(R, DC); 1797 1798 if (!R.empty()) { 1799 // Don't give errors about ambiguities in this lookup. 1800 R.suppressDiagnostics(); 1801 1802 // During a default argument instantiation the CurContext points 1803 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1804 // function parameter list, hence add an explicit check. 1805 bool isDefaultArgument = 1806 !CodeSynthesisContexts.empty() && 1807 CodeSynthesisContexts.back().Kind == 1808 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1809 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1810 bool isInstance = CurMethod && 1811 CurMethod->isInstance() && 1812 DC == CurMethod->getParent() && !isDefaultArgument; 1813 1814 // Give a code modification hint to insert 'this->'. 1815 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1816 // Actually quite difficult! 1817 if (getLangOpts().MSVCCompat) 1818 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1819 if (isInstance) { 1820 Diag(R.getNameLoc(), diagnostic) << Name 1821 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1822 CheckCXXThisCapture(R.getNameLoc()); 1823 } else { 1824 Diag(R.getNameLoc(), diagnostic) << Name; 1825 } 1826 1827 // Do we really want to note all of these? 1828 for (NamedDecl *D : R) 1829 Diag(D->getLocation(), diag::note_dependent_var_use); 1830 1831 // Return true if we are inside a default argument instantiation 1832 // and the found name refers to an instance member function, otherwise 1833 // the function calling DiagnoseEmptyLookup will try to create an 1834 // implicit member call and this is wrong for default argument. 1835 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1836 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1837 return true; 1838 } 1839 1840 // Tell the callee to try to recover. 1841 return false; 1842 } 1843 1844 R.clear(); 1845 } 1846 1847 // In Microsoft mode, if we are performing lookup from within a friend 1848 // function definition declared at class scope then we must set 1849 // DC to the lexical parent to be able to search into the parent 1850 // class. 1851 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1852 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1853 DC->getLexicalParent()->isRecord()) 1854 DC = DC->getLexicalParent(); 1855 else 1856 DC = DC->getParent(); 1857 } 1858 1859 // We didn't find anything, so try to correct for a typo. 1860 TypoCorrection Corrected; 1861 if (S && Out) { 1862 SourceLocation TypoLoc = R.getNameLoc(); 1863 assert(!ExplicitTemplateArgs && 1864 "Diagnosing an empty lookup with explicit template args!"); 1865 *Out = CorrectTypoDelayed( 1866 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1867 [=](const TypoCorrection &TC) { 1868 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1869 diagnostic, diagnostic_suggest); 1870 }, 1871 nullptr, CTK_ErrorRecovery); 1872 if (*Out) 1873 return true; 1874 } else if (S && (Corrected = 1875 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1876 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1877 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1878 bool DroppedSpecifier = 1879 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1880 R.setLookupName(Corrected.getCorrection()); 1881 1882 bool AcceptableWithRecovery = false; 1883 bool AcceptableWithoutRecovery = false; 1884 NamedDecl *ND = Corrected.getFoundDecl(); 1885 if (ND) { 1886 if (Corrected.isOverloaded()) { 1887 OverloadCandidateSet OCS(R.getNameLoc(), 1888 OverloadCandidateSet::CSK_Normal); 1889 OverloadCandidateSet::iterator Best; 1890 for (NamedDecl *CD : Corrected) { 1891 if (FunctionTemplateDecl *FTD = 1892 dyn_cast<FunctionTemplateDecl>(CD)) 1893 AddTemplateOverloadCandidate( 1894 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1895 Args, OCS); 1896 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1897 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1898 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1899 Args, OCS); 1900 } 1901 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1902 case OR_Success: 1903 ND = Best->FoundDecl; 1904 Corrected.setCorrectionDecl(ND); 1905 break; 1906 default: 1907 // FIXME: Arbitrarily pick the first declaration for the note. 1908 Corrected.setCorrectionDecl(ND); 1909 break; 1910 } 1911 } 1912 R.addDecl(ND); 1913 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1914 CXXRecordDecl *Record = nullptr; 1915 if (Corrected.getCorrectionSpecifier()) { 1916 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1917 Record = Ty->getAsCXXRecordDecl(); 1918 } 1919 if (!Record) 1920 Record = cast<CXXRecordDecl>( 1921 ND->getDeclContext()->getRedeclContext()); 1922 R.setNamingClass(Record); 1923 } 1924 1925 auto *UnderlyingND = ND->getUnderlyingDecl(); 1926 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 1927 isa<FunctionTemplateDecl>(UnderlyingND); 1928 // FIXME: If we ended up with a typo for a type name or 1929 // Objective-C class name, we're in trouble because the parser 1930 // is in the wrong place to recover. Suggest the typo 1931 // correction, but don't make it a fix-it since we're not going 1932 // to recover well anyway. 1933 AcceptableWithoutRecovery = 1934 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 1935 } else { 1936 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1937 // because we aren't able to recover. 1938 AcceptableWithoutRecovery = true; 1939 } 1940 1941 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1942 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 1943 ? diag::note_implicit_param_decl 1944 : diag::note_previous_decl; 1945 if (SS.isEmpty()) 1946 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1947 PDiag(NoteID), AcceptableWithRecovery); 1948 else 1949 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1950 << Name << computeDeclContext(SS, false) 1951 << DroppedSpecifier << SS.getRange(), 1952 PDiag(NoteID), AcceptableWithRecovery); 1953 1954 // Tell the callee whether to try to recover. 1955 return !AcceptableWithRecovery; 1956 } 1957 } 1958 R.clear(); 1959 1960 // Emit a special diagnostic for failed member lookups. 1961 // FIXME: computing the declaration context might fail here (?) 1962 if (!SS.isEmpty()) { 1963 Diag(R.getNameLoc(), diag::err_no_member) 1964 << Name << computeDeclContext(SS, false) 1965 << SS.getRange(); 1966 return true; 1967 } 1968 1969 // Give up, we can't recover. 1970 Diag(R.getNameLoc(), diagnostic) << Name; 1971 return true; 1972 } 1973 1974 /// In Microsoft mode, if we are inside a template class whose parent class has 1975 /// dependent base classes, and we can't resolve an unqualified identifier, then 1976 /// assume the identifier is a member of a dependent base class. We can only 1977 /// recover successfully in static methods, instance methods, and other contexts 1978 /// where 'this' is available. This doesn't precisely match MSVC's 1979 /// instantiation model, but it's close enough. 1980 static Expr * 1981 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 1982 DeclarationNameInfo &NameInfo, 1983 SourceLocation TemplateKWLoc, 1984 const TemplateArgumentListInfo *TemplateArgs) { 1985 // Only try to recover from lookup into dependent bases in static methods or 1986 // contexts where 'this' is available. 1987 QualType ThisType = S.getCurrentThisType(); 1988 const CXXRecordDecl *RD = nullptr; 1989 if (!ThisType.isNull()) 1990 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 1991 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 1992 RD = MD->getParent(); 1993 if (!RD || !RD->hasAnyDependentBases()) 1994 return nullptr; 1995 1996 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 1997 // is available, suggest inserting 'this->' as a fixit. 1998 SourceLocation Loc = NameInfo.getLoc(); 1999 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2000 DB << NameInfo.getName() << RD; 2001 2002 if (!ThisType.isNull()) { 2003 DB << FixItHint::CreateInsertion(Loc, "this->"); 2004 return CXXDependentScopeMemberExpr::Create( 2005 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2006 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2007 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2008 } 2009 2010 // Synthesize a fake NNS that points to the derived class. This will 2011 // perform name lookup during template instantiation. 2012 CXXScopeSpec SS; 2013 auto *NNS = 2014 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2015 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2016 return DependentScopeDeclRefExpr::Create( 2017 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2018 TemplateArgs); 2019 } 2020 2021 ExprResult 2022 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2023 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2024 bool HasTrailingLParen, bool IsAddressOfOperand, 2025 std::unique_ptr<CorrectionCandidateCallback> CCC, 2026 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2027 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2028 "cannot be direct & operand and have a trailing lparen"); 2029 if (SS.isInvalid()) 2030 return ExprError(); 2031 2032 TemplateArgumentListInfo TemplateArgsBuffer; 2033 2034 // Decompose the UnqualifiedId into the following data. 2035 DeclarationNameInfo NameInfo; 2036 const TemplateArgumentListInfo *TemplateArgs; 2037 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2038 2039 DeclarationName Name = NameInfo.getName(); 2040 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2041 SourceLocation NameLoc = NameInfo.getLoc(); 2042 2043 if (II && II->isEditorPlaceholder()) { 2044 // FIXME: When typed placeholders are supported we can create a typed 2045 // placeholder expression node. 2046 return ExprError(); 2047 } 2048 2049 // C++ [temp.dep.expr]p3: 2050 // An id-expression is type-dependent if it contains: 2051 // -- an identifier that was declared with a dependent type, 2052 // (note: handled after lookup) 2053 // -- a template-id that is dependent, 2054 // (note: handled in BuildTemplateIdExpr) 2055 // -- a conversion-function-id that specifies a dependent type, 2056 // -- a nested-name-specifier that contains a class-name that 2057 // names a dependent type. 2058 // Determine whether this is a member of an unknown specialization; 2059 // we need to handle these differently. 2060 bool DependentID = false; 2061 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2062 Name.getCXXNameType()->isDependentType()) { 2063 DependentID = true; 2064 } else if (SS.isSet()) { 2065 if (DeclContext *DC = computeDeclContext(SS, false)) { 2066 if (RequireCompleteDeclContext(SS, DC)) 2067 return ExprError(); 2068 } else { 2069 DependentID = true; 2070 } 2071 } 2072 2073 if (DependentID) 2074 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2075 IsAddressOfOperand, TemplateArgs); 2076 2077 // Perform the required lookup. 2078 LookupResult R(*this, NameInfo, 2079 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2080 ? LookupObjCImplicitSelfParam 2081 : LookupOrdinaryName); 2082 if (TemplateKWLoc.isValid() || TemplateArgs) { 2083 // Lookup the template name again to correctly establish the context in 2084 // which it was found. This is really unfortunate as we already did the 2085 // lookup to determine that it was a template name in the first place. If 2086 // this becomes a performance hit, we can work harder to preserve those 2087 // results until we get here but it's likely not worth it. 2088 bool MemberOfUnknownSpecialization; 2089 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2090 MemberOfUnknownSpecialization, TemplateKWLoc)) 2091 return ExprError(); 2092 2093 if (MemberOfUnknownSpecialization || 2094 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2095 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2096 IsAddressOfOperand, TemplateArgs); 2097 } else { 2098 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2099 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2100 2101 // If the result might be in a dependent base class, this is a dependent 2102 // id-expression. 2103 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2104 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2105 IsAddressOfOperand, TemplateArgs); 2106 2107 // If this reference is in an Objective-C method, then we need to do 2108 // some special Objective-C lookup, too. 2109 if (IvarLookupFollowUp) { 2110 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2111 if (E.isInvalid()) 2112 return ExprError(); 2113 2114 if (Expr *Ex = E.getAs<Expr>()) 2115 return Ex; 2116 } 2117 } 2118 2119 if (R.isAmbiguous()) 2120 return ExprError(); 2121 2122 // This could be an implicitly declared function reference (legal in C90, 2123 // extension in C99, forbidden in C++). 2124 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2125 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2126 if (D) R.addDecl(D); 2127 } 2128 2129 // Determine whether this name might be a candidate for 2130 // argument-dependent lookup. 2131 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2132 2133 if (R.empty() && !ADL) { 2134 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2135 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2136 TemplateKWLoc, TemplateArgs)) 2137 return E; 2138 } 2139 2140 // Don't diagnose an empty lookup for inline assembly. 2141 if (IsInlineAsmIdentifier) 2142 return ExprError(); 2143 2144 // If this name wasn't predeclared and if this is not a function 2145 // call, diagnose the problem. 2146 TypoExpr *TE = nullptr; 2147 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2148 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2149 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2150 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2151 "Typo correction callback misconfigured"); 2152 if (CCC) { 2153 // Make sure the callback knows what the typo being diagnosed is. 2154 CCC->setTypoName(II); 2155 if (SS.isValid()) 2156 CCC->setTypoNNS(SS.getScopeRep()); 2157 } 2158 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2159 // a template name, but we happen to have always already looked up the name 2160 // before we get here if it must be a template name. 2161 if (DiagnoseEmptyLookup(S, SS, R, 2162 CCC ? std::move(CCC) : std::move(DefaultValidator), 2163 nullptr, None, &TE)) { 2164 if (TE && KeywordReplacement) { 2165 auto &State = getTypoExprState(TE); 2166 auto BestTC = State.Consumer->getNextCorrection(); 2167 if (BestTC.isKeyword()) { 2168 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2169 if (State.DiagHandler) 2170 State.DiagHandler(BestTC); 2171 KeywordReplacement->startToken(); 2172 KeywordReplacement->setKind(II->getTokenID()); 2173 KeywordReplacement->setIdentifierInfo(II); 2174 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2175 // Clean up the state associated with the TypoExpr, since it has 2176 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2177 clearDelayedTypo(TE); 2178 // Signal that a correction to a keyword was performed by returning a 2179 // valid-but-null ExprResult. 2180 return (Expr*)nullptr; 2181 } 2182 State.Consumer->resetCorrectionStream(); 2183 } 2184 return TE ? TE : ExprError(); 2185 } 2186 2187 assert(!R.empty() && 2188 "DiagnoseEmptyLookup returned false but added no results"); 2189 2190 // If we found an Objective-C instance variable, let 2191 // LookupInObjCMethod build the appropriate expression to 2192 // reference the ivar. 2193 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2194 R.clear(); 2195 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2196 // In a hopelessly buggy code, Objective-C instance variable 2197 // lookup fails and no expression will be built to reference it. 2198 if (!E.isInvalid() && !E.get()) 2199 return ExprError(); 2200 return E; 2201 } 2202 } 2203 2204 // This is guaranteed from this point on. 2205 assert(!R.empty() || ADL); 2206 2207 // Check whether this might be a C++ implicit instance member access. 2208 // C++ [class.mfct.non-static]p3: 2209 // When an id-expression that is not part of a class member access 2210 // syntax and not used to form a pointer to member is used in the 2211 // body of a non-static member function of class X, if name lookup 2212 // resolves the name in the id-expression to a non-static non-type 2213 // member of some class C, the id-expression is transformed into a 2214 // class member access expression using (*this) as the 2215 // postfix-expression to the left of the . operator. 2216 // 2217 // But we don't actually need to do this for '&' operands if R 2218 // resolved to a function or overloaded function set, because the 2219 // expression is ill-formed if it actually works out to be a 2220 // non-static member function: 2221 // 2222 // C++ [expr.ref]p4: 2223 // Otherwise, if E1.E2 refers to a non-static member function. . . 2224 // [t]he expression can be used only as the left-hand operand of a 2225 // member function call. 2226 // 2227 // There are other safeguards against such uses, but it's important 2228 // to get this right here so that we don't end up making a 2229 // spuriously dependent expression if we're inside a dependent 2230 // instance method. 2231 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2232 bool MightBeImplicitMember; 2233 if (!IsAddressOfOperand) 2234 MightBeImplicitMember = true; 2235 else if (!SS.isEmpty()) 2236 MightBeImplicitMember = false; 2237 else if (R.isOverloadedResult()) 2238 MightBeImplicitMember = false; 2239 else if (R.isUnresolvableResult()) 2240 MightBeImplicitMember = true; 2241 else 2242 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2243 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2244 isa<MSPropertyDecl>(R.getFoundDecl()); 2245 2246 if (MightBeImplicitMember) 2247 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2248 R, TemplateArgs, S); 2249 } 2250 2251 if (TemplateArgs || TemplateKWLoc.isValid()) { 2252 2253 // In C++1y, if this is a variable template id, then check it 2254 // in BuildTemplateIdExpr(). 2255 // The single lookup result must be a variable template declaration. 2256 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2257 Id.TemplateId->Kind == TNK_Var_template) { 2258 assert(R.getAsSingle<VarTemplateDecl>() && 2259 "There should only be one declaration found."); 2260 } 2261 2262 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2263 } 2264 2265 return BuildDeclarationNameExpr(SS, R, ADL); 2266 } 2267 2268 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2269 /// declaration name, generally during template instantiation. 2270 /// There's a large number of things which don't need to be done along 2271 /// this path. 2272 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2273 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2274 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2275 DeclContext *DC = computeDeclContext(SS, false); 2276 if (!DC) 2277 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2278 NameInfo, /*TemplateArgs=*/nullptr); 2279 2280 if (RequireCompleteDeclContext(SS, DC)) 2281 return ExprError(); 2282 2283 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2284 LookupQualifiedName(R, DC); 2285 2286 if (R.isAmbiguous()) 2287 return ExprError(); 2288 2289 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2290 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2291 NameInfo, /*TemplateArgs=*/nullptr); 2292 2293 if (R.empty()) { 2294 Diag(NameInfo.getLoc(), diag::err_no_member) 2295 << NameInfo.getName() << DC << SS.getRange(); 2296 return ExprError(); 2297 } 2298 2299 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2300 // Diagnose a missing typename if this resolved unambiguously to a type in 2301 // a dependent context. If we can recover with a type, downgrade this to 2302 // a warning in Microsoft compatibility mode. 2303 unsigned DiagID = diag::err_typename_missing; 2304 if (RecoveryTSI && getLangOpts().MSVCCompat) 2305 DiagID = diag::ext_typename_missing; 2306 SourceLocation Loc = SS.getBeginLoc(); 2307 auto D = Diag(Loc, DiagID); 2308 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2309 << SourceRange(Loc, NameInfo.getEndLoc()); 2310 2311 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2312 // context. 2313 if (!RecoveryTSI) 2314 return ExprError(); 2315 2316 // Only issue the fixit if we're prepared to recover. 2317 D << FixItHint::CreateInsertion(Loc, "typename "); 2318 2319 // Recover by pretending this was an elaborated type. 2320 QualType Ty = Context.getTypeDeclType(TD); 2321 TypeLocBuilder TLB; 2322 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2323 2324 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2325 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2326 QTL.setElaboratedKeywordLoc(SourceLocation()); 2327 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2328 2329 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2330 2331 return ExprEmpty(); 2332 } 2333 2334 // Defend against this resolving to an implicit member access. We usually 2335 // won't get here if this might be a legitimate a class member (we end up in 2336 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2337 // a pointer-to-member or in an unevaluated context in C++11. 2338 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2339 return BuildPossibleImplicitMemberExpr(SS, 2340 /*TemplateKWLoc=*/SourceLocation(), 2341 R, /*TemplateArgs=*/nullptr, S); 2342 2343 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2344 } 2345 2346 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2347 /// detected that we're currently inside an ObjC method. Perform some 2348 /// additional lookup. 2349 /// 2350 /// Ideally, most of this would be done by lookup, but there's 2351 /// actually quite a lot of extra work involved. 2352 /// 2353 /// Returns a null sentinel to indicate trivial success. 2354 ExprResult 2355 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2356 IdentifierInfo *II, bool AllowBuiltinCreation) { 2357 SourceLocation Loc = Lookup.getNameLoc(); 2358 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2359 2360 // Check for error condition which is already reported. 2361 if (!CurMethod) 2362 return ExprError(); 2363 2364 // There are two cases to handle here. 1) scoped lookup could have failed, 2365 // in which case we should look for an ivar. 2) scoped lookup could have 2366 // found a decl, but that decl is outside the current instance method (i.e. 2367 // a global variable). In these two cases, we do a lookup for an ivar with 2368 // this name, if the lookup sucedes, we replace it our current decl. 2369 2370 // If we're in a class method, we don't normally want to look for 2371 // ivars. But if we don't find anything else, and there's an 2372 // ivar, that's an error. 2373 bool IsClassMethod = CurMethod->isClassMethod(); 2374 2375 bool LookForIvars; 2376 if (Lookup.empty()) 2377 LookForIvars = true; 2378 else if (IsClassMethod) 2379 LookForIvars = false; 2380 else 2381 LookForIvars = (Lookup.isSingleResult() && 2382 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2383 ObjCInterfaceDecl *IFace = nullptr; 2384 if (LookForIvars) { 2385 IFace = CurMethod->getClassInterface(); 2386 ObjCInterfaceDecl *ClassDeclared; 2387 ObjCIvarDecl *IV = nullptr; 2388 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2389 // Diagnose using an ivar in a class method. 2390 if (IsClassMethod) 2391 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2392 << IV->getDeclName()); 2393 2394 // If we're referencing an invalid decl, just return this as a silent 2395 // error node. The error diagnostic was already emitted on the decl. 2396 if (IV->isInvalidDecl()) 2397 return ExprError(); 2398 2399 // Check if referencing a field with __attribute__((deprecated)). 2400 if (DiagnoseUseOfDecl(IV, Loc)) 2401 return ExprError(); 2402 2403 // Diagnose the use of an ivar outside of the declaring class. 2404 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2405 !declaresSameEntity(ClassDeclared, IFace) && 2406 !getLangOpts().DebuggerSupport) 2407 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2408 2409 // FIXME: This should use a new expr for a direct reference, don't 2410 // turn this into Self->ivar, just return a BareIVarExpr or something. 2411 IdentifierInfo &II = Context.Idents.get("self"); 2412 UnqualifiedId SelfName; 2413 SelfName.setIdentifier(&II, SourceLocation()); 2414 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2415 CXXScopeSpec SelfScopeSpec; 2416 SourceLocation TemplateKWLoc; 2417 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2418 SelfName, false, false); 2419 if (SelfExpr.isInvalid()) 2420 return ExprError(); 2421 2422 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2423 if (SelfExpr.isInvalid()) 2424 return ExprError(); 2425 2426 MarkAnyDeclReferenced(Loc, IV, true); 2427 2428 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2429 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2430 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2431 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2432 2433 ObjCIvarRefExpr *Result = new (Context) 2434 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2435 IV->getLocation(), SelfExpr.get(), true, true); 2436 2437 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2438 if (!isUnevaluatedContext() && 2439 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2440 getCurFunction()->recordUseOfWeak(Result); 2441 } 2442 if (getLangOpts().ObjCAutoRefCount) { 2443 if (CurContext->isClosure()) 2444 Diag(Loc, diag::warn_implicitly_retains_self) 2445 << FixItHint::CreateInsertion(Loc, "self->"); 2446 } 2447 2448 return Result; 2449 } 2450 } else if (CurMethod->isInstanceMethod()) { 2451 // We should warn if a local variable hides an ivar. 2452 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2453 ObjCInterfaceDecl *ClassDeclared; 2454 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2455 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2456 declaresSameEntity(IFace, ClassDeclared)) 2457 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2458 } 2459 } 2460 } else if (Lookup.isSingleResult() && 2461 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2462 // If accessing a stand-alone ivar in a class method, this is an error. 2463 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2464 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2465 << IV->getDeclName()); 2466 } 2467 2468 if (Lookup.empty() && II && AllowBuiltinCreation) { 2469 // FIXME. Consolidate this with similar code in LookupName. 2470 if (unsigned BuiltinID = II->getBuiltinID()) { 2471 if (!(getLangOpts().CPlusPlus && 2472 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2473 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2474 S, Lookup.isForRedeclaration(), 2475 Lookup.getNameLoc()); 2476 if (D) Lookup.addDecl(D); 2477 } 2478 } 2479 } 2480 // Sentinel value saying that we didn't do anything special. 2481 return ExprResult((Expr *)nullptr); 2482 } 2483 2484 /// Cast a base object to a member's actual type. 2485 /// 2486 /// Logically this happens in three phases: 2487 /// 2488 /// * First we cast from the base type to the naming class. 2489 /// The naming class is the class into which we were looking 2490 /// when we found the member; it's the qualifier type if a 2491 /// qualifier was provided, and otherwise it's the base type. 2492 /// 2493 /// * Next we cast from the naming class to the declaring class. 2494 /// If the member we found was brought into a class's scope by 2495 /// a using declaration, this is that class; otherwise it's 2496 /// the class declaring the member. 2497 /// 2498 /// * Finally we cast from the declaring class to the "true" 2499 /// declaring class of the member. This conversion does not 2500 /// obey access control. 2501 ExprResult 2502 Sema::PerformObjectMemberConversion(Expr *From, 2503 NestedNameSpecifier *Qualifier, 2504 NamedDecl *FoundDecl, 2505 NamedDecl *Member) { 2506 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2507 if (!RD) 2508 return From; 2509 2510 QualType DestRecordType; 2511 QualType DestType; 2512 QualType FromRecordType; 2513 QualType FromType = From->getType(); 2514 bool PointerConversions = false; 2515 if (isa<FieldDecl>(Member)) { 2516 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2517 2518 if (FromType->getAs<PointerType>()) { 2519 DestType = Context.getPointerType(DestRecordType); 2520 FromRecordType = FromType->getPointeeType(); 2521 PointerConversions = true; 2522 } else { 2523 DestType = DestRecordType; 2524 FromRecordType = FromType; 2525 } 2526 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2527 if (Method->isStatic()) 2528 return From; 2529 2530 DestType = Method->getThisType(Context); 2531 DestRecordType = DestType->getPointeeType(); 2532 2533 if (FromType->getAs<PointerType>()) { 2534 FromRecordType = FromType->getPointeeType(); 2535 PointerConversions = true; 2536 } else { 2537 FromRecordType = FromType; 2538 DestType = DestRecordType; 2539 } 2540 } else { 2541 // No conversion necessary. 2542 return From; 2543 } 2544 2545 if (DestType->isDependentType() || FromType->isDependentType()) 2546 return From; 2547 2548 // If the unqualified types are the same, no conversion is necessary. 2549 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2550 return From; 2551 2552 SourceRange FromRange = From->getSourceRange(); 2553 SourceLocation FromLoc = FromRange.getBegin(); 2554 2555 ExprValueKind VK = From->getValueKind(); 2556 2557 // C++ [class.member.lookup]p8: 2558 // [...] Ambiguities can often be resolved by qualifying a name with its 2559 // class name. 2560 // 2561 // If the member was a qualified name and the qualified referred to a 2562 // specific base subobject type, we'll cast to that intermediate type 2563 // first and then to the object in which the member is declared. That allows 2564 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2565 // 2566 // class Base { public: int x; }; 2567 // class Derived1 : public Base { }; 2568 // class Derived2 : public Base { }; 2569 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2570 // 2571 // void VeryDerived::f() { 2572 // x = 17; // error: ambiguous base subobjects 2573 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2574 // } 2575 if (Qualifier && Qualifier->getAsType()) { 2576 QualType QType = QualType(Qualifier->getAsType(), 0); 2577 assert(QType->isRecordType() && "lookup done with non-record type"); 2578 2579 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2580 2581 // In C++98, the qualifier type doesn't actually have to be a base 2582 // type of the object type, in which case we just ignore it. 2583 // Otherwise build the appropriate casts. 2584 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2585 CXXCastPath BasePath; 2586 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2587 FromLoc, FromRange, &BasePath)) 2588 return ExprError(); 2589 2590 if (PointerConversions) 2591 QType = Context.getPointerType(QType); 2592 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2593 VK, &BasePath).get(); 2594 2595 FromType = QType; 2596 FromRecordType = QRecordType; 2597 2598 // If the qualifier type was the same as the destination type, 2599 // we're done. 2600 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2601 return From; 2602 } 2603 } 2604 2605 bool IgnoreAccess = false; 2606 2607 // If we actually found the member through a using declaration, cast 2608 // down to the using declaration's type. 2609 // 2610 // Pointer equality is fine here because only one declaration of a 2611 // class ever has member declarations. 2612 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2613 assert(isa<UsingShadowDecl>(FoundDecl)); 2614 QualType URecordType = Context.getTypeDeclType( 2615 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2616 2617 // We only need to do this if the naming-class to declaring-class 2618 // conversion is non-trivial. 2619 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2620 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2621 CXXCastPath BasePath; 2622 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2623 FromLoc, FromRange, &BasePath)) 2624 return ExprError(); 2625 2626 QualType UType = URecordType; 2627 if (PointerConversions) 2628 UType = Context.getPointerType(UType); 2629 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2630 VK, &BasePath).get(); 2631 FromType = UType; 2632 FromRecordType = URecordType; 2633 } 2634 2635 // We don't do access control for the conversion from the 2636 // declaring class to the true declaring class. 2637 IgnoreAccess = true; 2638 } 2639 2640 CXXCastPath BasePath; 2641 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2642 FromLoc, FromRange, &BasePath, 2643 IgnoreAccess)) 2644 return ExprError(); 2645 2646 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2647 VK, &BasePath); 2648 } 2649 2650 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2651 const LookupResult &R, 2652 bool HasTrailingLParen) { 2653 // Only when used directly as the postfix-expression of a call. 2654 if (!HasTrailingLParen) 2655 return false; 2656 2657 // Never if a scope specifier was provided. 2658 if (SS.isSet()) 2659 return false; 2660 2661 // Only in C++ or ObjC++. 2662 if (!getLangOpts().CPlusPlus) 2663 return false; 2664 2665 // Turn off ADL when we find certain kinds of declarations during 2666 // normal lookup: 2667 for (NamedDecl *D : R) { 2668 // C++0x [basic.lookup.argdep]p3: 2669 // -- a declaration of a class member 2670 // Since using decls preserve this property, we check this on the 2671 // original decl. 2672 if (D->isCXXClassMember()) 2673 return false; 2674 2675 // C++0x [basic.lookup.argdep]p3: 2676 // -- a block-scope function declaration that is not a 2677 // using-declaration 2678 // NOTE: we also trigger this for function templates (in fact, we 2679 // don't check the decl type at all, since all other decl types 2680 // turn off ADL anyway). 2681 if (isa<UsingShadowDecl>(D)) 2682 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2683 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2684 return false; 2685 2686 // C++0x [basic.lookup.argdep]p3: 2687 // -- a declaration that is neither a function or a function 2688 // template 2689 // And also for builtin functions. 2690 if (isa<FunctionDecl>(D)) { 2691 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2692 2693 // But also builtin functions. 2694 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2695 return false; 2696 } else if (!isa<FunctionTemplateDecl>(D)) 2697 return false; 2698 } 2699 2700 return true; 2701 } 2702 2703 2704 /// Diagnoses obvious problems with the use of the given declaration 2705 /// as an expression. This is only actually called for lookups that 2706 /// were not overloaded, and it doesn't promise that the declaration 2707 /// will in fact be used. 2708 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2709 if (D->isInvalidDecl()) 2710 return true; 2711 2712 if (isa<TypedefNameDecl>(D)) { 2713 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2714 return true; 2715 } 2716 2717 if (isa<ObjCInterfaceDecl>(D)) { 2718 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2719 return true; 2720 } 2721 2722 if (isa<NamespaceDecl>(D)) { 2723 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2724 return true; 2725 } 2726 2727 return false; 2728 } 2729 2730 // Certain multiversion types should be treated as overloaded even when there is 2731 // only one result. 2732 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 2733 assert(R.isSingleResult() && "Expected only a single result"); 2734 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 2735 return FD && 2736 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 2737 } 2738 2739 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2740 LookupResult &R, bool NeedsADL, 2741 bool AcceptInvalidDecl) { 2742 // If this is a single, fully-resolved result and we don't need ADL, 2743 // just build an ordinary singleton decl ref. 2744 if (!NeedsADL && R.isSingleResult() && 2745 !R.getAsSingle<FunctionTemplateDecl>() && 2746 !ShouldLookupResultBeMultiVersionOverload(R)) 2747 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2748 R.getRepresentativeDecl(), nullptr, 2749 AcceptInvalidDecl); 2750 2751 // We only need to check the declaration if there's exactly one 2752 // result, because in the overloaded case the results can only be 2753 // functions and function templates. 2754 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 2755 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2756 return ExprError(); 2757 2758 // Otherwise, just build an unresolved lookup expression. Suppress 2759 // any lookup-related diagnostics; we'll hash these out later, when 2760 // we've picked a target. 2761 R.suppressDiagnostics(); 2762 2763 UnresolvedLookupExpr *ULE 2764 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2765 SS.getWithLocInContext(Context), 2766 R.getLookupNameInfo(), 2767 NeedsADL, R.isOverloadedResult(), 2768 R.begin(), R.end()); 2769 2770 return ULE; 2771 } 2772 2773 static void 2774 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2775 ValueDecl *var, DeclContext *DC); 2776 2777 /// Complete semantic analysis for a reference to the given declaration. 2778 ExprResult Sema::BuildDeclarationNameExpr( 2779 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2780 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2781 bool AcceptInvalidDecl) { 2782 assert(D && "Cannot refer to a NULL declaration"); 2783 assert(!isa<FunctionTemplateDecl>(D) && 2784 "Cannot refer unambiguously to a function template"); 2785 2786 SourceLocation Loc = NameInfo.getLoc(); 2787 if (CheckDeclInExpr(*this, Loc, D)) 2788 return ExprError(); 2789 2790 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2791 // Specifically diagnose references to class templates that are missing 2792 // a template argument list. 2793 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 2794 return ExprError(); 2795 } 2796 2797 // Make sure that we're referring to a value. 2798 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2799 if (!VD) { 2800 Diag(Loc, diag::err_ref_non_value) 2801 << D << SS.getRange(); 2802 Diag(D->getLocation(), diag::note_declared_at); 2803 return ExprError(); 2804 } 2805 2806 // Check whether this declaration can be used. Note that we suppress 2807 // this check when we're going to perform argument-dependent lookup 2808 // on this function name, because this might not be the function 2809 // that overload resolution actually selects. 2810 if (DiagnoseUseOfDecl(VD, Loc)) 2811 return ExprError(); 2812 2813 // Only create DeclRefExpr's for valid Decl's. 2814 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2815 return ExprError(); 2816 2817 // Handle members of anonymous structs and unions. If we got here, 2818 // and the reference is to a class member indirect field, then this 2819 // must be the subject of a pointer-to-member expression. 2820 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2821 if (!indirectField->isCXXClassMember()) 2822 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2823 indirectField); 2824 2825 { 2826 QualType type = VD->getType(); 2827 if (type.isNull()) 2828 return ExprError(); 2829 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2830 // C++ [except.spec]p17: 2831 // An exception-specification is considered to be needed when: 2832 // - in an expression, the function is the unique lookup result or 2833 // the selected member of a set of overloaded functions. 2834 ResolveExceptionSpec(Loc, FPT); 2835 type = VD->getType(); 2836 } 2837 ExprValueKind valueKind = VK_RValue; 2838 2839 switch (D->getKind()) { 2840 // Ignore all the non-ValueDecl kinds. 2841 #define ABSTRACT_DECL(kind) 2842 #define VALUE(type, base) 2843 #define DECL(type, base) \ 2844 case Decl::type: 2845 #include "clang/AST/DeclNodes.inc" 2846 llvm_unreachable("invalid value decl kind"); 2847 2848 // These shouldn't make it here. 2849 case Decl::ObjCAtDefsField: 2850 case Decl::ObjCIvar: 2851 llvm_unreachable("forming non-member reference to ivar?"); 2852 2853 // Enum constants are always r-values and never references. 2854 // Unresolved using declarations are dependent. 2855 case Decl::EnumConstant: 2856 case Decl::UnresolvedUsingValue: 2857 case Decl::OMPDeclareReduction: 2858 valueKind = VK_RValue; 2859 break; 2860 2861 // Fields and indirect fields that got here must be for 2862 // pointer-to-member expressions; we just call them l-values for 2863 // internal consistency, because this subexpression doesn't really 2864 // exist in the high-level semantics. 2865 case Decl::Field: 2866 case Decl::IndirectField: 2867 assert(getLangOpts().CPlusPlus && 2868 "building reference to field in C?"); 2869 2870 // These can't have reference type in well-formed programs, but 2871 // for internal consistency we do this anyway. 2872 type = type.getNonReferenceType(); 2873 valueKind = VK_LValue; 2874 break; 2875 2876 // Non-type template parameters are either l-values or r-values 2877 // depending on the type. 2878 case Decl::NonTypeTemplateParm: { 2879 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2880 type = reftype->getPointeeType(); 2881 valueKind = VK_LValue; // even if the parameter is an r-value reference 2882 break; 2883 } 2884 2885 // For non-references, we need to strip qualifiers just in case 2886 // the template parameter was declared as 'const int' or whatever. 2887 valueKind = VK_RValue; 2888 type = type.getUnqualifiedType(); 2889 break; 2890 } 2891 2892 case Decl::Var: 2893 case Decl::VarTemplateSpecialization: 2894 case Decl::VarTemplatePartialSpecialization: 2895 case Decl::Decomposition: 2896 case Decl::OMPCapturedExpr: 2897 // In C, "extern void blah;" is valid and is an r-value. 2898 if (!getLangOpts().CPlusPlus && 2899 !type.hasQualifiers() && 2900 type->isVoidType()) { 2901 valueKind = VK_RValue; 2902 break; 2903 } 2904 LLVM_FALLTHROUGH; 2905 2906 case Decl::ImplicitParam: 2907 case Decl::ParmVar: { 2908 // These are always l-values. 2909 valueKind = VK_LValue; 2910 type = type.getNonReferenceType(); 2911 2912 // FIXME: Does the addition of const really only apply in 2913 // potentially-evaluated contexts? Since the variable isn't actually 2914 // captured in an unevaluated context, it seems that the answer is no. 2915 if (!isUnevaluatedContext()) { 2916 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2917 if (!CapturedType.isNull()) 2918 type = CapturedType; 2919 } 2920 2921 break; 2922 } 2923 2924 case Decl::Binding: { 2925 // These are always lvalues. 2926 valueKind = VK_LValue; 2927 type = type.getNonReferenceType(); 2928 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2929 // decides how that's supposed to work. 2930 auto *BD = cast<BindingDecl>(VD); 2931 if (BD->getDeclContext()->isFunctionOrMethod() && 2932 BD->getDeclContext() != CurContext) 2933 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2934 break; 2935 } 2936 2937 case Decl::Function: { 2938 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2939 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2940 type = Context.BuiltinFnTy; 2941 valueKind = VK_RValue; 2942 break; 2943 } 2944 } 2945 2946 const FunctionType *fty = type->castAs<FunctionType>(); 2947 2948 // If we're referring to a function with an __unknown_anytype 2949 // result type, make the entire expression __unknown_anytype. 2950 if (fty->getReturnType() == Context.UnknownAnyTy) { 2951 type = Context.UnknownAnyTy; 2952 valueKind = VK_RValue; 2953 break; 2954 } 2955 2956 // Functions are l-values in C++. 2957 if (getLangOpts().CPlusPlus) { 2958 valueKind = VK_LValue; 2959 break; 2960 } 2961 2962 // C99 DR 316 says that, if a function type comes from a 2963 // function definition (without a prototype), that type is only 2964 // used for checking compatibility. Therefore, when referencing 2965 // the function, we pretend that we don't have the full function 2966 // type. 2967 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2968 isa<FunctionProtoType>(fty)) 2969 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2970 fty->getExtInfo()); 2971 2972 // Functions are r-values in C. 2973 valueKind = VK_RValue; 2974 break; 2975 } 2976 2977 case Decl::CXXDeductionGuide: 2978 llvm_unreachable("building reference to deduction guide"); 2979 2980 case Decl::MSProperty: 2981 valueKind = VK_LValue; 2982 break; 2983 2984 case Decl::CXXMethod: 2985 // If we're referring to a method with an __unknown_anytype 2986 // result type, make the entire expression __unknown_anytype. 2987 // This should only be possible with a type written directly. 2988 if (const FunctionProtoType *proto 2989 = dyn_cast<FunctionProtoType>(VD->getType())) 2990 if (proto->getReturnType() == Context.UnknownAnyTy) { 2991 type = Context.UnknownAnyTy; 2992 valueKind = VK_RValue; 2993 break; 2994 } 2995 2996 // C++ methods are l-values if static, r-values if non-static. 2997 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2998 valueKind = VK_LValue; 2999 break; 3000 } 3001 LLVM_FALLTHROUGH; 3002 3003 case Decl::CXXConversion: 3004 case Decl::CXXDestructor: 3005 case Decl::CXXConstructor: 3006 valueKind = VK_RValue; 3007 break; 3008 } 3009 3010 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3011 TemplateArgs); 3012 } 3013 } 3014 3015 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3016 SmallString<32> &Target) { 3017 Target.resize(CharByteWidth * (Source.size() + 1)); 3018 char *ResultPtr = &Target[0]; 3019 const llvm::UTF8 *ErrorPtr; 3020 bool success = 3021 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3022 (void)success; 3023 assert(success); 3024 Target.resize(ResultPtr - &Target[0]); 3025 } 3026 3027 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3028 PredefinedExpr::IdentType IT) { 3029 // Pick the current block, lambda, captured statement or function. 3030 Decl *currentDecl = nullptr; 3031 if (const BlockScopeInfo *BSI = getCurBlock()) 3032 currentDecl = BSI->TheDecl; 3033 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3034 currentDecl = LSI->CallOperator; 3035 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3036 currentDecl = CSI->TheCapturedDecl; 3037 else 3038 currentDecl = getCurFunctionOrMethodDecl(); 3039 3040 if (!currentDecl) { 3041 Diag(Loc, diag::ext_predef_outside_function); 3042 currentDecl = Context.getTranslationUnitDecl(); 3043 } 3044 3045 QualType ResTy; 3046 StringLiteral *SL = nullptr; 3047 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3048 ResTy = Context.DependentTy; 3049 else { 3050 // Pre-defined identifiers are of type char[x], where x is the length of 3051 // the string. 3052 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3053 unsigned Length = Str.length(); 3054 3055 llvm::APInt LengthI(32, Length + 1); 3056 if (IT == PredefinedExpr::LFunction || IT == PredefinedExpr::LFuncSig) { 3057 ResTy = 3058 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3059 SmallString<32> RawChars; 3060 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3061 Str, RawChars); 3062 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3063 /*IndexTypeQuals*/ 0); 3064 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3065 /*Pascal*/ false, ResTy, Loc); 3066 } else { 3067 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3068 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3069 /*IndexTypeQuals*/ 0); 3070 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3071 /*Pascal*/ false, ResTy, Loc); 3072 } 3073 } 3074 3075 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3076 } 3077 3078 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3079 PredefinedExpr::IdentType IT; 3080 3081 switch (Kind) { 3082 default: llvm_unreachable("Unknown simple primary expr!"); 3083 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3084 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3085 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3086 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3087 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; // [MS] 3088 case tok::kw_L__FUNCSIG__: IT = PredefinedExpr::LFuncSig; break; // [MS] 3089 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3090 } 3091 3092 return BuildPredefinedExpr(Loc, IT); 3093 } 3094 3095 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3096 SmallString<16> CharBuffer; 3097 bool Invalid = false; 3098 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3099 if (Invalid) 3100 return ExprError(); 3101 3102 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3103 PP, Tok.getKind()); 3104 if (Literal.hadError()) 3105 return ExprError(); 3106 3107 QualType Ty; 3108 if (Literal.isWide()) 3109 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3110 else if (Literal.isUTF8() && getLangOpts().Char8) 3111 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3112 else if (Literal.isUTF16()) 3113 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3114 else if (Literal.isUTF32()) 3115 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3116 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3117 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3118 else 3119 Ty = Context.CharTy; // 'x' -> char in C++ 3120 3121 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3122 if (Literal.isWide()) 3123 Kind = CharacterLiteral::Wide; 3124 else if (Literal.isUTF16()) 3125 Kind = CharacterLiteral::UTF16; 3126 else if (Literal.isUTF32()) 3127 Kind = CharacterLiteral::UTF32; 3128 else if (Literal.isUTF8()) 3129 Kind = CharacterLiteral::UTF8; 3130 3131 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3132 Tok.getLocation()); 3133 3134 if (Literal.getUDSuffix().empty()) 3135 return Lit; 3136 3137 // We're building a user-defined literal. 3138 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3139 SourceLocation UDSuffixLoc = 3140 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3141 3142 // Make sure we're allowed user-defined literals here. 3143 if (!UDLScope) 3144 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3145 3146 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3147 // operator "" X (ch) 3148 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3149 Lit, Tok.getLocation()); 3150 } 3151 3152 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3153 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3154 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3155 Context.IntTy, Loc); 3156 } 3157 3158 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3159 QualType Ty, SourceLocation Loc) { 3160 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3161 3162 using llvm::APFloat; 3163 APFloat Val(Format); 3164 3165 APFloat::opStatus result = Literal.GetFloatValue(Val); 3166 3167 // Overflow is always an error, but underflow is only an error if 3168 // we underflowed to zero (APFloat reports denormals as underflow). 3169 if ((result & APFloat::opOverflow) || 3170 ((result & APFloat::opUnderflow) && Val.isZero())) { 3171 unsigned diagnostic; 3172 SmallString<20> buffer; 3173 if (result & APFloat::opOverflow) { 3174 diagnostic = diag::warn_float_overflow; 3175 APFloat::getLargest(Format).toString(buffer); 3176 } else { 3177 diagnostic = diag::warn_float_underflow; 3178 APFloat::getSmallest(Format).toString(buffer); 3179 } 3180 3181 S.Diag(Loc, diagnostic) 3182 << Ty 3183 << StringRef(buffer.data(), buffer.size()); 3184 } 3185 3186 bool isExact = (result == APFloat::opOK); 3187 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3188 } 3189 3190 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3191 assert(E && "Invalid expression"); 3192 3193 if (E->isValueDependent()) 3194 return false; 3195 3196 QualType QT = E->getType(); 3197 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3198 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3199 return true; 3200 } 3201 3202 llvm::APSInt ValueAPS; 3203 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3204 3205 if (R.isInvalid()) 3206 return true; 3207 3208 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3209 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3210 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3211 << ValueAPS.toString(10) << ValueIsPositive; 3212 return true; 3213 } 3214 3215 return false; 3216 } 3217 3218 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3219 // Fast path for a single digit (which is quite common). A single digit 3220 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3221 if (Tok.getLength() == 1) { 3222 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3223 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3224 } 3225 3226 SmallString<128> SpellingBuffer; 3227 // NumericLiteralParser wants to overread by one character. Add padding to 3228 // the buffer in case the token is copied to the buffer. If getSpelling() 3229 // returns a StringRef to the memory buffer, it should have a null char at 3230 // the EOF, so it is also safe. 3231 SpellingBuffer.resize(Tok.getLength() + 1); 3232 3233 // Get the spelling of the token, which eliminates trigraphs, etc. 3234 bool Invalid = false; 3235 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3236 if (Invalid) 3237 return ExprError(); 3238 3239 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3240 if (Literal.hadError) 3241 return ExprError(); 3242 3243 if (Literal.hasUDSuffix()) { 3244 // We're building a user-defined literal. 3245 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3246 SourceLocation UDSuffixLoc = 3247 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3248 3249 // Make sure we're allowed user-defined literals here. 3250 if (!UDLScope) 3251 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3252 3253 QualType CookedTy; 3254 if (Literal.isFloatingLiteral()) { 3255 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3256 // long double, the literal is treated as a call of the form 3257 // operator "" X (f L) 3258 CookedTy = Context.LongDoubleTy; 3259 } else { 3260 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3261 // unsigned long long, the literal is treated as a call of the form 3262 // operator "" X (n ULL) 3263 CookedTy = Context.UnsignedLongLongTy; 3264 } 3265 3266 DeclarationName OpName = 3267 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3268 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3269 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3270 3271 SourceLocation TokLoc = Tok.getLocation(); 3272 3273 // Perform literal operator lookup to determine if we're building a raw 3274 // literal or a cooked one. 3275 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3276 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3277 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3278 /*AllowStringTemplate*/ false, 3279 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3280 case LOLR_ErrorNoDiagnostic: 3281 // Lookup failure for imaginary constants isn't fatal, there's still the 3282 // GNU extension producing _Complex types. 3283 break; 3284 case LOLR_Error: 3285 return ExprError(); 3286 case LOLR_Cooked: { 3287 Expr *Lit; 3288 if (Literal.isFloatingLiteral()) { 3289 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3290 } else { 3291 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3292 if (Literal.GetIntegerValue(ResultVal)) 3293 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3294 << /* Unsigned */ 1; 3295 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3296 Tok.getLocation()); 3297 } 3298 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3299 } 3300 3301 case LOLR_Raw: { 3302 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3303 // literal is treated as a call of the form 3304 // operator "" X ("n") 3305 unsigned Length = Literal.getUDSuffixOffset(); 3306 QualType StrTy = Context.getConstantArrayType( 3307 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3308 llvm::APInt(32, Length + 1), ArrayType::Normal, 0); 3309 Expr *Lit = StringLiteral::Create( 3310 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3311 /*Pascal*/false, StrTy, &TokLoc, 1); 3312 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3313 } 3314 3315 case LOLR_Template: { 3316 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3317 // template), L is treated as a call fo the form 3318 // operator "" X <'c1', 'c2', ... 'ck'>() 3319 // where n is the source character sequence c1 c2 ... ck. 3320 TemplateArgumentListInfo ExplicitArgs; 3321 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3322 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3323 llvm::APSInt Value(CharBits, CharIsUnsigned); 3324 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3325 Value = TokSpelling[I]; 3326 TemplateArgument Arg(Context, Value, Context.CharTy); 3327 TemplateArgumentLocInfo ArgInfo; 3328 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3329 } 3330 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3331 &ExplicitArgs); 3332 } 3333 case LOLR_StringTemplate: 3334 llvm_unreachable("unexpected literal operator lookup result"); 3335 } 3336 } 3337 3338 Expr *Res; 3339 3340 if (Literal.isFixedPointLiteral()) { 3341 QualType Ty; 3342 3343 if (Literal.isAccum) { 3344 if (Literal.isHalf) { 3345 Ty = Context.ShortAccumTy; 3346 } else if (Literal.isLong) { 3347 Ty = Context.LongAccumTy; 3348 } else { 3349 Ty = Context.AccumTy; 3350 } 3351 } else if (Literal.isFract) { 3352 if (Literal.isHalf) { 3353 Ty = Context.ShortFractTy; 3354 } else if (Literal.isLong) { 3355 Ty = Context.LongFractTy; 3356 } else { 3357 Ty = Context.FractTy; 3358 } 3359 } 3360 3361 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3362 3363 bool isSigned = !Literal.isUnsigned; 3364 unsigned scale = Context.getFixedPointScale(Ty); 3365 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3366 3367 llvm::APInt Val(bit_width, 0, isSigned); 3368 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3369 bool ValIsZero = Val.isNullValue() && !Overflowed; 3370 3371 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3372 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3373 // Clause 6.4.4 - The value of a constant shall be in the range of 3374 // representable values for its type, with exception for constants of a 3375 // fract type with a value of exactly 1; such a constant shall denote 3376 // the maximal value for the type. 3377 --Val; 3378 else if (Val.ugt(MaxVal) || Overflowed) 3379 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3380 3381 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3382 Tok.getLocation(), scale); 3383 } else if (Literal.isFloatingLiteral()) { 3384 QualType Ty; 3385 if (Literal.isHalf){ 3386 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3387 Ty = Context.HalfTy; 3388 else { 3389 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3390 return ExprError(); 3391 } 3392 } else if (Literal.isFloat) 3393 Ty = Context.FloatTy; 3394 else if (Literal.isLong) 3395 Ty = Context.LongDoubleTy; 3396 else if (Literal.isFloat16) 3397 Ty = Context.Float16Ty; 3398 else if (Literal.isFloat128) 3399 Ty = Context.Float128Ty; 3400 else 3401 Ty = Context.DoubleTy; 3402 3403 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3404 3405 if (Ty == Context.DoubleTy) { 3406 if (getLangOpts().SinglePrecisionConstants) { 3407 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3408 if (BTy->getKind() != BuiltinType::Float) { 3409 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3410 } 3411 } else if (getLangOpts().OpenCL && 3412 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3413 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3414 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3415 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3416 } 3417 } 3418 } else if (!Literal.isIntegerLiteral()) { 3419 return ExprError(); 3420 } else { 3421 QualType Ty; 3422 3423 // 'long long' is a C99 or C++11 feature. 3424 if (!getLangOpts().C99 && Literal.isLongLong) { 3425 if (getLangOpts().CPlusPlus) 3426 Diag(Tok.getLocation(), 3427 getLangOpts().CPlusPlus11 ? 3428 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3429 else 3430 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3431 } 3432 3433 // Get the value in the widest-possible width. 3434 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3435 llvm::APInt ResultVal(MaxWidth, 0); 3436 3437 if (Literal.GetIntegerValue(ResultVal)) { 3438 // If this value didn't fit into uintmax_t, error and force to ull. 3439 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3440 << /* Unsigned */ 1; 3441 Ty = Context.UnsignedLongLongTy; 3442 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3443 "long long is not intmax_t?"); 3444 } else { 3445 // If this value fits into a ULL, try to figure out what else it fits into 3446 // according to the rules of C99 6.4.4.1p5. 3447 3448 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3449 // be an unsigned int. 3450 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3451 3452 // Check from smallest to largest, picking the smallest type we can. 3453 unsigned Width = 0; 3454 3455 // Microsoft specific integer suffixes are explicitly sized. 3456 if (Literal.MicrosoftInteger) { 3457 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3458 Width = 8; 3459 Ty = Context.CharTy; 3460 } else { 3461 Width = Literal.MicrosoftInteger; 3462 Ty = Context.getIntTypeForBitwidth(Width, 3463 /*Signed=*/!Literal.isUnsigned); 3464 } 3465 } 3466 3467 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3468 // Are int/unsigned possibilities? 3469 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3470 3471 // Does it fit in a unsigned int? 3472 if (ResultVal.isIntN(IntSize)) { 3473 // Does it fit in a signed int? 3474 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3475 Ty = Context.IntTy; 3476 else if (AllowUnsigned) 3477 Ty = Context.UnsignedIntTy; 3478 Width = IntSize; 3479 } 3480 } 3481 3482 // Are long/unsigned long possibilities? 3483 if (Ty.isNull() && !Literal.isLongLong) { 3484 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3485 3486 // Does it fit in a unsigned long? 3487 if (ResultVal.isIntN(LongSize)) { 3488 // Does it fit in a signed long? 3489 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3490 Ty = Context.LongTy; 3491 else if (AllowUnsigned) 3492 Ty = Context.UnsignedLongTy; 3493 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3494 // is compatible. 3495 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3496 const unsigned LongLongSize = 3497 Context.getTargetInfo().getLongLongWidth(); 3498 Diag(Tok.getLocation(), 3499 getLangOpts().CPlusPlus 3500 ? Literal.isLong 3501 ? diag::warn_old_implicitly_unsigned_long_cxx 3502 : /*C++98 UB*/ diag:: 3503 ext_old_implicitly_unsigned_long_cxx 3504 : diag::warn_old_implicitly_unsigned_long) 3505 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3506 : /*will be ill-formed*/ 1); 3507 Ty = Context.UnsignedLongTy; 3508 } 3509 Width = LongSize; 3510 } 3511 } 3512 3513 // Check long long if needed. 3514 if (Ty.isNull()) { 3515 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3516 3517 // Does it fit in a unsigned long long? 3518 if (ResultVal.isIntN(LongLongSize)) { 3519 // Does it fit in a signed long long? 3520 // To be compatible with MSVC, hex integer literals ending with the 3521 // LL or i64 suffix are always signed in Microsoft mode. 3522 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3523 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3524 Ty = Context.LongLongTy; 3525 else if (AllowUnsigned) 3526 Ty = Context.UnsignedLongLongTy; 3527 Width = LongLongSize; 3528 } 3529 } 3530 3531 // If we still couldn't decide a type, we probably have something that 3532 // does not fit in a signed long long, but has no U suffix. 3533 if (Ty.isNull()) { 3534 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3535 Ty = Context.UnsignedLongLongTy; 3536 Width = Context.getTargetInfo().getLongLongWidth(); 3537 } 3538 3539 if (ResultVal.getBitWidth() != Width) 3540 ResultVal = ResultVal.trunc(Width); 3541 } 3542 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3543 } 3544 3545 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3546 if (Literal.isImaginary) { 3547 Res = new (Context) ImaginaryLiteral(Res, 3548 Context.getComplexType(Res->getType())); 3549 3550 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3551 } 3552 return Res; 3553 } 3554 3555 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3556 assert(E && "ActOnParenExpr() missing expr"); 3557 return new (Context) ParenExpr(L, R, E); 3558 } 3559 3560 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3561 SourceLocation Loc, 3562 SourceRange ArgRange) { 3563 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3564 // scalar or vector data type argument..." 3565 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3566 // type (C99 6.2.5p18) or void. 3567 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3568 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3569 << T << ArgRange; 3570 return true; 3571 } 3572 3573 assert((T->isVoidType() || !T->isIncompleteType()) && 3574 "Scalar types should always be complete"); 3575 return false; 3576 } 3577 3578 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3579 SourceLocation Loc, 3580 SourceRange ArgRange, 3581 UnaryExprOrTypeTrait TraitKind) { 3582 // Invalid types must be hard errors for SFINAE in C++. 3583 if (S.LangOpts.CPlusPlus) 3584 return true; 3585 3586 // C99 6.5.3.4p1: 3587 if (T->isFunctionType() && 3588 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3589 // sizeof(function)/alignof(function) is allowed as an extension. 3590 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3591 << TraitKind << ArgRange; 3592 return false; 3593 } 3594 3595 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3596 // this is an error (OpenCL v1.1 s6.3.k) 3597 if (T->isVoidType()) { 3598 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3599 : diag::ext_sizeof_alignof_void_type; 3600 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3601 return false; 3602 } 3603 3604 return true; 3605 } 3606 3607 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3608 SourceLocation Loc, 3609 SourceRange ArgRange, 3610 UnaryExprOrTypeTrait TraitKind) { 3611 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3612 // runtime doesn't allow it. 3613 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3614 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3615 << T << (TraitKind == UETT_SizeOf) 3616 << ArgRange; 3617 return true; 3618 } 3619 3620 return false; 3621 } 3622 3623 /// Check whether E is a pointer from a decayed array type (the decayed 3624 /// pointer type is equal to T) and emit a warning if it is. 3625 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3626 Expr *E) { 3627 // Don't warn if the operation changed the type. 3628 if (T != E->getType()) 3629 return; 3630 3631 // Now look for array decays. 3632 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3633 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3634 return; 3635 3636 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3637 << ICE->getType() 3638 << ICE->getSubExpr()->getType(); 3639 } 3640 3641 /// Check the constraints on expression operands to unary type expression 3642 /// and type traits. 3643 /// 3644 /// Completes any types necessary and validates the constraints on the operand 3645 /// expression. The logic mostly mirrors the type-based overload, but may modify 3646 /// the expression as it completes the type for that expression through template 3647 /// instantiation, etc. 3648 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3649 UnaryExprOrTypeTrait ExprKind) { 3650 QualType ExprTy = E->getType(); 3651 assert(!ExprTy->isReferenceType()); 3652 3653 if (ExprKind == UETT_VecStep) 3654 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3655 E->getSourceRange()); 3656 3657 // Whitelist some types as extensions 3658 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3659 E->getSourceRange(), ExprKind)) 3660 return false; 3661 3662 // 'alignof' applied to an expression only requires the base element type of 3663 // the expression to be complete. 'sizeof' requires the expression's type to 3664 // be complete (and will attempt to complete it if it's an array of unknown 3665 // bound). 3666 if (ExprKind == UETT_AlignOf) { 3667 if (RequireCompleteType(E->getExprLoc(), 3668 Context.getBaseElementType(E->getType()), 3669 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3670 E->getSourceRange())) 3671 return true; 3672 } else { 3673 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3674 ExprKind, E->getSourceRange())) 3675 return true; 3676 } 3677 3678 // Completing the expression's type may have changed it. 3679 ExprTy = E->getType(); 3680 assert(!ExprTy->isReferenceType()); 3681 3682 if (ExprTy->isFunctionType()) { 3683 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3684 << ExprKind << E->getSourceRange(); 3685 return true; 3686 } 3687 3688 // The operand for sizeof and alignof is in an unevaluated expression context, 3689 // so side effects could result in unintended consequences. 3690 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3691 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3692 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3693 3694 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3695 E->getSourceRange(), ExprKind)) 3696 return true; 3697 3698 if (ExprKind == UETT_SizeOf) { 3699 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3700 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3701 QualType OType = PVD->getOriginalType(); 3702 QualType Type = PVD->getType(); 3703 if (Type->isPointerType() && OType->isArrayType()) { 3704 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3705 << Type << OType; 3706 Diag(PVD->getLocation(), diag::note_declared_at); 3707 } 3708 } 3709 } 3710 3711 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3712 // decays into a pointer and returns an unintended result. This is most 3713 // likely a typo for "sizeof(array) op x". 3714 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3715 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3716 BO->getLHS()); 3717 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3718 BO->getRHS()); 3719 } 3720 } 3721 3722 return false; 3723 } 3724 3725 /// Check the constraints on operands to unary expression and type 3726 /// traits. 3727 /// 3728 /// This will complete any types necessary, and validate the various constraints 3729 /// on those operands. 3730 /// 3731 /// The UsualUnaryConversions() function is *not* called by this routine. 3732 /// C99 6.3.2.1p[2-4] all state: 3733 /// Except when it is the operand of the sizeof operator ... 3734 /// 3735 /// C++ [expr.sizeof]p4 3736 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3737 /// standard conversions are not applied to the operand of sizeof. 3738 /// 3739 /// This policy is followed for all of the unary trait expressions. 3740 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3741 SourceLocation OpLoc, 3742 SourceRange ExprRange, 3743 UnaryExprOrTypeTrait ExprKind) { 3744 if (ExprType->isDependentType()) 3745 return false; 3746 3747 // C++ [expr.sizeof]p2: 3748 // When applied to a reference or a reference type, the result 3749 // is the size of the referenced type. 3750 // C++11 [expr.alignof]p3: 3751 // When alignof is applied to a reference type, the result 3752 // shall be the alignment of the referenced type. 3753 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3754 ExprType = Ref->getPointeeType(); 3755 3756 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3757 // When alignof or _Alignof is applied to an array type, the result 3758 // is the alignment of the element type. 3759 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3760 ExprType = Context.getBaseElementType(ExprType); 3761 3762 if (ExprKind == UETT_VecStep) 3763 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3764 3765 // Whitelist some types as extensions 3766 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3767 ExprKind)) 3768 return false; 3769 3770 if (RequireCompleteType(OpLoc, ExprType, 3771 diag::err_sizeof_alignof_incomplete_type, 3772 ExprKind, ExprRange)) 3773 return true; 3774 3775 if (ExprType->isFunctionType()) { 3776 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3777 << ExprKind << ExprRange; 3778 return true; 3779 } 3780 3781 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3782 ExprKind)) 3783 return true; 3784 3785 return false; 3786 } 3787 3788 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3789 E = E->IgnoreParens(); 3790 3791 // Cannot know anything else if the expression is dependent. 3792 if (E->isTypeDependent()) 3793 return false; 3794 3795 if (E->getObjectKind() == OK_BitField) { 3796 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3797 << 1 << E->getSourceRange(); 3798 return true; 3799 } 3800 3801 ValueDecl *D = nullptr; 3802 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3803 D = DRE->getDecl(); 3804 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3805 D = ME->getMemberDecl(); 3806 } 3807 3808 // If it's a field, require the containing struct to have a 3809 // complete definition so that we can compute the layout. 3810 // 3811 // This can happen in C++11 onwards, either by naming the member 3812 // in a way that is not transformed into a member access expression 3813 // (in an unevaluated operand, for instance), or by naming the member 3814 // in a trailing-return-type. 3815 // 3816 // For the record, since __alignof__ on expressions is a GCC 3817 // extension, GCC seems to permit this but always gives the 3818 // nonsensical answer 0. 3819 // 3820 // We don't really need the layout here --- we could instead just 3821 // directly check for all the appropriate alignment-lowing 3822 // attributes --- but that would require duplicating a lot of 3823 // logic that just isn't worth duplicating for such a marginal 3824 // use-case. 3825 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3826 // Fast path this check, since we at least know the record has a 3827 // definition if we can find a member of it. 3828 if (!FD->getParent()->isCompleteDefinition()) { 3829 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3830 << E->getSourceRange(); 3831 return true; 3832 } 3833 3834 // Otherwise, if it's a field, and the field doesn't have 3835 // reference type, then it must have a complete type (or be a 3836 // flexible array member, which we explicitly want to 3837 // white-list anyway), which makes the following checks trivial. 3838 if (!FD->getType()->isReferenceType()) 3839 return false; 3840 } 3841 3842 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3843 } 3844 3845 bool Sema::CheckVecStepExpr(Expr *E) { 3846 E = E->IgnoreParens(); 3847 3848 // Cannot know anything else if the expression is dependent. 3849 if (E->isTypeDependent()) 3850 return false; 3851 3852 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3853 } 3854 3855 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3856 CapturingScopeInfo *CSI) { 3857 assert(T->isVariablyModifiedType()); 3858 assert(CSI != nullptr); 3859 3860 // We're going to walk down into the type and look for VLA expressions. 3861 do { 3862 const Type *Ty = T.getTypePtr(); 3863 switch (Ty->getTypeClass()) { 3864 #define TYPE(Class, Base) 3865 #define ABSTRACT_TYPE(Class, Base) 3866 #define NON_CANONICAL_TYPE(Class, Base) 3867 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3868 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3869 #include "clang/AST/TypeNodes.def" 3870 T = QualType(); 3871 break; 3872 // These types are never variably-modified. 3873 case Type::Builtin: 3874 case Type::Complex: 3875 case Type::Vector: 3876 case Type::ExtVector: 3877 case Type::Record: 3878 case Type::Enum: 3879 case Type::Elaborated: 3880 case Type::TemplateSpecialization: 3881 case Type::ObjCObject: 3882 case Type::ObjCInterface: 3883 case Type::ObjCObjectPointer: 3884 case Type::ObjCTypeParam: 3885 case Type::Pipe: 3886 llvm_unreachable("type class is never variably-modified!"); 3887 case Type::Adjusted: 3888 T = cast<AdjustedType>(Ty)->getOriginalType(); 3889 break; 3890 case Type::Decayed: 3891 T = cast<DecayedType>(Ty)->getPointeeType(); 3892 break; 3893 case Type::Pointer: 3894 T = cast<PointerType>(Ty)->getPointeeType(); 3895 break; 3896 case Type::BlockPointer: 3897 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3898 break; 3899 case Type::LValueReference: 3900 case Type::RValueReference: 3901 T = cast<ReferenceType>(Ty)->getPointeeType(); 3902 break; 3903 case Type::MemberPointer: 3904 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3905 break; 3906 case Type::ConstantArray: 3907 case Type::IncompleteArray: 3908 // Losing element qualification here is fine. 3909 T = cast<ArrayType>(Ty)->getElementType(); 3910 break; 3911 case Type::VariableArray: { 3912 // Losing element qualification here is fine. 3913 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3914 3915 // Unknown size indication requires no size computation. 3916 // Otherwise, evaluate and record it. 3917 if (auto Size = VAT->getSizeExpr()) { 3918 if (!CSI->isVLATypeCaptured(VAT)) { 3919 RecordDecl *CapRecord = nullptr; 3920 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3921 CapRecord = LSI->Lambda; 3922 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3923 CapRecord = CRSI->TheRecordDecl; 3924 } 3925 if (CapRecord) { 3926 auto ExprLoc = Size->getExprLoc(); 3927 auto SizeType = Context.getSizeType(); 3928 // Build the non-static data member. 3929 auto Field = 3930 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3931 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3932 /*BW*/ nullptr, /*Mutable*/ false, 3933 /*InitStyle*/ ICIS_NoInit); 3934 Field->setImplicit(true); 3935 Field->setAccess(AS_private); 3936 Field->setCapturedVLAType(VAT); 3937 CapRecord->addDecl(Field); 3938 3939 CSI->addVLATypeCapture(ExprLoc, SizeType); 3940 } 3941 } 3942 } 3943 T = VAT->getElementType(); 3944 break; 3945 } 3946 case Type::FunctionProto: 3947 case Type::FunctionNoProto: 3948 T = cast<FunctionType>(Ty)->getReturnType(); 3949 break; 3950 case Type::Paren: 3951 case Type::TypeOf: 3952 case Type::UnaryTransform: 3953 case Type::Attributed: 3954 case Type::SubstTemplateTypeParm: 3955 case Type::PackExpansion: 3956 // Keep walking after single level desugaring. 3957 T = T.getSingleStepDesugaredType(Context); 3958 break; 3959 case Type::Typedef: 3960 T = cast<TypedefType>(Ty)->desugar(); 3961 break; 3962 case Type::Decltype: 3963 T = cast<DecltypeType>(Ty)->desugar(); 3964 break; 3965 case Type::Auto: 3966 case Type::DeducedTemplateSpecialization: 3967 T = cast<DeducedType>(Ty)->getDeducedType(); 3968 break; 3969 case Type::TypeOfExpr: 3970 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 3971 break; 3972 case Type::Atomic: 3973 T = cast<AtomicType>(Ty)->getValueType(); 3974 break; 3975 } 3976 } while (!T.isNull() && T->isVariablyModifiedType()); 3977 } 3978 3979 /// Build a sizeof or alignof expression given a type operand. 3980 ExprResult 3981 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3982 SourceLocation OpLoc, 3983 UnaryExprOrTypeTrait ExprKind, 3984 SourceRange R) { 3985 if (!TInfo) 3986 return ExprError(); 3987 3988 QualType T = TInfo->getType(); 3989 3990 if (!T->isDependentType() && 3991 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3992 return ExprError(); 3993 3994 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 3995 if (auto *TT = T->getAs<TypedefType>()) { 3996 for (auto I = FunctionScopes.rbegin(), 3997 E = std::prev(FunctionScopes.rend()); 3998 I != E; ++I) { 3999 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4000 if (CSI == nullptr) 4001 break; 4002 DeclContext *DC = nullptr; 4003 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4004 DC = LSI->CallOperator; 4005 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4006 DC = CRSI->TheCapturedDecl; 4007 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4008 DC = BSI->TheDecl; 4009 if (DC) { 4010 if (DC->containsDecl(TT->getDecl())) 4011 break; 4012 captureVariablyModifiedType(Context, T, CSI); 4013 } 4014 } 4015 } 4016 } 4017 4018 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4019 return new (Context) UnaryExprOrTypeTraitExpr( 4020 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4021 } 4022 4023 /// Build a sizeof or alignof expression given an expression 4024 /// operand. 4025 ExprResult 4026 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4027 UnaryExprOrTypeTrait ExprKind) { 4028 ExprResult PE = CheckPlaceholderExpr(E); 4029 if (PE.isInvalid()) 4030 return ExprError(); 4031 4032 E = PE.get(); 4033 4034 // Verify that the operand is valid. 4035 bool isInvalid = false; 4036 if (E->isTypeDependent()) { 4037 // Delay type-checking for type-dependent expressions. 4038 } else if (ExprKind == UETT_AlignOf) { 4039 isInvalid = CheckAlignOfExpr(*this, E); 4040 } else if (ExprKind == UETT_VecStep) { 4041 isInvalid = CheckVecStepExpr(E); 4042 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4043 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4044 isInvalid = true; 4045 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4046 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4047 isInvalid = true; 4048 } else { 4049 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4050 } 4051 4052 if (isInvalid) 4053 return ExprError(); 4054 4055 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4056 PE = TransformToPotentiallyEvaluated(E); 4057 if (PE.isInvalid()) return ExprError(); 4058 E = PE.get(); 4059 } 4060 4061 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4062 return new (Context) UnaryExprOrTypeTraitExpr( 4063 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4064 } 4065 4066 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4067 /// expr and the same for @c alignof and @c __alignof 4068 /// Note that the ArgRange is invalid if isType is false. 4069 ExprResult 4070 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4071 UnaryExprOrTypeTrait ExprKind, bool IsType, 4072 void *TyOrEx, SourceRange ArgRange) { 4073 // If error parsing type, ignore. 4074 if (!TyOrEx) return ExprError(); 4075 4076 if (IsType) { 4077 TypeSourceInfo *TInfo; 4078 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4079 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4080 } 4081 4082 Expr *ArgEx = (Expr *)TyOrEx; 4083 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4084 return Result; 4085 } 4086 4087 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4088 bool IsReal) { 4089 if (V.get()->isTypeDependent()) 4090 return S.Context.DependentTy; 4091 4092 // _Real and _Imag are only l-values for normal l-values. 4093 if (V.get()->getObjectKind() != OK_Ordinary) { 4094 V = S.DefaultLvalueConversion(V.get()); 4095 if (V.isInvalid()) 4096 return QualType(); 4097 } 4098 4099 // These operators return the element type of a complex type. 4100 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4101 return CT->getElementType(); 4102 4103 // Otherwise they pass through real integer and floating point types here. 4104 if (V.get()->getType()->isArithmeticType()) 4105 return V.get()->getType(); 4106 4107 // Test for placeholders. 4108 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4109 if (PR.isInvalid()) return QualType(); 4110 if (PR.get() != V.get()) { 4111 V = PR; 4112 return CheckRealImagOperand(S, V, Loc, IsReal); 4113 } 4114 4115 // Reject anything else. 4116 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4117 << (IsReal ? "__real" : "__imag"); 4118 return QualType(); 4119 } 4120 4121 4122 4123 ExprResult 4124 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4125 tok::TokenKind Kind, Expr *Input) { 4126 UnaryOperatorKind Opc; 4127 switch (Kind) { 4128 default: llvm_unreachable("Unknown unary op!"); 4129 case tok::plusplus: Opc = UO_PostInc; break; 4130 case tok::minusminus: Opc = UO_PostDec; break; 4131 } 4132 4133 // Since this might is a postfix expression, get rid of ParenListExprs. 4134 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4135 if (Result.isInvalid()) return ExprError(); 4136 Input = Result.get(); 4137 4138 return BuildUnaryOp(S, OpLoc, Opc, Input); 4139 } 4140 4141 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4142 /// 4143 /// \return true on error 4144 static bool checkArithmeticOnObjCPointer(Sema &S, 4145 SourceLocation opLoc, 4146 Expr *op) { 4147 assert(op->getType()->isObjCObjectPointerType()); 4148 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4149 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4150 return false; 4151 4152 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4153 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4154 << op->getSourceRange(); 4155 return true; 4156 } 4157 4158 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4159 auto *BaseNoParens = Base->IgnoreParens(); 4160 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4161 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4162 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4163 } 4164 4165 ExprResult 4166 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4167 Expr *idx, SourceLocation rbLoc) { 4168 if (base && !base->getType().isNull() && 4169 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4170 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4171 /*Length=*/nullptr, rbLoc); 4172 4173 // Since this might be a postfix expression, get rid of ParenListExprs. 4174 if (isa<ParenListExpr>(base)) { 4175 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4176 if (result.isInvalid()) return ExprError(); 4177 base = result.get(); 4178 } 4179 4180 // Handle any non-overload placeholder types in the base and index 4181 // expressions. We can't handle overloads here because the other 4182 // operand might be an overloadable type, in which case the overload 4183 // resolution for the operator overload should get the first crack 4184 // at the overload. 4185 bool IsMSPropertySubscript = false; 4186 if (base->getType()->isNonOverloadPlaceholderType()) { 4187 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4188 if (!IsMSPropertySubscript) { 4189 ExprResult result = CheckPlaceholderExpr(base); 4190 if (result.isInvalid()) 4191 return ExprError(); 4192 base = result.get(); 4193 } 4194 } 4195 if (idx->getType()->isNonOverloadPlaceholderType()) { 4196 ExprResult result = CheckPlaceholderExpr(idx); 4197 if (result.isInvalid()) return ExprError(); 4198 idx = result.get(); 4199 } 4200 4201 // Build an unanalyzed expression if either operand is type-dependent. 4202 if (getLangOpts().CPlusPlus && 4203 (base->isTypeDependent() || idx->isTypeDependent())) { 4204 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4205 VK_LValue, OK_Ordinary, rbLoc); 4206 } 4207 4208 // MSDN, property (C++) 4209 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4210 // This attribute can also be used in the declaration of an empty array in a 4211 // class or structure definition. For example: 4212 // __declspec(property(get=GetX, put=PutX)) int x[]; 4213 // The above statement indicates that x[] can be used with one or more array 4214 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4215 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4216 if (IsMSPropertySubscript) { 4217 // Build MS property subscript expression if base is MS property reference 4218 // or MS property subscript. 4219 return new (Context) MSPropertySubscriptExpr( 4220 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4221 } 4222 4223 // Use C++ overloaded-operator rules if either operand has record 4224 // type. The spec says to do this if either type is *overloadable*, 4225 // but enum types can't declare subscript operators or conversion 4226 // operators, so there's nothing interesting for overload resolution 4227 // to do if there aren't any record types involved. 4228 // 4229 // ObjC pointers have their own subscripting logic that is not tied 4230 // to overload resolution and so should not take this path. 4231 if (getLangOpts().CPlusPlus && 4232 (base->getType()->isRecordType() || 4233 (!base->getType()->isObjCObjectPointerType() && 4234 idx->getType()->isRecordType()))) { 4235 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4236 } 4237 4238 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4239 } 4240 4241 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4242 Expr *LowerBound, 4243 SourceLocation ColonLoc, Expr *Length, 4244 SourceLocation RBLoc) { 4245 if (Base->getType()->isPlaceholderType() && 4246 !Base->getType()->isSpecificPlaceholderType( 4247 BuiltinType::OMPArraySection)) { 4248 ExprResult Result = CheckPlaceholderExpr(Base); 4249 if (Result.isInvalid()) 4250 return ExprError(); 4251 Base = Result.get(); 4252 } 4253 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4254 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4255 if (Result.isInvalid()) 4256 return ExprError(); 4257 Result = DefaultLvalueConversion(Result.get()); 4258 if (Result.isInvalid()) 4259 return ExprError(); 4260 LowerBound = Result.get(); 4261 } 4262 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4263 ExprResult Result = CheckPlaceholderExpr(Length); 4264 if (Result.isInvalid()) 4265 return ExprError(); 4266 Result = DefaultLvalueConversion(Result.get()); 4267 if (Result.isInvalid()) 4268 return ExprError(); 4269 Length = Result.get(); 4270 } 4271 4272 // Build an unanalyzed expression if either operand is type-dependent. 4273 if (Base->isTypeDependent() || 4274 (LowerBound && 4275 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4276 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4277 return new (Context) 4278 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4279 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4280 } 4281 4282 // Perform default conversions. 4283 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4284 QualType ResultTy; 4285 if (OriginalTy->isAnyPointerType()) { 4286 ResultTy = OriginalTy->getPointeeType(); 4287 } else if (OriginalTy->isArrayType()) { 4288 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4289 } else { 4290 return ExprError( 4291 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4292 << Base->getSourceRange()); 4293 } 4294 // C99 6.5.2.1p1 4295 if (LowerBound) { 4296 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4297 LowerBound); 4298 if (Res.isInvalid()) 4299 return ExprError(Diag(LowerBound->getExprLoc(), 4300 diag::err_omp_typecheck_section_not_integer) 4301 << 0 << LowerBound->getSourceRange()); 4302 LowerBound = Res.get(); 4303 4304 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4305 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4306 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4307 << 0 << LowerBound->getSourceRange(); 4308 } 4309 if (Length) { 4310 auto Res = 4311 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4312 if (Res.isInvalid()) 4313 return ExprError(Diag(Length->getExprLoc(), 4314 diag::err_omp_typecheck_section_not_integer) 4315 << 1 << Length->getSourceRange()); 4316 Length = Res.get(); 4317 4318 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4319 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4320 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4321 << 1 << Length->getSourceRange(); 4322 } 4323 4324 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4325 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4326 // type. Note that functions are not objects, and that (in C99 parlance) 4327 // incomplete types are not object types. 4328 if (ResultTy->isFunctionType()) { 4329 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4330 << ResultTy << Base->getSourceRange(); 4331 return ExprError(); 4332 } 4333 4334 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4335 diag::err_omp_section_incomplete_type, Base)) 4336 return ExprError(); 4337 4338 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4339 llvm::APSInt LowerBoundValue; 4340 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4341 // OpenMP 4.5, [2.4 Array Sections] 4342 // The array section must be a subset of the original array. 4343 if (LowerBoundValue.isNegative()) { 4344 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4345 << LowerBound->getSourceRange(); 4346 return ExprError(); 4347 } 4348 } 4349 } 4350 4351 if (Length) { 4352 llvm::APSInt LengthValue; 4353 if (Length->EvaluateAsInt(LengthValue, Context)) { 4354 // OpenMP 4.5, [2.4 Array Sections] 4355 // The length must evaluate to non-negative integers. 4356 if (LengthValue.isNegative()) { 4357 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4358 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4359 << Length->getSourceRange(); 4360 return ExprError(); 4361 } 4362 } 4363 } else if (ColonLoc.isValid() && 4364 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4365 !OriginalTy->isVariableArrayType()))) { 4366 // OpenMP 4.5, [2.4 Array Sections] 4367 // When the size of the array dimension is not known, the length must be 4368 // specified explicitly. 4369 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4370 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4371 return ExprError(); 4372 } 4373 4374 if (!Base->getType()->isSpecificPlaceholderType( 4375 BuiltinType::OMPArraySection)) { 4376 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4377 if (Result.isInvalid()) 4378 return ExprError(); 4379 Base = Result.get(); 4380 } 4381 return new (Context) 4382 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4383 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4384 } 4385 4386 ExprResult 4387 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4388 Expr *Idx, SourceLocation RLoc) { 4389 Expr *LHSExp = Base; 4390 Expr *RHSExp = Idx; 4391 4392 ExprValueKind VK = VK_LValue; 4393 ExprObjectKind OK = OK_Ordinary; 4394 4395 // Per C++ core issue 1213, the result is an xvalue if either operand is 4396 // a non-lvalue array, and an lvalue otherwise. 4397 if (getLangOpts().CPlusPlus11) { 4398 for (auto *Op : {LHSExp, RHSExp}) { 4399 Op = Op->IgnoreImplicit(); 4400 if (Op->getType()->isArrayType() && !Op->isLValue()) 4401 VK = VK_XValue; 4402 } 4403 } 4404 4405 // Perform default conversions. 4406 if (!LHSExp->getType()->getAs<VectorType>()) { 4407 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4408 if (Result.isInvalid()) 4409 return ExprError(); 4410 LHSExp = Result.get(); 4411 } 4412 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4413 if (Result.isInvalid()) 4414 return ExprError(); 4415 RHSExp = Result.get(); 4416 4417 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4418 4419 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4420 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4421 // in the subscript position. As a result, we need to derive the array base 4422 // and index from the expression types. 4423 Expr *BaseExpr, *IndexExpr; 4424 QualType ResultType; 4425 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4426 BaseExpr = LHSExp; 4427 IndexExpr = RHSExp; 4428 ResultType = Context.DependentTy; 4429 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4430 BaseExpr = LHSExp; 4431 IndexExpr = RHSExp; 4432 ResultType = PTy->getPointeeType(); 4433 } else if (const ObjCObjectPointerType *PTy = 4434 LHSTy->getAs<ObjCObjectPointerType>()) { 4435 BaseExpr = LHSExp; 4436 IndexExpr = RHSExp; 4437 4438 // Use custom logic if this should be the pseudo-object subscript 4439 // expression. 4440 if (!LangOpts.isSubscriptPointerArithmetic()) 4441 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4442 nullptr); 4443 4444 ResultType = PTy->getPointeeType(); 4445 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4446 // Handle the uncommon case of "123[Ptr]". 4447 BaseExpr = RHSExp; 4448 IndexExpr = LHSExp; 4449 ResultType = PTy->getPointeeType(); 4450 } else if (const ObjCObjectPointerType *PTy = 4451 RHSTy->getAs<ObjCObjectPointerType>()) { 4452 // Handle the uncommon case of "123[Ptr]". 4453 BaseExpr = RHSExp; 4454 IndexExpr = LHSExp; 4455 ResultType = PTy->getPointeeType(); 4456 if (!LangOpts.isSubscriptPointerArithmetic()) { 4457 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4458 << ResultType << BaseExpr->getSourceRange(); 4459 return ExprError(); 4460 } 4461 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4462 BaseExpr = LHSExp; // vectors: V[123] 4463 IndexExpr = RHSExp; 4464 // We apply C++ DR1213 to vector subscripting too. 4465 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 4466 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 4467 if (Materialized.isInvalid()) 4468 return ExprError(); 4469 LHSExp = Materialized.get(); 4470 } 4471 VK = LHSExp->getValueKind(); 4472 if (VK != VK_RValue) 4473 OK = OK_VectorComponent; 4474 4475 ResultType = VTy->getElementType(); 4476 QualType BaseType = BaseExpr->getType(); 4477 Qualifiers BaseQuals = BaseType.getQualifiers(); 4478 Qualifiers MemberQuals = ResultType.getQualifiers(); 4479 Qualifiers Combined = BaseQuals + MemberQuals; 4480 if (Combined != MemberQuals) 4481 ResultType = Context.getQualifiedType(ResultType, Combined); 4482 } else if (LHSTy->isArrayType()) { 4483 // If we see an array that wasn't promoted by 4484 // DefaultFunctionArrayLvalueConversion, it must be an array that 4485 // wasn't promoted because of the C90 rule that doesn't 4486 // allow promoting non-lvalue arrays. Warn, then 4487 // force the promotion here. 4488 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4489 << LHSExp->getSourceRange(); 4490 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4491 CK_ArrayToPointerDecay).get(); 4492 LHSTy = LHSExp->getType(); 4493 4494 BaseExpr = LHSExp; 4495 IndexExpr = RHSExp; 4496 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4497 } else if (RHSTy->isArrayType()) { 4498 // Same as previous, except for 123[f().a] case 4499 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4500 << RHSExp->getSourceRange(); 4501 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4502 CK_ArrayToPointerDecay).get(); 4503 RHSTy = RHSExp->getType(); 4504 4505 BaseExpr = RHSExp; 4506 IndexExpr = LHSExp; 4507 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4508 } else { 4509 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4510 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4511 } 4512 // C99 6.5.2.1p1 4513 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4514 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4515 << IndexExpr->getSourceRange()); 4516 4517 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4518 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4519 && !IndexExpr->isTypeDependent()) 4520 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4521 4522 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4523 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4524 // type. Note that Functions are not objects, and that (in C99 parlance) 4525 // incomplete types are not object types. 4526 if (ResultType->isFunctionType()) { 4527 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 4528 << ResultType << BaseExpr->getSourceRange(); 4529 return ExprError(); 4530 } 4531 4532 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4533 // GNU extension: subscripting on pointer to void 4534 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4535 << BaseExpr->getSourceRange(); 4536 4537 // C forbids expressions of unqualified void type from being l-values. 4538 // See IsCForbiddenLValueType. 4539 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4540 } else if (!ResultType->isDependentType() && 4541 RequireCompleteType(LLoc, ResultType, 4542 diag::err_subscript_incomplete_type, BaseExpr)) 4543 return ExprError(); 4544 4545 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4546 !ResultType.isCForbiddenLValueType()); 4547 4548 return new (Context) 4549 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4550 } 4551 4552 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4553 ParmVarDecl *Param) { 4554 if (Param->hasUnparsedDefaultArg()) { 4555 Diag(CallLoc, 4556 diag::err_use_of_default_argument_to_function_declared_later) << 4557 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4558 Diag(UnparsedDefaultArgLocs[Param], 4559 diag::note_default_argument_declared_here); 4560 return true; 4561 } 4562 4563 if (Param->hasUninstantiatedDefaultArg()) { 4564 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4565 4566 EnterExpressionEvaluationContext EvalContext( 4567 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4568 4569 // Instantiate the expression. 4570 // 4571 // FIXME: Pass in a correct Pattern argument, otherwise 4572 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4573 // 4574 // template<typename T> 4575 // struct A { 4576 // static int FooImpl(); 4577 // 4578 // template<typename Tp> 4579 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4580 // // template argument list [[T], [Tp]], should be [[Tp]]. 4581 // friend A<Tp> Foo(int a); 4582 // }; 4583 // 4584 // template<typename T> 4585 // A<T> Foo(int a = A<T>::FooImpl()); 4586 MultiLevelTemplateArgumentList MutiLevelArgList 4587 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4588 4589 InstantiatingTemplate Inst(*this, CallLoc, Param, 4590 MutiLevelArgList.getInnermost()); 4591 if (Inst.isInvalid()) 4592 return true; 4593 if (Inst.isAlreadyInstantiating()) { 4594 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4595 Param->setInvalidDecl(); 4596 return true; 4597 } 4598 4599 ExprResult Result; 4600 { 4601 // C++ [dcl.fct.default]p5: 4602 // The names in the [default argument] expression are bound, and 4603 // the semantic constraints are checked, at the point where the 4604 // default argument expression appears. 4605 ContextRAII SavedContext(*this, FD); 4606 LocalInstantiationScope Local(*this); 4607 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4608 /*DirectInit*/false); 4609 } 4610 if (Result.isInvalid()) 4611 return true; 4612 4613 // Check the expression as an initializer for the parameter. 4614 InitializedEntity Entity 4615 = InitializedEntity::InitializeParameter(Context, Param); 4616 InitializationKind Kind = InitializationKind::CreateCopy( 4617 Param->getLocation(), 4618 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 4619 Expr *ResultE = Result.getAs<Expr>(); 4620 4621 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4622 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4623 if (Result.isInvalid()) 4624 return true; 4625 4626 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4627 Param->getOuterLocStart()); 4628 if (Result.isInvalid()) 4629 return true; 4630 4631 // Remember the instantiated default argument. 4632 Param->setDefaultArg(Result.getAs<Expr>()); 4633 if (ASTMutationListener *L = getASTMutationListener()) { 4634 L->DefaultArgumentInstantiated(Param); 4635 } 4636 } 4637 4638 // If the default argument expression is not set yet, we are building it now. 4639 if (!Param->hasInit()) { 4640 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4641 Param->setInvalidDecl(); 4642 return true; 4643 } 4644 4645 // If the default expression creates temporaries, we need to 4646 // push them to the current stack of expression temporaries so they'll 4647 // be properly destroyed. 4648 // FIXME: We should really be rebuilding the default argument with new 4649 // bound temporaries; see the comment in PR5810. 4650 // We don't need to do that with block decls, though, because 4651 // blocks in default argument expression can never capture anything. 4652 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4653 // Set the "needs cleanups" bit regardless of whether there are 4654 // any explicit objects. 4655 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4656 4657 // Append all the objects to the cleanup list. Right now, this 4658 // should always be a no-op, because blocks in default argument 4659 // expressions should never be able to capture anything. 4660 assert(!Init->getNumObjects() && 4661 "default argument expression has capturing blocks?"); 4662 } 4663 4664 // We already type-checked the argument, so we know it works. 4665 // Just mark all of the declarations in this potentially-evaluated expression 4666 // as being "referenced". 4667 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4668 /*SkipLocalVariables=*/true); 4669 return false; 4670 } 4671 4672 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4673 FunctionDecl *FD, ParmVarDecl *Param) { 4674 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4675 return ExprError(); 4676 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4677 } 4678 4679 Sema::VariadicCallType 4680 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4681 Expr *Fn) { 4682 if (Proto && Proto->isVariadic()) { 4683 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4684 return VariadicConstructor; 4685 else if (Fn && Fn->getType()->isBlockPointerType()) 4686 return VariadicBlock; 4687 else if (FDecl) { 4688 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4689 if (Method->isInstance()) 4690 return VariadicMethod; 4691 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4692 return VariadicMethod; 4693 return VariadicFunction; 4694 } 4695 return VariadicDoesNotApply; 4696 } 4697 4698 namespace { 4699 class FunctionCallCCC : public FunctionCallFilterCCC { 4700 public: 4701 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4702 unsigned NumArgs, MemberExpr *ME) 4703 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4704 FunctionName(FuncName) {} 4705 4706 bool ValidateCandidate(const TypoCorrection &candidate) override { 4707 if (!candidate.getCorrectionSpecifier() || 4708 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4709 return false; 4710 } 4711 4712 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4713 } 4714 4715 private: 4716 const IdentifierInfo *const FunctionName; 4717 }; 4718 } 4719 4720 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4721 FunctionDecl *FDecl, 4722 ArrayRef<Expr *> Args) { 4723 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4724 DeclarationName FuncName = FDecl->getDeclName(); 4725 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 4726 4727 if (TypoCorrection Corrected = S.CorrectTypo( 4728 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4729 S.getScopeForContext(S.CurContext), nullptr, 4730 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4731 Args.size(), ME), 4732 Sema::CTK_ErrorRecovery)) { 4733 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4734 if (Corrected.isOverloaded()) { 4735 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4736 OverloadCandidateSet::iterator Best; 4737 for (NamedDecl *CD : Corrected) { 4738 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4739 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4740 OCS); 4741 } 4742 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4743 case OR_Success: 4744 ND = Best->FoundDecl; 4745 Corrected.setCorrectionDecl(ND); 4746 break; 4747 default: 4748 break; 4749 } 4750 } 4751 ND = ND->getUnderlyingDecl(); 4752 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4753 return Corrected; 4754 } 4755 } 4756 return TypoCorrection(); 4757 } 4758 4759 /// ConvertArgumentsForCall - Converts the arguments specified in 4760 /// Args/NumArgs to the parameter types of the function FDecl with 4761 /// function prototype Proto. Call is the call expression itself, and 4762 /// Fn is the function expression. For a C++ member function, this 4763 /// routine does not attempt to convert the object argument. Returns 4764 /// true if the call is ill-formed. 4765 bool 4766 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4767 FunctionDecl *FDecl, 4768 const FunctionProtoType *Proto, 4769 ArrayRef<Expr *> Args, 4770 SourceLocation RParenLoc, 4771 bool IsExecConfig) { 4772 // Bail out early if calling a builtin with custom typechecking. 4773 if (FDecl) 4774 if (unsigned ID = FDecl->getBuiltinID()) 4775 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4776 return false; 4777 4778 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4779 // assignment, to the types of the corresponding parameter, ... 4780 unsigned NumParams = Proto->getNumParams(); 4781 bool Invalid = false; 4782 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4783 unsigned FnKind = Fn->getType()->isBlockPointerType() 4784 ? 1 /* block */ 4785 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4786 : 0 /* function */); 4787 4788 // If too few arguments are available (and we don't have default 4789 // arguments for the remaining parameters), don't make the call. 4790 if (Args.size() < NumParams) { 4791 if (Args.size() < MinArgs) { 4792 TypoCorrection TC; 4793 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4794 unsigned diag_id = 4795 MinArgs == NumParams && !Proto->isVariadic() 4796 ? diag::err_typecheck_call_too_few_args_suggest 4797 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4798 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4799 << static_cast<unsigned>(Args.size()) 4800 << TC.getCorrectionRange()); 4801 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4802 Diag(RParenLoc, 4803 MinArgs == NumParams && !Proto->isVariadic() 4804 ? diag::err_typecheck_call_too_few_args_one 4805 : diag::err_typecheck_call_too_few_args_at_least_one) 4806 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4807 else 4808 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4809 ? diag::err_typecheck_call_too_few_args 4810 : diag::err_typecheck_call_too_few_args_at_least) 4811 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4812 << Fn->getSourceRange(); 4813 4814 // Emit the location of the prototype. 4815 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4816 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 4817 4818 return true; 4819 } 4820 Call->setNumArgs(Context, NumParams); 4821 } 4822 4823 // If too many are passed and not variadic, error on the extras and drop 4824 // them. 4825 if (Args.size() > NumParams) { 4826 if (!Proto->isVariadic()) { 4827 TypoCorrection TC; 4828 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4829 unsigned diag_id = 4830 MinArgs == NumParams && !Proto->isVariadic() 4831 ? diag::err_typecheck_call_too_many_args_suggest 4832 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4833 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4834 << static_cast<unsigned>(Args.size()) 4835 << TC.getCorrectionRange()); 4836 } else if (NumParams == 1 && FDecl && 4837 FDecl->getParamDecl(0)->getDeclName()) 4838 Diag(Args[NumParams]->getBeginLoc(), 4839 MinArgs == NumParams 4840 ? diag::err_typecheck_call_too_many_args_one 4841 : diag::err_typecheck_call_too_many_args_at_most_one) 4842 << FnKind << FDecl->getParamDecl(0) 4843 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4844 << SourceRange(Args[NumParams]->getBeginLoc(), 4845 Args.back()->getEndLoc()); 4846 else 4847 Diag(Args[NumParams]->getBeginLoc(), 4848 MinArgs == NumParams 4849 ? diag::err_typecheck_call_too_many_args 4850 : diag::err_typecheck_call_too_many_args_at_most) 4851 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4852 << Fn->getSourceRange() 4853 << SourceRange(Args[NumParams]->getBeginLoc(), 4854 Args.back()->getEndLoc()); 4855 4856 // Emit the location of the prototype. 4857 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4858 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 4859 4860 // This deletes the extra arguments. 4861 Call->setNumArgs(Context, NumParams); 4862 return true; 4863 } 4864 } 4865 SmallVector<Expr *, 8> AllArgs; 4866 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4867 4868 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 4869 AllArgs, CallType); 4870 if (Invalid) 4871 return true; 4872 unsigned TotalNumArgs = AllArgs.size(); 4873 for (unsigned i = 0; i < TotalNumArgs; ++i) 4874 Call->setArg(i, AllArgs[i]); 4875 4876 return false; 4877 } 4878 4879 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4880 const FunctionProtoType *Proto, 4881 unsigned FirstParam, ArrayRef<Expr *> Args, 4882 SmallVectorImpl<Expr *> &AllArgs, 4883 VariadicCallType CallType, bool AllowExplicit, 4884 bool IsListInitialization) { 4885 unsigned NumParams = Proto->getNumParams(); 4886 bool Invalid = false; 4887 size_t ArgIx = 0; 4888 // Continue to check argument types (even if we have too few/many args). 4889 for (unsigned i = FirstParam; i < NumParams; i++) { 4890 QualType ProtoArgType = Proto->getParamType(i); 4891 4892 Expr *Arg; 4893 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4894 if (ArgIx < Args.size()) { 4895 Arg = Args[ArgIx++]; 4896 4897 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 4898 diag::err_call_incomplete_argument, Arg)) 4899 return true; 4900 4901 // Strip the unbridged-cast placeholder expression off, if applicable. 4902 bool CFAudited = false; 4903 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4904 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4905 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4906 Arg = stripARCUnbridgedCast(Arg); 4907 else if (getLangOpts().ObjCAutoRefCount && 4908 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4909 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4910 CFAudited = true; 4911 4912 if (Proto->getExtParameterInfo(i).isNoEscape()) 4913 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 4914 BE->getBlockDecl()->setDoesNotEscape(); 4915 4916 InitializedEntity Entity = 4917 Param ? InitializedEntity::InitializeParameter(Context, Param, 4918 ProtoArgType) 4919 : InitializedEntity::InitializeParameter( 4920 Context, ProtoArgType, Proto->isParamConsumed(i)); 4921 4922 // Remember that parameter belongs to a CF audited API. 4923 if (CFAudited) 4924 Entity.setParameterCFAudited(); 4925 4926 ExprResult ArgE = PerformCopyInitialization( 4927 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4928 if (ArgE.isInvalid()) 4929 return true; 4930 4931 Arg = ArgE.getAs<Expr>(); 4932 } else { 4933 assert(Param && "can't use default arguments without a known callee"); 4934 4935 ExprResult ArgExpr = 4936 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4937 if (ArgExpr.isInvalid()) 4938 return true; 4939 4940 Arg = ArgExpr.getAs<Expr>(); 4941 } 4942 4943 // Check for array bounds violations for each argument to the call. This 4944 // check only triggers warnings when the argument isn't a more complex Expr 4945 // with its own checking, such as a BinaryOperator. 4946 CheckArrayAccess(Arg); 4947 4948 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4949 CheckStaticArrayArgument(CallLoc, Param, Arg); 4950 4951 AllArgs.push_back(Arg); 4952 } 4953 4954 // If this is a variadic call, handle args passed through "...". 4955 if (CallType != VariadicDoesNotApply) { 4956 // Assume that extern "C" functions with variadic arguments that 4957 // return __unknown_anytype aren't *really* variadic. 4958 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4959 FDecl->isExternC()) { 4960 for (Expr *A : Args.slice(ArgIx)) { 4961 QualType paramType; // ignored 4962 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4963 Invalid |= arg.isInvalid(); 4964 AllArgs.push_back(arg.get()); 4965 } 4966 4967 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4968 } else { 4969 for (Expr *A : Args.slice(ArgIx)) { 4970 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4971 Invalid |= Arg.isInvalid(); 4972 AllArgs.push_back(Arg.get()); 4973 } 4974 } 4975 4976 // Check for array bounds violations. 4977 for (Expr *A : Args.slice(ArgIx)) 4978 CheckArrayAccess(A); 4979 } 4980 return Invalid; 4981 } 4982 4983 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4984 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4985 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4986 TL = DTL.getOriginalLoc(); 4987 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4988 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4989 << ATL.getLocalSourceRange(); 4990 } 4991 4992 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4993 /// array parameter, check that it is non-null, and that if it is formed by 4994 /// array-to-pointer decay, the underlying array is sufficiently large. 4995 /// 4996 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4997 /// array type derivation, then for each call to the function, the value of the 4998 /// corresponding actual argument shall provide access to the first element of 4999 /// an array with at least as many elements as specified by the size expression. 5000 void 5001 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5002 ParmVarDecl *Param, 5003 const Expr *ArgExpr) { 5004 // Static array parameters are not supported in C++. 5005 if (!Param || getLangOpts().CPlusPlus) 5006 return; 5007 5008 QualType OrigTy = Param->getOriginalType(); 5009 5010 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5011 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5012 return; 5013 5014 if (ArgExpr->isNullPointerConstant(Context, 5015 Expr::NPC_NeverValueDependent)) { 5016 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5017 DiagnoseCalleeStaticArrayParam(*this, Param); 5018 return; 5019 } 5020 5021 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5022 if (!CAT) 5023 return; 5024 5025 const ConstantArrayType *ArgCAT = 5026 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 5027 if (!ArgCAT) 5028 return; 5029 5030 if (ArgCAT->getSize().ult(CAT->getSize())) { 5031 Diag(CallLoc, diag::warn_static_array_too_small) 5032 << ArgExpr->getSourceRange() 5033 << (unsigned) ArgCAT->getSize().getZExtValue() 5034 << (unsigned) CAT->getSize().getZExtValue(); 5035 DiagnoseCalleeStaticArrayParam(*this, Param); 5036 } 5037 } 5038 5039 /// Given a function expression of unknown-any type, try to rebuild it 5040 /// to have a function type. 5041 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5042 5043 /// Is the given type a placeholder that we need to lower out 5044 /// immediately during argument processing? 5045 static bool isPlaceholderToRemoveAsArg(QualType type) { 5046 // Placeholders are never sugared. 5047 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5048 if (!placeholder) return false; 5049 5050 switch (placeholder->getKind()) { 5051 // Ignore all the non-placeholder types. 5052 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5053 case BuiltinType::Id: 5054 #include "clang/Basic/OpenCLImageTypes.def" 5055 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5056 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5057 #include "clang/AST/BuiltinTypes.def" 5058 return false; 5059 5060 // We cannot lower out overload sets; they might validly be resolved 5061 // by the call machinery. 5062 case BuiltinType::Overload: 5063 return false; 5064 5065 // Unbridged casts in ARC can be handled in some call positions and 5066 // should be left in place. 5067 case BuiltinType::ARCUnbridgedCast: 5068 return false; 5069 5070 // Pseudo-objects should be converted as soon as possible. 5071 case BuiltinType::PseudoObject: 5072 return true; 5073 5074 // The debugger mode could theoretically but currently does not try 5075 // to resolve unknown-typed arguments based on known parameter types. 5076 case BuiltinType::UnknownAny: 5077 return true; 5078 5079 // These are always invalid as call arguments and should be reported. 5080 case BuiltinType::BoundMember: 5081 case BuiltinType::BuiltinFn: 5082 case BuiltinType::OMPArraySection: 5083 return true; 5084 5085 } 5086 llvm_unreachable("bad builtin type kind"); 5087 } 5088 5089 /// Check an argument list for placeholders that we won't try to 5090 /// handle later. 5091 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5092 // Apply this processing to all the arguments at once instead of 5093 // dying at the first failure. 5094 bool hasInvalid = false; 5095 for (size_t i = 0, e = args.size(); i != e; i++) { 5096 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5097 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5098 if (result.isInvalid()) hasInvalid = true; 5099 else args[i] = result.get(); 5100 } else if (hasInvalid) { 5101 (void)S.CorrectDelayedTyposInExpr(args[i]); 5102 } 5103 } 5104 return hasInvalid; 5105 } 5106 5107 /// If a builtin function has a pointer argument with no explicit address 5108 /// space, then it should be able to accept a pointer to any address 5109 /// space as input. In order to do this, we need to replace the 5110 /// standard builtin declaration with one that uses the same address space 5111 /// as the call. 5112 /// 5113 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5114 /// it does not contain any pointer arguments without 5115 /// an address space qualifer. Otherwise the rewritten 5116 /// FunctionDecl is returned. 5117 /// TODO: Handle pointer return types. 5118 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5119 const FunctionDecl *FDecl, 5120 MultiExprArg ArgExprs) { 5121 5122 QualType DeclType = FDecl->getType(); 5123 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5124 5125 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5126 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5127 return nullptr; 5128 5129 bool NeedsNewDecl = false; 5130 unsigned i = 0; 5131 SmallVector<QualType, 8> OverloadParams; 5132 5133 for (QualType ParamType : FT->param_types()) { 5134 5135 // Convert array arguments to pointer to simplify type lookup. 5136 ExprResult ArgRes = 5137 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5138 if (ArgRes.isInvalid()) 5139 return nullptr; 5140 Expr *Arg = ArgRes.get(); 5141 QualType ArgType = Arg->getType(); 5142 if (!ParamType->isPointerType() || 5143 ParamType.getQualifiers().hasAddressSpace() || 5144 !ArgType->isPointerType() || 5145 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5146 OverloadParams.push_back(ParamType); 5147 continue; 5148 } 5149 5150 QualType PointeeType = ParamType->getPointeeType(); 5151 if (PointeeType.getQualifiers().hasAddressSpace()) 5152 continue; 5153 5154 NeedsNewDecl = true; 5155 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5156 5157 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5158 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5159 } 5160 5161 if (!NeedsNewDecl) 5162 return nullptr; 5163 5164 FunctionProtoType::ExtProtoInfo EPI; 5165 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5166 OverloadParams, EPI); 5167 DeclContext *Parent = Context.getTranslationUnitDecl(); 5168 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5169 FDecl->getLocation(), 5170 FDecl->getLocation(), 5171 FDecl->getIdentifier(), 5172 OverloadTy, 5173 /*TInfo=*/nullptr, 5174 SC_Extern, false, 5175 /*hasPrototype=*/true); 5176 SmallVector<ParmVarDecl*, 16> Params; 5177 FT = cast<FunctionProtoType>(OverloadTy); 5178 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5179 QualType ParamType = FT->getParamType(i); 5180 ParmVarDecl *Parm = 5181 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5182 SourceLocation(), nullptr, ParamType, 5183 /*TInfo=*/nullptr, SC_None, nullptr); 5184 Parm->setScopeInfo(0, i); 5185 Params.push_back(Parm); 5186 } 5187 OverloadDecl->setParams(Params); 5188 return OverloadDecl; 5189 } 5190 5191 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5192 FunctionDecl *Callee, 5193 MultiExprArg ArgExprs) { 5194 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5195 // similar attributes) really don't like it when functions are called with an 5196 // invalid number of args. 5197 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5198 /*PartialOverloading=*/false) && 5199 !Callee->isVariadic()) 5200 return; 5201 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5202 return; 5203 5204 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5205 S.Diag(Fn->getBeginLoc(), 5206 isa<CXXMethodDecl>(Callee) 5207 ? diag::err_ovl_no_viable_member_function_in_call 5208 : diag::err_ovl_no_viable_function_in_call) 5209 << Callee << Callee->getSourceRange(); 5210 S.Diag(Callee->getLocation(), 5211 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5212 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5213 return; 5214 } 5215 } 5216 5217 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5218 const UnresolvedMemberExpr *const UME, Sema &S) { 5219 5220 const auto GetFunctionLevelDCIfCXXClass = 5221 [](Sema &S) -> const CXXRecordDecl * { 5222 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5223 if (!DC || !DC->getParent()) 5224 return nullptr; 5225 5226 // If the call to some member function was made from within a member 5227 // function body 'M' return return 'M's parent. 5228 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5229 return MD->getParent()->getCanonicalDecl(); 5230 // else the call was made from within a default member initializer of a 5231 // class, so return the class. 5232 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5233 return RD->getCanonicalDecl(); 5234 return nullptr; 5235 }; 5236 // If our DeclContext is neither a member function nor a class (in the 5237 // case of a lambda in a default member initializer), we can't have an 5238 // enclosing 'this'. 5239 5240 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5241 if (!CurParentClass) 5242 return false; 5243 5244 // The naming class for implicit member functions call is the class in which 5245 // name lookup starts. 5246 const CXXRecordDecl *const NamingClass = 5247 UME->getNamingClass()->getCanonicalDecl(); 5248 assert(NamingClass && "Must have naming class even for implicit access"); 5249 5250 // If the unresolved member functions were found in a 'naming class' that is 5251 // related (either the same or derived from) to the class that contains the 5252 // member function that itself contained the implicit member access. 5253 5254 return CurParentClass == NamingClass || 5255 CurParentClass->isDerivedFrom(NamingClass); 5256 } 5257 5258 static void 5259 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5260 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5261 5262 if (!UME) 5263 return; 5264 5265 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5266 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5267 // already been captured, or if this is an implicit member function call (if 5268 // it isn't, an attempt to capture 'this' should already have been made). 5269 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5270 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5271 return; 5272 5273 // Check if the naming class in which the unresolved members were found is 5274 // related (same as or is a base of) to the enclosing class. 5275 5276 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5277 return; 5278 5279 5280 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5281 // If the enclosing function is not dependent, then this lambda is 5282 // capture ready, so if we can capture this, do so. 5283 if (!EnclosingFunctionCtx->isDependentContext()) { 5284 // If the current lambda and all enclosing lambdas can capture 'this' - 5285 // then go ahead and capture 'this' (since our unresolved overload set 5286 // contains at least one non-static member function). 5287 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5288 S.CheckCXXThisCapture(CallLoc); 5289 } else if (S.CurContext->isDependentContext()) { 5290 // ... since this is an implicit member reference, that might potentially 5291 // involve a 'this' capture, mark 'this' for potential capture in 5292 // enclosing lambdas. 5293 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5294 CurLSI->addPotentialThisCapture(CallLoc); 5295 } 5296 } 5297 5298 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5299 /// This provides the location of the left/right parens and a list of comma 5300 /// locations. 5301 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5302 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5303 Expr *ExecConfig, bool IsExecConfig) { 5304 // Since this might be a postfix expression, get rid of ParenListExprs. 5305 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5306 if (Result.isInvalid()) return ExprError(); 5307 Fn = Result.get(); 5308 5309 if (checkArgsForPlaceholders(*this, ArgExprs)) 5310 return ExprError(); 5311 5312 if (getLangOpts().CPlusPlus) { 5313 // If this is a pseudo-destructor expression, build the call immediately. 5314 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5315 if (!ArgExprs.empty()) { 5316 // Pseudo-destructor calls should not have any arguments. 5317 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 5318 << FixItHint::CreateRemoval( 5319 SourceRange(ArgExprs.front()->getBeginLoc(), 5320 ArgExprs.back()->getEndLoc())); 5321 } 5322 5323 return new (Context) 5324 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5325 } 5326 if (Fn->getType() == Context.PseudoObjectTy) { 5327 ExprResult result = CheckPlaceholderExpr(Fn); 5328 if (result.isInvalid()) return ExprError(); 5329 Fn = result.get(); 5330 } 5331 5332 // Determine whether this is a dependent call inside a C++ template, 5333 // in which case we won't do any semantic analysis now. 5334 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 5335 if (ExecConfig) { 5336 return new (Context) CUDAKernelCallExpr( 5337 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5338 Context.DependentTy, VK_RValue, RParenLoc); 5339 } else { 5340 5341 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5342 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5343 Fn->getBeginLoc()); 5344 5345 return new (Context) CallExpr( 5346 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5347 } 5348 } 5349 5350 // Determine whether this is a call to an object (C++ [over.call.object]). 5351 if (Fn->getType()->isRecordType()) 5352 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5353 RParenLoc); 5354 5355 if (Fn->getType() == Context.UnknownAnyTy) { 5356 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5357 if (result.isInvalid()) return ExprError(); 5358 Fn = result.get(); 5359 } 5360 5361 if (Fn->getType() == Context.BoundMemberTy) { 5362 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5363 RParenLoc); 5364 } 5365 } 5366 5367 // Check for overloaded calls. This can happen even in C due to extensions. 5368 if (Fn->getType() == Context.OverloadTy) { 5369 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5370 5371 // We aren't supposed to apply this logic if there's an '&' involved. 5372 if (!find.HasFormOfMemberPointer) { 5373 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5374 return new (Context) CallExpr( 5375 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5376 OverloadExpr *ovl = find.Expression; 5377 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5378 return BuildOverloadedCallExpr( 5379 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5380 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5381 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5382 RParenLoc); 5383 } 5384 } 5385 5386 // If we're directly calling a function, get the appropriate declaration. 5387 if (Fn->getType() == Context.UnknownAnyTy) { 5388 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5389 if (result.isInvalid()) return ExprError(); 5390 Fn = result.get(); 5391 } 5392 5393 Expr *NakedFn = Fn->IgnoreParens(); 5394 5395 bool CallingNDeclIndirectly = false; 5396 NamedDecl *NDecl = nullptr; 5397 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5398 if (UnOp->getOpcode() == UO_AddrOf) { 5399 CallingNDeclIndirectly = true; 5400 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5401 } 5402 } 5403 5404 if (isa<DeclRefExpr>(NakedFn)) { 5405 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5406 5407 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5408 if (FDecl && FDecl->getBuiltinID()) { 5409 // Rewrite the function decl for this builtin by replacing parameters 5410 // with no explicit address space with the address space of the arguments 5411 // in ArgExprs. 5412 if ((FDecl = 5413 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5414 NDecl = FDecl; 5415 Fn = DeclRefExpr::Create( 5416 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5417 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5418 } 5419 } 5420 } else if (isa<MemberExpr>(NakedFn)) 5421 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5422 5423 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5424 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 5425 FD, /*Complain=*/true, Fn->getBeginLoc())) 5426 return ExprError(); 5427 5428 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5429 return ExprError(); 5430 5431 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5432 } 5433 5434 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5435 ExecConfig, IsExecConfig); 5436 } 5437 5438 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5439 /// 5440 /// __builtin_astype( value, dst type ) 5441 /// 5442 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5443 SourceLocation BuiltinLoc, 5444 SourceLocation RParenLoc) { 5445 ExprValueKind VK = VK_RValue; 5446 ExprObjectKind OK = OK_Ordinary; 5447 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5448 QualType SrcTy = E->getType(); 5449 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5450 return ExprError(Diag(BuiltinLoc, 5451 diag::err_invalid_astype_of_different_size) 5452 << DstTy 5453 << SrcTy 5454 << E->getSourceRange()); 5455 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5456 } 5457 5458 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5459 /// provided arguments. 5460 /// 5461 /// __builtin_convertvector( value, dst type ) 5462 /// 5463 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5464 SourceLocation BuiltinLoc, 5465 SourceLocation RParenLoc) { 5466 TypeSourceInfo *TInfo; 5467 GetTypeFromParser(ParsedDestTy, &TInfo); 5468 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5469 } 5470 5471 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5472 /// i.e. an expression not of \p OverloadTy. The expression should 5473 /// unary-convert to an expression of function-pointer or 5474 /// block-pointer type. 5475 /// 5476 /// \param NDecl the declaration being called, if available 5477 ExprResult 5478 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5479 SourceLocation LParenLoc, 5480 ArrayRef<Expr *> Args, 5481 SourceLocation RParenLoc, 5482 Expr *Config, bool IsExecConfig) { 5483 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5484 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5485 5486 // Functions with 'interrupt' attribute cannot be called directly. 5487 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5488 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5489 return ExprError(); 5490 } 5491 5492 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5493 // so there's some risk when calling out to non-interrupt handler functions 5494 // that the callee might not preserve them. This is easy to diagnose here, 5495 // but can be very challenging to debug. 5496 if (auto *Caller = getCurFunctionDecl()) 5497 if (Caller->hasAttr<ARMInterruptAttr>()) { 5498 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5499 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5500 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5501 } 5502 5503 // Promote the function operand. 5504 // We special-case function promotion here because we only allow promoting 5505 // builtin functions to function pointers in the callee of a call. 5506 ExprResult Result; 5507 if (BuiltinID && 5508 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5509 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5510 CK_BuiltinFnToFnPtr).get(); 5511 } else { 5512 Result = CallExprUnaryConversions(Fn); 5513 } 5514 if (Result.isInvalid()) 5515 return ExprError(); 5516 Fn = Result.get(); 5517 5518 // Make the call expr early, before semantic checks. This guarantees cleanup 5519 // of arguments and function on error. 5520 CallExpr *TheCall; 5521 if (Config) 5522 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5523 cast<CallExpr>(Config), Args, 5524 Context.BoolTy, VK_RValue, 5525 RParenLoc); 5526 else 5527 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5528 VK_RValue, RParenLoc); 5529 5530 if (!getLangOpts().CPlusPlus) { 5531 // C cannot always handle TypoExpr nodes in builtin calls and direct 5532 // function calls as their argument checking don't necessarily handle 5533 // dependent types properly, so make sure any TypoExprs have been 5534 // dealt with. 5535 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5536 if (!Result.isUsable()) return ExprError(); 5537 TheCall = dyn_cast<CallExpr>(Result.get()); 5538 if (!TheCall) return Result; 5539 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5540 } 5541 5542 // Bail out early if calling a builtin with custom typechecking. 5543 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5544 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5545 5546 retry: 5547 const FunctionType *FuncT; 5548 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5549 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5550 // have type pointer to function". 5551 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5552 if (!FuncT) 5553 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5554 << Fn->getType() << Fn->getSourceRange()); 5555 } else if (const BlockPointerType *BPT = 5556 Fn->getType()->getAs<BlockPointerType>()) { 5557 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5558 } else { 5559 // Handle calls to expressions of unknown-any type. 5560 if (Fn->getType() == Context.UnknownAnyTy) { 5561 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5562 if (rewrite.isInvalid()) return ExprError(); 5563 Fn = rewrite.get(); 5564 TheCall->setCallee(Fn); 5565 goto retry; 5566 } 5567 5568 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5569 << Fn->getType() << Fn->getSourceRange()); 5570 } 5571 5572 if (getLangOpts().CUDA) { 5573 if (Config) { 5574 // CUDA: Kernel calls must be to global functions 5575 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5576 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5577 << FDecl << Fn->getSourceRange()); 5578 5579 // CUDA: Kernel function must have 'void' return type 5580 if (!FuncT->getReturnType()->isVoidType()) 5581 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5582 << Fn->getType() << Fn->getSourceRange()); 5583 } else { 5584 // CUDA: Calls to global functions must be configured 5585 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5586 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5587 << FDecl << Fn->getSourceRange()); 5588 } 5589 } 5590 5591 // Check for a valid return type 5592 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 5593 FDecl)) 5594 return ExprError(); 5595 5596 // We know the result type of the call, set it. 5597 TheCall->setType(FuncT->getCallResultType(Context)); 5598 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5599 5600 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5601 if (Proto) { 5602 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5603 IsExecConfig)) 5604 return ExprError(); 5605 } else { 5606 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5607 5608 if (FDecl) { 5609 // Check if we have too few/too many template arguments, based 5610 // on our knowledge of the function definition. 5611 const FunctionDecl *Def = nullptr; 5612 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5613 Proto = Def->getType()->getAs<FunctionProtoType>(); 5614 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5615 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5616 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5617 } 5618 5619 // If the function we're calling isn't a function prototype, but we have 5620 // a function prototype from a prior declaratiom, use that prototype. 5621 if (!FDecl->hasPrototype()) 5622 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5623 } 5624 5625 // Promote the arguments (C99 6.5.2.2p6). 5626 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5627 Expr *Arg = Args[i]; 5628 5629 if (Proto && i < Proto->getNumParams()) { 5630 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5631 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5632 ExprResult ArgE = 5633 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5634 if (ArgE.isInvalid()) 5635 return true; 5636 5637 Arg = ArgE.getAs<Expr>(); 5638 5639 } else { 5640 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5641 5642 if (ArgE.isInvalid()) 5643 return true; 5644 5645 Arg = ArgE.getAs<Expr>(); 5646 } 5647 5648 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 5649 diag::err_call_incomplete_argument, Arg)) 5650 return ExprError(); 5651 5652 TheCall->setArg(i, Arg); 5653 } 5654 } 5655 5656 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5657 if (!Method->isStatic()) 5658 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5659 << Fn->getSourceRange()); 5660 5661 // Check for sentinels 5662 if (NDecl) 5663 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5664 5665 // Do special checking on direct calls to functions. 5666 if (FDecl) { 5667 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5668 return ExprError(); 5669 5670 if (BuiltinID) 5671 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5672 } else if (NDecl) { 5673 if (CheckPointerCall(NDecl, TheCall, Proto)) 5674 return ExprError(); 5675 } else { 5676 if (CheckOtherCall(TheCall, Proto)) 5677 return ExprError(); 5678 } 5679 5680 return MaybeBindToTemporary(TheCall); 5681 } 5682 5683 ExprResult 5684 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5685 SourceLocation RParenLoc, Expr *InitExpr) { 5686 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5687 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5688 5689 TypeSourceInfo *TInfo; 5690 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5691 if (!TInfo) 5692 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5693 5694 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5695 } 5696 5697 ExprResult 5698 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5699 SourceLocation RParenLoc, Expr *LiteralExpr) { 5700 QualType literalType = TInfo->getType(); 5701 5702 if (literalType->isArrayType()) { 5703 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5704 diag::err_illegal_decl_array_incomplete_type, 5705 SourceRange(LParenLoc, 5706 LiteralExpr->getSourceRange().getEnd()))) 5707 return ExprError(); 5708 if (literalType->isVariableArrayType()) 5709 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5710 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5711 } else if (!literalType->isDependentType() && 5712 RequireCompleteType(LParenLoc, literalType, 5713 diag::err_typecheck_decl_incomplete_type, 5714 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5715 return ExprError(); 5716 5717 InitializedEntity Entity 5718 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5719 InitializationKind Kind 5720 = InitializationKind::CreateCStyleCast(LParenLoc, 5721 SourceRange(LParenLoc, RParenLoc), 5722 /*InitList=*/true); 5723 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5724 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5725 &literalType); 5726 if (Result.isInvalid()) 5727 return ExprError(); 5728 LiteralExpr = Result.get(); 5729 5730 bool isFileScope = !CurContext->isFunctionOrMethod(); 5731 if (isFileScope) { 5732 if (!LiteralExpr->isTypeDependent() && 5733 !LiteralExpr->isValueDependent() && 5734 !literalType->isDependentType()) // C99 6.5.2.5p3 5735 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5736 return ExprError(); 5737 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 5738 literalType.getAddressSpace() != LangAS::Default) { 5739 // Embedded-C extensions to C99 6.5.2.5: 5740 // "If the compound literal occurs inside the body of a function, the 5741 // type name shall not be qualified by an address-space qualifier." 5742 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 5743 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 5744 return ExprError(); 5745 } 5746 5747 // In C, compound literals are l-values for some reason. 5748 // For GCC compatibility, in C++, file-scope array compound literals with 5749 // constant initializers are also l-values, and compound literals are 5750 // otherwise prvalues. 5751 // 5752 // (GCC also treats C++ list-initialized file-scope array prvalues with 5753 // constant initializers as l-values, but that's non-conforming, so we don't 5754 // follow it there.) 5755 // 5756 // FIXME: It would be better to handle the lvalue cases as materializing and 5757 // lifetime-extending a temporary object, but our materialized temporaries 5758 // representation only supports lifetime extension from a variable, not "out 5759 // of thin air". 5760 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5761 // is bound to the result of applying array-to-pointer decay to the compound 5762 // literal. 5763 // FIXME: GCC supports compound literals of reference type, which should 5764 // obviously have a value kind derived from the kind of reference involved. 5765 ExprValueKind VK = 5766 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5767 ? VK_RValue 5768 : VK_LValue; 5769 5770 return MaybeBindToTemporary( 5771 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5772 VK, LiteralExpr, isFileScope)); 5773 } 5774 5775 ExprResult 5776 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5777 SourceLocation RBraceLoc) { 5778 // Immediately handle non-overload placeholders. Overloads can be 5779 // resolved contextually, but everything else here can't. 5780 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5781 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5782 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5783 5784 // Ignore failures; dropping the entire initializer list because 5785 // of one failure would be terrible for indexing/etc. 5786 if (result.isInvalid()) continue; 5787 5788 InitArgList[I] = result.get(); 5789 } 5790 } 5791 5792 // Semantic analysis for initializers is done by ActOnDeclarator() and 5793 // CheckInitializer() - it requires knowledge of the object being initialized. 5794 5795 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5796 RBraceLoc); 5797 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5798 return E; 5799 } 5800 5801 /// Do an explicit extend of the given block pointer if we're in ARC. 5802 void Sema::maybeExtendBlockObject(ExprResult &E) { 5803 assert(E.get()->getType()->isBlockPointerType()); 5804 assert(E.get()->isRValue()); 5805 5806 // Only do this in an r-value context. 5807 if (!getLangOpts().ObjCAutoRefCount) return; 5808 5809 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5810 CK_ARCExtendBlockObject, E.get(), 5811 /*base path*/ nullptr, VK_RValue); 5812 Cleanup.setExprNeedsCleanups(true); 5813 } 5814 5815 /// Prepare a conversion of the given expression to an ObjC object 5816 /// pointer type. 5817 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5818 QualType type = E.get()->getType(); 5819 if (type->isObjCObjectPointerType()) { 5820 return CK_BitCast; 5821 } else if (type->isBlockPointerType()) { 5822 maybeExtendBlockObject(E); 5823 return CK_BlockPointerToObjCPointerCast; 5824 } else { 5825 assert(type->isPointerType()); 5826 return CK_CPointerToObjCPointerCast; 5827 } 5828 } 5829 5830 /// Prepares for a scalar cast, performing all the necessary stages 5831 /// except the final cast and returning the kind required. 5832 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5833 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5834 // Also, callers should have filtered out the invalid cases with 5835 // pointers. Everything else should be possible. 5836 5837 QualType SrcTy = Src.get()->getType(); 5838 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5839 return CK_NoOp; 5840 5841 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5842 case Type::STK_MemberPointer: 5843 llvm_unreachable("member pointer type in C"); 5844 5845 case Type::STK_CPointer: 5846 case Type::STK_BlockPointer: 5847 case Type::STK_ObjCObjectPointer: 5848 switch (DestTy->getScalarTypeKind()) { 5849 case Type::STK_CPointer: { 5850 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5851 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 5852 if (SrcAS != DestAS) 5853 return CK_AddressSpaceConversion; 5854 return CK_BitCast; 5855 } 5856 case Type::STK_BlockPointer: 5857 return (SrcKind == Type::STK_BlockPointer 5858 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5859 case Type::STK_ObjCObjectPointer: 5860 if (SrcKind == Type::STK_ObjCObjectPointer) 5861 return CK_BitCast; 5862 if (SrcKind == Type::STK_CPointer) 5863 return CK_CPointerToObjCPointerCast; 5864 maybeExtendBlockObject(Src); 5865 return CK_BlockPointerToObjCPointerCast; 5866 case Type::STK_Bool: 5867 return CK_PointerToBoolean; 5868 case Type::STK_Integral: 5869 return CK_PointerToIntegral; 5870 case Type::STK_Floating: 5871 case Type::STK_FloatingComplex: 5872 case Type::STK_IntegralComplex: 5873 case Type::STK_MemberPointer: 5874 llvm_unreachable("illegal cast from pointer"); 5875 } 5876 llvm_unreachable("Should have returned before this"); 5877 5878 case Type::STK_Bool: // casting from bool is like casting from an integer 5879 case Type::STK_Integral: 5880 switch (DestTy->getScalarTypeKind()) { 5881 case Type::STK_CPointer: 5882 case Type::STK_ObjCObjectPointer: 5883 case Type::STK_BlockPointer: 5884 if (Src.get()->isNullPointerConstant(Context, 5885 Expr::NPC_ValueDependentIsNull)) 5886 return CK_NullToPointer; 5887 return CK_IntegralToPointer; 5888 case Type::STK_Bool: 5889 return CK_IntegralToBoolean; 5890 case Type::STK_Integral: 5891 return CK_IntegralCast; 5892 case Type::STK_Floating: 5893 return CK_IntegralToFloating; 5894 case Type::STK_IntegralComplex: 5895 Src = ImpCastExprToType(Src.get(), 5896 DestTy->castAs<ComplexType>()->getElementType(), 5897 CK_IntegralCast); 5898 return CK_IntegralRealToComplex; 5899 case Type::STK_FloatingComplex: 5900 Src = ImpCastExprToType(Src.get(), 5901 DestTy->castAs<ComplexType>()->getElementType(), 5902 CK_IntegralToFloating); 5903 return CK_FloatingRealToComplex; 5904 case Type::STK_MemberPointer: 5905 llvm_unreachable("member pointer type in C"); 5906 } 5907 llvm_unreachable("Should have returned before this"); 5908 5909 case Type::STK_Floating: 5910 switch (DestTy->getScalarTypeKind()) { 5911 case Type::STK_Floating: 5912 return CK_FloatingCast; 5913 case Type::STK_Bool: 5914 return CK_FloatingToBoolean; 5915 case Type::STK_Integral: 5916 return CK_FloatingToIntegral; 5917 case Type::STK_FloatingComplex: 5918 Src = ImpCastExprToType(Src.get(), 5919 DestTy->castAs<ComplexType>()->getElementType(), 5920 CK_FloatingCast); 5921 return CK_FloatingRealToComplex; 5922 case Type::STK_IntegralComplex: 5923 Src = ImpCastExprToType(Src.get(), 5924 DestTy->castAs<ComplexType>()->getElementType(), 5925 CK_FloatingToIntegral); 5926 return CK_IntegralRealToComplex; 5927 case Type::STK_CPointer: 5928 case Type::STK_ObjCObjectPointer: 5929 case Type::STK_BlockPointer: 5930 llvm_unreachable("valid float->pointer cast?"); 5931 case Type::STK_MemberPointer: 5932 llvm_unreachable("member pointer type in C"); 5933 } 5934 llvm_unreachable("Should have returned before this"); 5935 5936 case Type::STK_FloatingComplex: 5937 switch (DestTy->getScalarTypeKind()) { 5938 case Type::STK_FloatingComplex: 5939 return CK_FloatingComplexCast; 5940 case Type::STK_IntegralComplex: 5941 return CK_FloatingComplexToIntegralComplex; 5942 case Type::STK_Floating: { 5943 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5944 if (Context.hasSameType(ET, DestTy)) 5945 return CK_FloatingComplexToReal; 5946 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5947 return CK_FloatingCast; 5948 } 5949 case Type::STK_Bool: 5950 return CK_FloatingComplexToBoolean; 5951 case Type::STK_Integral: 5952 Src = ImpCastExprToType(Src.get(), 5953 SrcTy->castAs<ComplexType>()->getElementType(), 5954 CK_FloatingComplexToReal); 5955 return CK_FloatingToIntegral; 5956 case Type::STK_CPointer: 5957 case Type::STK_ObjCObjectPointer: 5958 case Type::STK_BlockPointer: 5959 llvm_unreachable("valid complex float->pointer cast?"); 5960 case Type::STK_MemberPointer: 5961 llvm_unreachable("member pointer type in C"); 5962 } 5963 llvm_unreachable("Should have returned before this"); 5964 5965 case Type::STK_IntegralComplex: 5966 switch (DestTy->getScalarTypeKind()) { 5967 case Type::STK_FloatingComplex: 5968 return CK_IntegralComplexToFloatingComplex; 5969 case Type::STK_IntegralComplex: 5970 return CK_IntegralComplexCast; 5971 case Type::STK_Integral: { 5972 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5973 if (Context.hasSameType(ET, DestTy)) 5974 return CK_IntegralComplexToReal; 5975 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5976 return CK_IntegralCast; 5977 } 5978 case Type::STK_Bool: 5979 return CK_IntegralComplexToBoolean; 5980 case Type::STK_Floating: 5981 Src = ImpCastExprToType(Src.get(), 5982 SrcTy->castAs<ComplexType>()->getElementType(), 5983 CK_IntegralComplexToReal); 5984 return CK_IntegralToFloating; 5985 case Type::STK_CPointer: 5986 case Type::STK_ObjCObjectPointer: 5987 case Type::STK_BlockPointer: 5988 llvm_unreachable("valid complex int->pointer cast?"); 5989 case Type::STK_MemberPointer: 5990 llvm_unreachable("member pointer type in C"); 5991 } 5992 llvm_unreachable("Should have returned before this"); 5993 } 5994 5995 llvm_unreachable("Unhandled scalar cast"); 5996 } 5997 5998 static bool breakDownVectorType(QualType type, uint64_t &len, 5999 QualType &eltType) { 6000 // Vectors are simple. 6001 if (const VectorType *vecType = type->getAs<VectorType>()) { 6002 len = vecType->getNumElements(); 6003 eltType = vecType->getElementType(); 6004 assert(eltType->isScalarType()); 6005 return true; 6006 } 6007 6008 // We allow lax conversion to and from non-vector types, but only if 6009 // they're real types (i.e. non-complex, non-pointer scalar types). 6010 if (!type->isRealType()) return false; 6011 6012 len = 1; 6013 eltType = type; 6014 return true; 6015 } 6016 6017 /// Are the two types lax-compatible vector types? That is, given 6018 /// that one of them is a vector, do they have equal storage sizes, 6019 /// where the storage size is the number of elements times the element 6020 /// size? 6021 /// 6022 /// This will also return false if either of the types is neither a 6023 /// vector nor a real type. 6024 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 6025 assert(destTy->isVectorType() || srcTy->isVectorType()); 6026 6027 // Disallow lax conversions between scalars and ExtVectors (these 6028 // conversions are allowed for other vector types because common headers 6029 // depend on them). Most scalar OP ExtVector cases are handled by the 6030 // splat path anyway, which does what we want (convert, not bitcast). 6031 // What this rules out for ExtVectors is crazy things like char4*float. 6032 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 6033 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 6034 6035 uint64_t srcLen, destLen; 6036 QualType srcEltTy, destEltTy; 6037 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 6038 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 6039 6040 // ASTContext::getTypeSize will return the size rounded up to a 6041 // power of 2, so instead of using that, we need to use the raw 6042 // element size multiplied by the element count. 6043 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 6044 uint64_t destEltSize = Context.getTypeSize(destEltTy); 6045 6046 return (srcLen * srcEltSize == destLen * destEltSize); 6047 } 6048 6049 /// Is this a legal conversion between two types, one of which is 6050 /// known to be a vector type? 6051 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6052 assert(destTy->isVectorType() || srcTy->isVectorType()); 6053 6054 if (!Context.getLangOpts().LaxVectorConversions) 6055 return false; 6056 return areLaxCompatibleVectorTypes(srcTy, destTy); 6057 } 6058 6059 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6060 CastKind &Kind) { 6061 assert(VectorTy->isVectorType() && "Not a vector type!"); 6062 6063 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 6064 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 6065 return Diag(R.getBegin(), 6066 Ty->isVectorType() ? 6067 diag::err_invalid_conversion_between_vectors : 6068 diag::err_invalid_conversion_between_vector_and_integer) 6069 << VectorTy << Ty << R; 6070 } else 6071 return Diag(R.getBegin(), 6072 diag::err_invalid_conversion_between_vector_and_scalar) 6073 << VectorTy << Ty << R; 6074 6075 Kind = CK_BitCast; 6076 return false; 6077 } 6078 6079 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6080 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6081 6082 if (DestElemTy == SplattedExpr->getType()) 6083 return SplattedExpr; 6084 6085 assert(DestElemTy->isFloatingType() || 6086 DestElemTy->isIntegralOrEnumerationType()); 6087 6088 CastKind CK; 6089 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6090 // OpenCL requires that we convert `true` boolean expressions to -1, but 6091 // only when splatting vectors. 6092 if (DestElemTy->isFloatingType()) { 6093 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6094 // in two steps: boolean to signed integral, then to floating. 6095 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6096 CK_BooleanToSignedIntegral); 6097 SplattedExpr = CastExprRes.get(); 6098 CK = CK_IntegralToFloating; 6099 } else { 6100 CK = CK_BooleanToSignedIntegral; 6101 } 6102 } else { 6103 ExprResult CastExprRes = SplattedExpr; 6104 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6105 if (CastExprRes.isInvalid()) 6106 return ExprError(); 6107 SplattedExpr = CastExprRes.get(); 6108 } 6109 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6110 } 6111 6112 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6113 Expr *CastExpr, CastKind &Kind) { 6114 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6115 6116 QualType SrcTy = CastExpr->getType(); 6117 6118 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6119 // an ExtVectorType. 6120 // In OpenCL, casts between vectors of different types are not allowed. 6121 // (See OpenCL 6.2). 6122 if (SrcTy->isVectorType()) { 6123 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6124 (getLangOpts().OpenCL && 6125 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6126 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6127 << DestTy << SrcTy << R; 6128 return ExprError(); 6129 } 6130 Kind = CK_BitCast; 6131 return CastExpr; 6132 } 6133 6134 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6135 // conversion will take place first from scalar to elt type, and then 6136 // splat from elt type to vector. 6137 if (SrcTy->isPointerType()) 6138 return Diag(R.getBegin(), 6139 diag::err_invalid_conversion_between_vector_and_scalar) 6140 << DestTy << SrcTy << R; 6141 6142 Kind = CK_VectorSplat; 6143 return prepareVectorSplat(DestTy, CastExpr); 6144 } 6145 6146 ExprResult 6147 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6148 Declarator &D, ParsedType &Ty, 6149 SourceLocation RParenLoc, Expr *CastExpr) { 6150 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6151 "ActOnCastExpr(): missing type or expr"); 6152 6153 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6154 if (D.isInvalidType()) 6155 return ExprError(); 6156 6157 if (getLangOpts().CPlusPlus) { 6158 // Check that there are no default arguments (C++ only). 6159 CheckExtraCXXDefaultArguments(D); 6160 } else { 6161 // Make sure any TypoExprs have been dealt with. 6162 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6163 if (!Res.isUsable()) 6164 return ExprError(); 6165 CastExpr = Res.get(); 6166 } 6167 6168 checkUnusedDeclAttributes(D); 6169 6170 QualType castType = castTInfo->getType(); 6171 Ty = CreateParsedType(castType, castTInfo); 6172 6173 bool isVectorLiteral = false; 6174 6175 // Check for an altivec or OpenCL literal, 6176 // i.e. all the elements are integer constants. 6177 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6178 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6179 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6180 && castType->isVectorType() && (PE || PLE)) { 6181 if (PLE && PLE->getNumExprs() == 0) { 6182 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6183 return ExprError(); 6184 } 6185 if (PE || PLE->getNumExprs() == 1) { 6186 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6187 if (!E->getType()->isVectorType()) 6188 isVectorLiteral = true; 6189 } 6190 else 6191 isVectorLiteral = true; 6192 } 6193 6194 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6195 // then handle it as such. 6196 if (isVectorLiteral) 6197 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6198 6199 // If the Expr being casted is a ParenListExpr, handle it specially. 6200 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6201 // sequence of BinOp comma operators. 6202 if (isa<ParenListExpr>(CastExpr)) { 6203 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6204 if (Result.isInvalid()) return ExprError(); 6205 CastExpr = Result.get(); 6206 } 6207 6208 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6209 !getSourceManager().isInSystemMacro(LParenLoc)) 6210 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6211 6212 CheckTollFreeBridgeCast(castType, CastExpr); 6213 6214 CheckObjCBridgeRelatedCast(castType, CastExpr); 6215 6216 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6217 6218 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6219 } 6220 6221 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6222 SourceLocation RParenLoc, Expr *E, 6223 TypeSourceInfo *TInfo) { 6224 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6225 "Expected paren or paren list expression"); 6226 6227 Expr **exprs; 6228 unsigned numExprs; 6229 Expr *subExpr; 6230 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6231 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6232 LiteralLParenLoc = PE->getLParenLoc(); 6233 LiteralRParenLoc = PE->getRParenLoc(); 6234 exprs = PE->getExprs(); 6235 numExprs = PE->getNumExprs(); 6236 } else { // isa<ParenExpr> by assertion at function entrance 6237 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6238 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6239 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6240 exprs = &subExpr; 6241 numExprs = 1; 6242 } 6243 6244 QualType Ty = TInfo->getType(); 6245 assert(Ty->isVectorType() && "Expected vector type"); 6246 6247 SmallVector<Expr *, 8> initExprs; 6248 const VectorType *VTy = Ty->getAs<VectorType>(); 6249 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6250 6251 // '(...)' form of vector initialization in AltiVec: the number of 6252 // initializers must be one or must match the size of the vector. 6253 // If a single value is specified in the initializer then it will be 6254 // replicated to all the components of the vector 6255 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6256 // The number of initializers must be one or must match the size of the 6257 // vector. If a single value is specified in the initializer then it will 6258 // be replicated to all the components of the vector 6259 if (numExprs == 1) { 6260 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6261 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6262 if (Literal.isInvalid()) 6263 return ExprError(); 6264 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6265 PrepareScalarCast(Literal, ElemTy)); 6266 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6267 } 6268 else if (numExprs < numElems) { 6269 Diag(E->getExprLoc(), 6270 diag::err_incorrect_number_of_vector_initializers); 6271 return ExprError(); 6272 } 6273 else 6274 initExprs.append(exprs, exprs + numExprs); 6275 } 6276 else { 6277 // For OpenCL, when the number of initializers is a single value, 6278 // it will be replicated to all components of the vector. 6279 if (getLangOpts().OpenCL && 6280 VTy->getVectorKind() == VectorType::GenericVector && 6281 numExprs == 1) { 6282 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6283 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6284 if (Literal.isInvalid()) 6285 return ExprError(); 6286 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6287 PrepareScalarCast(Literal, ElemTy)); 6288 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6289 } 6290 6291 initExprs.append(exprs, exprs + numExprs); 6292 } 6293 // FIXME: This means that pretty-printing the final AST will produce curly 6294 // braces instead of the original commas. 6295 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6296 initExprs, LiteralRParenLoc); 6297 initE->setType(Ty); 6298 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6299 } 6300 6301 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6302 /// the ParenListExpr into a sequence of comma binary operators. 6303 ExprResult 6304 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6305 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6306 if (!E) 6307 return OrigExpr; 6308 6309 ExprResult Result(E->getExpr(0)); 6310 6311 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6312 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6313 E->getExpr(i)); 6314 6315 if (Result.isInvalid()) return ExprError(); 6316 6317 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6318 } 6319 6320 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6321 SourceLocation R, 6322 MultiExprArg Val) { 6323 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 6324 return expr; 6325 } 6326 6327 /// Emit a specialized diagnostic when one expression is a null pointer 6328 /// constant and the other is not a pointer. Returns true if a diagnostic is 6329 /// emitted. 6330 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6331 SourceLocation QuestionLoc) { 6332 Expr *NullExpr = LHSExpr; 6333 Expr *NonPointerExpr = RHSExpr; 6334 Expr::NullPointerConstantKind NullKind = 6335 NullExpr->isNullPointerConstant(Context, 6336 Expr::NPC_ValueDependentIsNotNull); 6337 6338 if (NullKind == Expr::NPCK_NotNull) { 6339 NullExpr = RHSExpr; 6340 NonPointerExpr = LHSExpr; 6341 NullKind = 6342 NullExpr->isNullPointerConstant(Context, 6343 Expr::NPC_ValueDependentIsNotNull); 6344 } 6345 6346 if (NullKind == Expr::NPCK_NotNull) 6347 return false; 6348 6349 if (NullKind == Expr::NPCK_ZeroExpression) 6350 return false; 6351 6352 if (NullKind == Expr::NPCK_ZeroLiteral) { 6353 // In this case, check to make sure that we got here from a "NULL" 6354 // string in the source code. 6355 NullExpr = NullExpr->IgnoreParenImpCasts(); 6356 SourceLocation loc = NullExpr->getExprLoc(); 6357 if (!findMacroSpelling(loc, "NULL")) 6358 return false; 6359 } 6360 6361 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6362 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6363 << NonPointerExpr->getType() << DiagType 6364 << NonPointerExpr->getSourceRange(); 6365 return true; 6366 } 6367 6368 /// Return false if the condition expression is valid, true otherwise. 6369 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6370 QualType CondTy = Cond->getType(); 6371 6372 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6373 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6374 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6375 << CondTy << Cond->getSourceRange(); 6376 return true; 6377 } 6378 6379 // C99 6.5.15p2 6380 if (CondTy->isScalarType()) return false; 6381 6382 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6383 << CondTy << Cond->getSourceRange(); 6384 return true; 6385 } 6386 6387 /// Handle when one or both operands are void type. 6388 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6389 ExprResult &RHS) { 6390 Expr *LHSExpr = LHS.get(); 6391 Expr *RHSExpr = RHS.get(); 6392 6393 if (!LHSExpr->getType()->isVoidType()) 6394 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6395 << RHSExpr->getSourceRange(); 6396 if (!RHSExpr->getType()->isVoidType()) 6397 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6398 << LHSExpr->getSourceRange(); 6399 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6400 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6401 return S.Context.VoidTy; 6402 } 6403 6404 /// Return false if the NullExpr can be promoted to PointerTy, 6405 /// true otherwise. 6406 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6407 QualType PointerTy) { 6408 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6409 !NullExpr.get()->isNullPointerConstant(S.Context, 6410 Expr::NPC_ValueDependentIsNull)) 6411 return true; 6412 6413 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6414 return false; 6415 } 6416 6417 /// Checks compatibility between two pointers and return the resulting 6418 /// type. 6419 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6420 ExprResult &RHS, 6421 SourceLocation Loc) { 6422 QualType LHSTy = LHS.get()->getType(); 6423 QualType RHSTy = RHS.get()->getType(); 6424 6425 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6426 // Two identical pointers types are always compatible. 6427 return LHSTy; 6428 } 6429 6430 QualType lhptee, rhptee; 6431 6432 // Get the pointee types. 6433 bool IsBlockPointer = false; 6434 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6435 lhptee = LHSBTy->getPointeeType(); 6436 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6437 IsBlockPointer = true; 6438 } else { 6439 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6440 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6441 } 6442 6443 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6444 // differently qualified versions of compatible types, the result type is 6445 // a pointer to an appropriately qualified version of the composite 6446 // type. 6447 6448 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6449 // clause doesn't make sense for our extensions. E.g. address space 2 should 6450 // be incompatible with address space 3: they may live on different devices or 6451 // anything. 6452 Qualifiers lhQual = lhptee.getQualifiers(); 6453 Qualifiers rhQual = rhptee.getQualifiers(); 6454 6455 LangAS ResultAddrSpace = LangAS::Default; 6456 LangAS LAddrSpace = lhQual.getAddressSpace(); 6457 LangAS RAddrSpace = rhQual.getAddressSpace(); 6458 6459 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6460 // spaces is disallowed. 6461 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6462 ResultAddrSpace = LAddrSpace; 6463 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6464 ResultAddrSpace = RAddrSpace; 6465 else { 6466 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6467 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6468 << RHS.get()->getSourceRange(); 6469 return QualType(); 6470 } 6471 6472 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6473 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6474 lhQual.removeCVRQualifiers(); 6475 rhQual.removeCVRQualifiers(); 6476 6477 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6478 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6479 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6480 // qual types are compatible iff 6481 // * corresponded types are compatible 6482 // * CVR qualifiers are equal 6483 // * address spaces are equal 6484 // Thus for conditional operator we merge CVR and address space unqualified 6485 // pointees and if there is a composite type we return a pointer to it with 6486 // merged qualifiers. 6487 LHSCastKind = 6488 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6489 RHSCastKind = 6490 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6491 lhQual.removeAddressSpace(); 6492 rhQual.removeAddressSpace(); 6493 6494 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6495 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6496 6497 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6498 6499 if (CompositeTy.isNull()) { 6500 // In this situation, we assume void* type. No especially good 6501 // reason, but this is what gcc does, and we do have to pick 6502 // to get a consistent AST. 6503 QualType incompatTy; 6504 incompatTy = S.Context.getPointerType( 6505 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6506 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6507 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6508 6509 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6510 // for casts between types with incompatible address space qualifiers. 6511 // For the following code the compiler produces casts between global and 6512 // local address spaces of the corresponded innermost pointees: 6513 // local int *global *a; 6514 // global int *global *b; 6515 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6516 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6517 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6518 << RHS.get()->getSourceRange(); 6519 6520 return incompatTy; 6521 } 6522 6523 // The pointer types are compatible. 6524 // In case of OpenCL ResultTy should have the address space qualifier 6525 // which is a superset of address spaces of both the 2nd and the 3rd 6526 // operands of the conditional operator. 6527 QualType ResultTy = [&, ResultAddrSpace]() { 6528 if (S.getLangOpts().OpenCL) { 6529 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6530 CompositeQuals.setAddressSpace(ResultAddrSpace); 6531 return S.Context 6532 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6533 .withCVRQualifiers(MergedCVRQual); 6534 } 6535 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6536 }(); 6537 if (IsBlockPointer) 6538 ResultTy = S.Context.getBlockPointerType(ResultTy); 6539 else 6540 ResultTy = S.Context.getPointerType(ResultTy); 6541 6542 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6543 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6544 return ResultTy; 6545 } 6546 6547 /// Return the resulting type when the operands are both block pointers. 6548 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6549 ExprResult &LHS, 6550 ExprResult &RHS, 6551 SourceLocation Loc) { 6552 QualType LHSTy = LHS.get()->getType(); 6553 QualType RHSTy = RHS.get()->getType(); 6554 6555 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6556 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6557 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6558 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6559 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6560 return destType; 6561 } 6562 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6563 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6564 << RHS.get()->getSourceRange(); 6565 return QualType(); 6566 } 6567 6568 // We have 2 block pointer types. 6569 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6570 } 6571 6572 /// Return the resulting type when the operands are both pointers. 6573 static QualType 6574 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6575 ExprResult &RHS, 6576 SourceLocation Loc) { 6577 // get the pointer types 6578 QualType LHSTy = LHS.get()->getType(); 6579 QualType RHSTy = RHS.get()->getType(); 6580 6581 // get the "pointed to" types 6582 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6583 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6584 6585 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6586 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6587 // Figure out necessary qualifiers (C99 6.5.15p6) 6588 QualType destPointee 6589 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6590 QualType destType = S.Context.getPointerType(destPointee); 6591 // Add qualifiers if necessary. 6592 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6593 // Promote to void*. 6594 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6595 return destType; 6596 } 6597 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6598 QualType destPointee 6599 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6600 QualType destType = S.Context.getPointerType(destPointee); 6601 // Add qualifiers if necessary. 6602 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6603 // Promote to void*. 6604 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6605 return destType; 6606 } 6607 6608 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6609 } 6610 6611 /// Return false if the first expression is not an integer and the second 6612 /// expression is not a pointer, true otherwise. 6613 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6614 Expr* PointerExpr, SourceLocation Loc, 6615 bool IsIntFirstExpr) { 6616 if (!PointerExpr->getType()->isPointerType() || 6617 !Int.get()->getType()->isIntegerType()) 6618 return false; 6619 6620 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6621 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6622 6623 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6624 << Expr1->getType() << Expr2->getType() 6625 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6626 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6627 CK_IntegralToPointer); 6628 return true; 6629 } 6630 6631 /// Simple conversion between integer and floating point types. 6632 /// 6633 /// Used when handling the OpenCL conditional operator where the 6634 /// condition is a vector while the other operands are scalar. 6635 /// 6636 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6637 /// types are either integer or floating type. Between the two 6638 /// operands, the type with the higher rank is defined as the "result 6639 /// type". The other operand needs to be promoted to the same type. No 6640 /// other type promotion is allowed. We cannot use 6641 /// UsualArithmeticConversions() for this purpose, since it always 6642 /// promotes promotable types. 6643 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6644 ExprResult &RHS, 6645 SourceLocation QuestionLoc) { 6646 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6647 if (LHS.isInvalid()) 6648 return QualType(); 6649 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6650 if (RHS.isInvalid()) 6651 return QualType(); 6652 6653 // For conversion purposes, we ignore any qualifiers. 6654 // For example, "const float" and "float" are equivalent. 6655 QualType LHSType = 6656 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6657 QualType RHSType = 6658 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6659 6660 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6661 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6662 << LHSType << LHS.get()->getSourceRange(); 6663 return QualType(); 6664 } 6665 6666 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6667 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6668 << RHSType << RHS.get()->getSourceRange(); 6669 return QualType(); 6670 } 6671 6672 // If both types are identical, no conversion is needed. 6673 if (LHSType == RHSType) 6674 return LHSType; 6675 6676 // Now handle "real" floating types (i.e. float, double, long double). 6677 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6678 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6679 /*IsCompAssign = */ false); 6680 6681 // Finally, we have two differing integer types. 6682 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6683 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6684 } 6685 6686 /// Convert scalar operands to a vector that matches the 6687 /// condition in length. 6688 /// 6689 /// Used when handling the OpenCL conditional operator where the 6690 /// condition is a vector while the other operands are scalar. 6691 /// 6692 /// We first compute the "result type" for the scalar operands 6693 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6694 /// into a vector of that type where the length matches the condition 6695 /// vector type. s6.11.6 requires that the element types of the result 6696 /// and the condition must have the same number of bits. 6697 static QualType 6698 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6699 QualType CondTy, SourceLocation QuestionLoc) { 6700 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6701 if (ResTy.isNull()) return QualType(); 6702 6703 const VectorType *CV = CondTy->getAs<VectorType>(); 6704 assert(CV); 6705 6706 // Determine the vector result type 6707 unsigned NumElements = CV->getNumElements(); 6708 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6709 6710 // Ensure that all types have the same number of bits 6711 if (S.Context.getTypeSize(CV->getElementType()) 6712 != S.Context.getTypeSize(ResTy)) { 6713 // Since VectorTy is created internally, it does not pretty print 6714 // with an OpenCL name. Instead, we just print a description. 6715 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6716 SmallString<64> Str; 6717 llvm::raw_svector_ostream OS(Str); 6718 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6719 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6720 << CondTy << OS.str(); 6721 return QualType(); 6722 } 6723 6724 // Convert operands to the vector result type 6725 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6726 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6727 6728 return VectorTy; 6729 } 6730 6731 /// Return false if this is a valid OpenCL condition vector 6732 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6733 SourceLocation QuestionLoc) { 6734 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6735 // integral type. 6736 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6737 assert(CondTy); 6738 QualType EleTy = CondTy->getElementType(); 6739 if (EleTy->isIntegerType()) return false; 6740 6741 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6742 << Cond->getType() << Cond->getSourceRange(); 6743 return true; 6744 } 6745 6746 /// Return false if the vector condition type and the vector 6747 /// result type are compatible. 6748 /// 6749 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6750 /// number of elements, and their element types have the same number 6751 /// of bits. 6752 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6753 SourceLocation QuestionLoc) { 6754 const VectorType *CV = CondTy->getAs<VectorType>(); 6755 const VectorType *RV = VecResTy->getAs<VectorType>(); 6756 assert(CV && RV); 6757 6758 if (CV->getNumElements() != RV->getNumElements()) { 6759 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6760 << CondTy << VecResTy; 6761 return true; 6762 } 6763 6764 QualType CVE = CV->getElementType(); 6765 QualType RVE = RV->getElementType(); 6766 6767 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6768 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6769 << CondTy << VecResTy; 6770 return true; 6771 } 6772 6773 return false; 6774 } 6775 6776 /// Return the resulting type for the conditional operator in 6777 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6778 /// s6.3.i) when the condition is a vector type. 6779 static QualType 6780 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6781 ExprResult &LHS, ExprResult &RHS, 6782 SourceLocation QuestionLoc) { 6783 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6784 if (Cond.isInvalid()) 6785 return QualType(); 6786 QualType CondTy = Cond.get()->getType(); 6787 6788 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6789 return QualType(); 6790 6791 // If either operand is a vector then find the vector type of the 6792 // result as specified in OpenCL v1.1 s6.3.i. 6793 if (LHS.get()->getType()->isVectorType() || 6794 RHS.get()->getType()->isVectorType()) { 6795 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6796 /*isCompAssign*/false, 6797 /*AllowBothBool*/true, 6798 /*AllowBoolConversions*/false); 6799 if (VecResTy.isNull()) return QualType(); 6800 // The result type must match the condition type as specified in 6801 // OpenCL v1.1 s6.11.6. 6802 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6803 return QualType(); 6804 return VecResTy; 6805 } 6806 6807 // Both operands are scalar. 6808 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6809 } 6810 6811 /// Return true if the Expr is block type 6812 static bool checkBlockType(Sema &S, const Expr *E) { 6813 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6814 QualType Ty = CE->getCallee()->getType(); 6815 if (Ty->isBlockPointerType()) { 6816 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6817 return true; 6818 } 6819 } 6820 return false; 6821 } 6822 6823 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6824 /// In that case, LHS = cond. 6825 /// C99 6.5.15 6826 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6827 ExprResult &RHS, ExprValueKind &VK, 6828 ExprObjectKind &OK, 6829 SourceLocation QuestionLoc) { 6830 6831 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6832 if (!LHSResult.isUsable()) return QualType(); 6833 LHS = LHSResult; 6834 6835 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6836 if (!RHSResult.isUsable()) return QualType(); 6837 RHS = RHSResult; 6838 6839 // C++ is sufficiently different to merit its own checker. 6840 if (getLangOpts().CPlusPlus) 6841 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6842 6843 VK = VK_RValue; 6844 OK = OK_Ordinary; 6845 6846 // The OpenCL operator with a vector condition is sufficiently 6847 // different to merit its own checker. 6848 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6849 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6850 6851 // First, check the condition. 6852 Cond = UsualUnaryConversions(Cond.get()); 6853 if (Cond.isInvalid()) 6854 return QualType(); 6855 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6856 return QualType(); 6857 6858 // Now check the two expressions. 6859 if (LHS.get()->getType()->isVectorType() || 6860 RHS.get()->getType()->isVectorType()) 6861 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6862 /*AllowBothBool*/true, 6863 /*AllowBoolConversions*/false); 6864 6865 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6866 if (LHS.isInvalid() || RHS.isInvalid()) 6867 return QualType(); 6868 6869 QualType LHSTy = LHS.get()->getType(); 6870 QualType RHSTy = RHS.get()->getType(); 6871 6872 // Diagnose attempts to convert between __float128 and long double where 6873 // such conversions currently can't be handled. 6874 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 6875 Diag(QuestionLoc, 6876 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 6877 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6878 return QualType(); 6879 } 6880 6881 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 6882 // selection operator (?:). 6883 if (getLangOpts().OpenCL && 6884 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 6885 return QualType(); 6886 } 6887 6888 // If both operands have arithmetic type, do the usual arithmetic conversions 6889 // to find a common type: C99 6.5.15p3,5. 6890 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6891 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6892 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6893 6894 return ResTy; 6895 } 6896 6897 // If both operands are the same structure or union type, the result is that 6898 // type. 6899 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6900 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6901 if (LHSRT->getDecl() == RHSRT->getDecl()) 6902 // "If both the operands have structure or union type, the result has 6903 // that type." This implies that CV qualifiers are dropped. 6904 return LHSTy.getUnqualifiedType(); 6905 // FIXME: Type of conditional expression must be complete in C mode. 6906 } 6907 6908 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6909 // The following || allows only one side to be void (a GCC-ism). 6910 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6911 return checkConditionalVoidType(*this, LHS, RHS); 6912 } 6913 6914 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6915 // the type of the other operand." 6916 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6917 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6918 6919 // All objective-c pointer type analysis is done here. 6920 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6921 QuestionLoc); 6922 if (LHS.isInvalid() || RHS.isInvalid()) 6923 return QualType(); 6924 if (!compositeType.isNull()) 6925 return compositeType; 6926 6927 6928 // Handle block pointer types. 6929 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6930 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6931 QuestionLoc); 6932 6933 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6934 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6935 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6936 QuestionLoc); 6937 6938 // GCC compatibility: soften pointer/integer mismatch. Note that 6939 // null pointers have been filtered out by this point. 6940 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6941 /*isIntFirstExpr=*/true)) 6942 return RHSTy; 6943 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6944 /*isIntFirstExpr=*/false)) 6945 return LHSTy; 6946 6947 // Emit a better diagnostic if one of the expressions is a null pointer 6948 // constant and the other is not a pointer type. In this case, the user most 6949 // likely forgot to take the address of the other expression. 6950 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6951 return QualType(); 6952 6953 // Otherwise, the operands are not compatible. 6954 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6955 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6956 << RHS.get()->getSourceRange(); 6957 return QualType(); 6958 } 6959 6960 /// FindCompositeObjCPointerType - Helper method to find composite type of 6961 /// two objective-c pointer types of the two input expressions. 6962 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6963 SourceLocation QuestionLoc) { 6964 QualType LHSTy = LHS.get()->getType(); 6965 QualType RHSTy = RHS.get()->getType(); 6966 6967 // Handle things like Class and struct objc_class*. Here we case the result 6968 // to the pseudo-builtin, because that will be implicitly cast back to the 6969 // redefinition type if an attempt is made to access its fields. 6970 if (LHSTy->isObjCClassType() && 6971 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6972 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6973 return LHSTy; 6974 } 6975 if (RHSTy->isObjCClassType() && 6976 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6977 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6978 return RHSTy; 6979 } 6980 // And the same for struct objc_object* / id 6981 if (LHSTy->isObjCIdType() && 6982 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6983 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6984 return LHSTy; 6985 } 6986 if (RHSTy->isObjCIdType() && 6987 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6988 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6989 return RHSTy; 6990 } 6991 // And the same for struct objc_selector* / SEL 6992 if (Context.isObjCSelType(LHSTy) && 6993 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6994 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6995 return LHSTy; 6996 } 6997 if (Context.isObjCSelType(RHSTy) && 6998 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6999 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 7000 return RHSTy; 7001 } 7002 // Check constraints for Objective-C object pointers types. 7003 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 7004 7005 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 7006 // Two identical object pointer types are always compatible. 7007 return LHSTy; 7008 } 7009 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 7010 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 7011 QualType compositeType = LHSTy; 7012 7013 // If both operands are interfaces and either operand can be 7014 // assigned to the other, use that type as the composite 7015 // type. This allows 7016 // xxx ? (A*) a : (B*) b 7017 // where B is a subclass of A. 7018 // 7019 // Additionally, as for assignment, if either type is 'id' 7020 // allow silent coercion. Finally, if the types are 7021 // incompatible then make sure to use 'id' as the composite 7022 // type so the result is acceptable for sending messages to. 7023 7024 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 7025 // It could return the composite type. 7026 if (!(compositeType = 7027 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 7028 // Nothing more to do. 7029 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 7030 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 7031 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 7032 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 7033 } else if ((LHSTy->isObjCQualifiedIdType() || 7034 RHSTy->isObjCQualifiedIdType()) && 7035 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 7036 // Need to handle "id<xx>" explicitly. 7037 // GCC allows qualified id and any Objective-C type to devolve to 7038 // id. Currently localizing to here until clear this should be 7039 // part of ObjCQualifiedIdTypesAreCompatible. 7040 compositeType = Context.getObjCIdType(); 7041 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 7042 compositeType = Context.getObjCIdType(); 7043 } else { 7044 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 7045 << LHSTy << RHSTy 7046 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7047 QualType incompatTy = Context.getObjCIdType(); 7048 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 7049 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 7050 return incompatTy; 7051 } 7052 // The object pointer types are compatible. 7053 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 7054 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 7055 return compositeType; 7056 } 7057 // Check Objective-C object pointer types and 'void *' 7058 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 7059 if (getLangOpts().ObjCAutoRefCount) { 7060 // ARC forbids the implicit conversion of object pointers to 'void *', 7061 // so these types are not compatible. 7062 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7063 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7064 LHS = RHS = true; 7065 return QualType(); 7066 } 7067 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 7068 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7069 QualType destPointee 7070 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7071 QualType destType = Context.getPointerType(destPointee); 7072 // Add qualifiers if necessary. 7073 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7074 // Promote to void*. 7075 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7076 return destType; 7077 } 7078 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7079 if (getLangOpts().ObjCAutoRefCount) { 7080 // ARC forbids the implicit conversion of object pointers to 'void *', 7081 // so these types are not compatible. 7082 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7083 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7084 LHS = RHS = true; 7085 return QualType(); 7086 } 7087 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7088 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 7089 QualType destPointee 7090 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7091 QualType destType = Context.getPointerType(destPointee); 7092 // Add qualifiers if necessary. 7093 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7094 // Promote to void*. 7095 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7096 return destType; 7097 } 7098 return QualType(); 7099 } 7100 7101 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7102 /// ParenRange in parentheses. 7103 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7104 const PartialDiagnostic &Note, 7105 SourceRange ParenRange) { 7106 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7107 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7108 EndLoc.isValid()) { 7109 Self.Diag(Loc, Note) 7110 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7111 << FixItHint::CreateInsertion(EndLoc, ")"); 7112 } else { 7113 // We can't display the parentheses, so just show the bare note. 7114 Self.Diag(Loc, Note) << ParenRange; 7115 } 7116 } 7117 7118 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7119 return BinaryOperator::isAdditiveOp(Opc) || 7120 BinaryOperator::isMultiplicativeOp(Opc) || 7121 BinaryOperator::isShiftOp(Opc); 7122 } 7123 7124 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7125 /// expression, either using a built-in or overloaded operator, 7126 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7127 /// expression. 7128 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7129 Expr **RHSExprs) { 7130 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7131 E = E->IgnoreImpCasts(); 7132 E = E->IgnoreConversionOperator(); 7133 E = E->IgnoreImpCasts(); 7134 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 7135 E = MTE->GetTemporaryExpr(); 7136 E = E->IgnoreImpCasts(); 7137 } 7138 7139 // Built-in binary operator. 7140 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7141 if (IsArithmeticOp(OP->getOpcode())) { 7142 *Opcode = OP->getOpcode(); 7143 *RHSExprs = OP->getRHS(); 7144 return true; 7145 } 7146 } 7147 7148 // Overloaded operator. 7149 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7150 if (Call->getNumArgs() != 2) 7151 return false; 7152 7153 // Make sure this is really a binary operator that is safe to pass into 7154 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7155 OverloadedOperatorKind OO = Call->getOperator(); 7156 if (OO < OO_Plus || OO > OO_Arrow || 7157 OO == OO_PlusPlus || OO == OO_MinusMinus) 7158 return false; 7159 7160 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7161 if (IsArithmeticOp(OpKind)) { 7162 *Opcode = OpKind; 7163 *RHSExprs = Call->getArg(1); 7164 return true; 7165 } 7166 } 7167 7168 return false; 7169 } 7170 7171 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7172 /// or is a logical expression such as (x==y) which has int type, but is 7173 /// commonly interpreted as boolean. 7174 static bool ExprLooksBoolean(Expr *E) { 7175 E = E->IgnoreParenImpCasts(); 7176 7177 if (E->getType()->isBooleanType()) 7178 return true; 7179 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7180 return OP->isComparisonOp() || OP->isLogicalOp(); 7181 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7182 return OP->getOpcode() == UO_LNot; 7183 if (E->getType()->isPointerType()) 7184 return true; 7185 // FIXME: What about overloaded operator calls returning "unspecified boolean 7186 // type"s (commonly pointer-to-members)? 7187 7188 return false; 7189 } 7190 7191 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7192 /// and binary operator are mixed in a way that suggests the programmer assumed 7193 /// the conditional operator has higher precedence, for example: 7194 /// "int x = a + someBinaryCondition ? 1 : 2". 7195 static void DiagnoseConditionalPrecedence(Sema &Self, 7196 SourceLocation OpLoc, 7197 Expr *Condition, 7198 Expr *LHSExpr, 7199 Expr *RHSExpr) { 7200 BinaryOperatorKind CondOpcode; 7201 Expr *CondRHS; 7202 7203 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7204 return; 7205 if (!ExprLooksBoolean(CondRHS)) 7206 return; 7207 7208 // The condition is an arithmetic binary expression, with a right- 7209 // hand side that looks boolean, so warn. 7210 7211 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7212 << Condition->getSourceRange() 7213 << BinaryOperator::getOpcodeStr(CondOpcode); 7214 7215 SuggestParentheses( 7216 Self, OpLoc, 7217 Self.PDiag(diag::note_precedence_silence) 7218 << BinaryOperator::getOpcodeStr(CondOpcode), 7219 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 7220 7221 SuggestParentheses(Self, OpLoc, 7222 Self.PDiag(diag::note_precedence_conditional_first), 7223 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 7224 } 7225 7226 /// Compute the nullability of a conditional expression. 7227 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7228 QualType LHSTy, QualType RHSTy, 7229 ASTContext &Ctx) { 7230 if (!ResTy->isAnyPointerType()) 7231 return ResTy; 7232 7233 auto GetNullability = [&Ctx](QualType Ty) { 7234 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7235 if (Kind) 7236 return *Kind; 7237 return NullabilityKind::Unspecified; 7238 }; 7239 7240 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7241 NullabilityKind MergedKind; 7242 7243 // Compute nullability of a binary conditional expression. 7244 if (IsBin) { 7245 if (LHSKind == NullabilityKind::NonNull) 7246 MergedKind = NullabilityKind::NonNull; 7247 else 7248 MergedKind = RHSKind; 7249 // Compute nullability of a normal conditional expression. 7250 } else { 7251 if (LHSKind == NullabilityKind::Nullable || 7252 RHSKind == NullabilityKind::Nullable) 7253 MergedKind = NullabilityKind::Nullable; 7254 else if (LHSKind == NullabilityKind::NonNull) 7255 MergedKind = RHSKind; 7256 else if (RHSKind == NullabilityKind::NonNull) 7257 MergedKind = LHSKind; 7258 else 7259 MergedKind = NullabilityKind::Unspecified; 7260 } 7261 7262 // Return if ResTy already has the correct nullability. 7263 if (GetNullability(ResTy) == MergedKind) 7264 return ResTy; 7265 7266 // Strip all nullability from ResTy. 7267 while (ResTy->getNullability(Ctx)) 7268 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7269 7270 // Create a new AttributedType with the new nullability kind. 7271 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7272 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7273 } 7274 7275 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7276 /// in the case of a the GNU conditional expr extension. 7277 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7278 SourceLocation ColonLoc, 7279 Expr *CondExpr, Expr *LHSExpr, 7280 Expr *RHSExpr) { 7281 if (!getLangOpts().CPlusPlus) { 7282 // C cannot handle TypoExpr nodes in the condition because it 7283 // doesn't handle dependent types properly, so make sure any TypoExprs have 7284 // been dealt with before checking the operands. 7285 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7286 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7287 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7288 7289 if (!CondResult.isUsable()) 7290 return ExprError(); 7291 7292 if (LHSExpr) { 7293 if (!LHSResult.isUsable()) 7294 return ExprError(); 7295 } 7296 7297 if (!RHSResult.isUsable()) 7298 return ExprError(); 7299 7300 CondExpr = CondResult.get(); 7301 LHSExpr = LHSResult.get(); 7302 RHSExpr = RHSResult.get(); 7303 } 7304 7305 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7306 // was the condition. 7307 OpaqueValueExpr *opaqueValue = nullptr; 7308 Expr *commonExpr = nullptr; 7309 if (!LHSExpr) { 7310 commonExpr = CondExpr; 7311 // Lower out placeholder types first. This is important so that we don't 7312 // try to capture a placeholder. This happens in few cases in C++; such 7313 // as Objective-C++'s dictionary subscripting syntax. 7314 if (commonExpr->hasPlaceholderType()) { 7315 ExprResult result = CheckPlaceholderExpr(commonExpr); 7316 if (!result.isUsable()) return ExprError(); 7317 commonExpr = result.get(); 7318 } 7319 // We usually want to apply unary conversions *before* saving, except 7320 // in the special case of a C++ l-value conditional. 7321 if (!(getLangOpts().CPlusPlus 7322 && !commonExpr->isTypeDependent() 7323 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7324 && commonExpr->isGLValue() 7325 && commonExpr->isOrdinaryOrBitFieldObject() 7326 && RHSExpr->isOrdinaryOrBitFieldObject() 7327 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7328 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7329 if (commonRes.isInvalid()) 7330 return ExprError(); 7331 commonExpr = commonRes.get(); 7332 } 7333 7334 // If the common expression is a class or array prvalue, materialize it 7335 // so that we can safely refer to it multiple times. 7336 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7337 commonExpr->getType()->isArrayType())) { 7338 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7339 if (MatExpr.isInvalid()) 7340 return ExprError(); 7341 commonExpr = MatExpr.get(); 7342 } 7343 7344 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7345 commonExpr->getType(), 7346 commonExpr->getValueKind(), 7347 commonExpr->getObjectKind(), 7348 commonExpr); 7349 LHSExpr = CondExpr = opaqueValue; 7350 } 7351 7352 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7353 ExprValueKind VK = VK_RValue; 7354 ExprObjectKind OK = OK_Ordinary; 7355 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7356 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7357 VK, OK, QuestionLoc); 7358 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7359 RHS.isInvalid()) 7360 return ExprError(); 7361 7362 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7363 RHS.get()); 7364 7365 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7366 7367 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7368 Context); 7369 7370 if (!commonExpr) 7371 return new (Context) 7372 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7373 RHS.get(), result, VK, OK); 7374 7375 return new (Context) BinaryConditionalOperator( 7376 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7377 ColonLoc, result, VK, OK); 7378 } 7379 7380 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7381 // being closely modeled after the C99 spec:-). The odd characteristic of this 7382 // routine is it effectively iqnores the qualifiers on the top level pointee. 7383 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7384 // FIXME: add a couple examples in this comment. 7385 static Sema::AssignConvertType 7386 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7387 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7388 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7389 7390 // get the "pointed to" type (ignoring qualifiers at the top level) 7391 const Type *lhptee, *rhptee; 7392 Qualifiers lhq, rhq; 7393 std::tie(lhptee, lhq) = 7394 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7395 std::tie(rhptee, rhq) = 7396 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7397 7398 Sema::AssignConvertType ConvTy = Sema::Compatible; 7399 7400 // C99 6.5.16.1p1: This following citation is common to constraints 7401 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7402 // qualifiers of the type *pointed to* by the right; 7403 7404 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7405 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7406 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7407 // Ignore lifetime for further calculation. 7408 lhq.removeObjCLifetime(); 7409 rhq.removeObjCLifetime(); 7410 } 7411 7412 if (!lhq.compatiblyIncludes(rhq)) { 7413 // Treat address-space mismatches as fatal. TODO: address subspaces 7414 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7415 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7416 7417 // It's okay to add or remove GC or lifetime qualifiers when converting to 7418 // and from void*. 7419 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7420 .compatiblyIncludes( 7421 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7422 && (lhptee->isVoidType() || rhptee->isVoidType())) 7423 ; // keep old 7424 7425 // Treat lifetime mismatches as fatal. 7426 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7427 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7428 7429 // For GCC/MS compatibility, other qualifier mismatches are treated 7430 // as still compatible in C. 7431 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7432 } 7433 7434 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7435 // incomplete type and the other is a pointer to a qualified or unqualified 7436 // version of void... 7437 if (lhptee->isVoidType()) { 7438 if (rhptee->isIncompleteOrObjectType()) 7439 return ConvTy; 7440 7441 // As an extension, we allow cast to/from void* to function pointer. 7442 assert(rhptee->isFunctionType()); 7443 return Sema::FunctionVoidPointer; 7444 } 7445 7446 if (rhptee->isVoidType()) { 7447 if (lhptee->isIncompleteOrObjectType()) 7448 return ConvTy; 7449 7450 // As an extension, we allow cast to/from void* to function pointer. 7451 assert(lhptee->isFunctionType()); 7452 return Sema::FunctionVoidPointer; 7453 } 7454 7455 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7456 // unqualified versions of compatible types, ... 7457 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7458 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7459 // Check if the pointee types are compatible ignoring the sign. 7460 // We explicitly check for char so that we catch "char" vs 7461 // "unsigned char" on systems where "char" is unsigned. 7462 if (lhptee->isCharType()) 7463 ltrans = S.Context.UnsignedCharTy; 7464 else if (lhptee->hasSignedIntegerRepresentation()) 7465 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7466 7467 if (rhptee->isCharType()) 7468 rtrans = S.Context.UnsignedCharTy; 7469 else if (rhptee->hasSignedIntegerRepresentation()) 7470 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7471 7472 if (ltrans == rtrans) { 7473 // Types are compatible ignoring the sign. Qualifier incompatibility 7474 // takes priority over sign incompatibility because the sign 7475 // warning can be disabled. 7476 if (ConvTy != Sema::Compatible) 7477 return ConvTy; 7478 7479 return Sema::IncompatiblePointerSign; 7480 } 7481 7482 // If we are a multi-level pointer, it's possible that our issue is simply 7483 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7484 // the eventual target type is the same and the pointers have the same 7485 // level of indirection, this must be the issue. 7486 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7487 do { 7488 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7489 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7490 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7491 7492 if (lhptee == rhptee) 7493 return Sema::IncompatibleNestedPointerQualifiers; 7494 } 7495 7496 // General pointer incompatibility takes priority over qualifiers. 7497 return Sema::IncompatiblePointer; 7498 } 7499 if (!S.getLangOpts().CPlusPlus && 7500 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7501 return Sema::IncompatiblePointer; 7502 return ConvTy; 7503 } 7504 7505 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7506 /// block pointer types are compatible or whether a block and normal pointer 7507 /// are compatible. It is more restrict than comparing two function pointer 7508 // types. 7509 static Sema::AssignConvertType 7510 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7511 QualType RHSType) { 7512 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7513 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7514 7515 QualType lhptee, rhptee; 7516 7517 // get the "pointed to" type (ignoring qualifiers at the top level) 7518 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7519 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7520 7521 // In C++, the types have to match exactly. 7522 if (S.getLangOpts().CPlusPlus) 7523 return Sema::IncompatibleBlockPointer; 7524 7525 Sema::AssignConvertType ConvTy = Sema::Compatible; 7526 7527 // For blocks we enforce that qualifiers are identical. 7528 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7529 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7530 if (S.getLangOpts().OpenCL) { 7531 LQuals.removeAddressSpace(); 7532 RQuals.removeAddressSpace(); 7533 } 7534 if (LQuals != RQuals) 7535 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7536 7537 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7538 // assignment. 7539 // The current behavior is similar to C++ lambdas. A block might be 7540 // assigned to a variable iff its return type and parameters are compatible 7541 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7542 // an assignment. Presumably it should behave in way that a function pointer 7543 // assignment does in C, so for each parameter and return type: 7544 // * CVR and address space of LHS should be a superset of CVR and address 7545 // space of RHS. 7546 // * unqualified types should be compatible. 7547 if (S.getLangOpts().OpenCL) { 7548 if (!S.Context.typesAreBlockPointerCompatible( 7549 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7550 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7551 return Sema::IncompatibleBlockPointer; 7552 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7553 return Sema::IncompatibleBlockPointer; 7554 7555 return ConvTy; 7556 } 7557 7558 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7559 /// for assignment compatibility. 7560 static Sema::AssignConvertType 7561 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7562 QualType RHSType) { 7563 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7564 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7565 7566 if (LHSType->isObjCBuiltinType()) { 7567 // Class is not compatible with ObjC object pointers. 7568 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7569 !RHSType->isObjCQualifiedClassType()) 7570 return Sema::IncompatiblePointer; 7571 return Sema::Compatible; 7572 } 7573 if (RHSType->isObjCBuiltinType()) { 7574 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7575 !LHSType->isObjCQualifiedClassType()) 7576 return Sema::IncompatiblePointer; 7577 return Sema::Compatible; 7578 } 7579 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7580 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7581 7582 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7583 // make an exception for id<P> 7584 !LHSType->isObjCQualifiedIdType()) 7585 return Sema::CompatiblePointerDiscardsQualifiers; 7586 7587 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7588 return Sema::Compatible; 7589 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7590 return Sema::IncompatibleObjCQualifiedId; 7591 return Sema::IncompatiblePointer; 7592 } 7593 7594 Sema::AssignConvertType 7595 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7596 QualType LHSType, QualType RHSType) { 7597 // Fake up an opaque expression. We don't actually care about what 7598 // cast operations are required, so if CheckAssignmentConstraints 7599 // adds casts to this they'll be wasted, but fortunately that doesn't 7600 // usually happen on valid code. 7601 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7602 ExprResult RHSPtr = &RHSExpr; 7603 CastKind K; 7604 7605 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7606 } 7607 7608 /// This helper function returns true if QT is a vector type that has element 7609 /// type ElementType. 7610 static bool isVector(QualType QT, QualType ElementType) { 7611 if (const VectorType *VT = QT->getAs<VectorType>()) 7612 return VT->getElementType() == ElementType; 7613 return false; 7614 } 7615 7616 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7617 /// has code to accommodate several GCC extensions when type checking 7618 /// pointers. Here are some objectionable examples that GCC considers warnings: 7619 /// 7620 /// int a, *pint; 7621 /// short *pshort; 7622 /// struct foo *pfoo; 7623 /// 7624 /// pint = pshort; // warning: assignment from incompatible pointer type 7625 /// a = pint; // warning: assignment makes integer from pointer without a cast 7626 /// pint = a; // warning: assignment makes pointer from integer without a cast 7627 /// pint = pfoo; // warning: assignment from incompatible pointer type 7628 /// 7629 /// As a result, the code for dealing with pointers is more complex than the 7630 /// C99 spec dictates. 7631 /// 7632 /// Sets 'Kind' for any result kind except Incompatible. 7633 Sema::AssignConvertType 7634 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7635 CastKind &Kind, bool ConvertRHS) { 7636 QualType RHSType = RHS.get()->getType(); 7637 QualType OrigLHSType = LHSType; 7638 7639 // Get canonical types. We're not formatting these types, just comparing 7640 // them. 7641 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7642 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7643 7644 // Common case: no conversion required. 7645 if (LHSType == RHSType) { 7646 Kind = CK_NoOp; 7647 return Compatible; 7648 } 7649 7650 // If we have an atomic type, try a non-atomic assignment, then just add an 7651 // atomic qualification step. 7652 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7653 Sema::AssignConvertType result = 7654 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7655 if (result != Compatible) 7656 return result; 7657 if (Kind != CK_NoOp && ConvertRHS) 7658 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7659 Kind = CK_NonAtomicToAtomic; 7660 return Compatible; 7661 } 7662 7663 // If the left-hand side is a reference type, then we are in a 7664 // (rare!) case where we've allowed the use of references in C, 7665 // e.g., as a parameter type in a built-in function. In this case, 7666 // just make sure that the type referenced is compatible with the 7667 // right-hand side type. The caller is responsible for adjusting 7668 // LHSType so that the resulting expression does not have reference 7669 // type. 7670 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7671 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7672 Kind = CK_LValueBitCast; 7673 return Compatible; 7674 } 7675 return Incompatible; 7676 } 7677 7678 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7679 // to the same ExtVector type. 7680 if (LHSType->isExtVectorType()) { 7681 if (RHSType->isExtVectorType()) 7682 return Incompatible; 7683 if (RHSType->isArithmeticType()) { 7684 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7685 if (ConvertRHS) 7686 RHS = prepareVectorSplat(LHSType, RHS.get()); 7687 Kind = CK_VectorSplat; 7688 return Compatible; 7689 } 7690 } 7691 7692 // Conversions to or from vector type. 7693 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7694 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7695 // Allow assignments of an AltiVec vector type to an equivalent GCC 7696 // vector type and vice versa 7697 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7698 Kind = CK_BitCast; 7699 return Compatible; 7700 } 7701 7702 // If we are allowing lax vector conversions, and LHS and RHS are both 7703 // vectors, the total size only needs to be the same. This is a bitcast; 7704 // no bits are changed but the result type is different. 7705 if (isLaxVectorConversion(RHSType, LHSType)) { 7706 Kind = CK_BitCast; 7707 return IncompatibleVectors; 7708 } 7709 } 7710 7711 // When the RHS comes from another lax conversion (e.g. binops between 7712 // scalars and vectors) the result is canonicalized as a vector. When the 7713 // LHS is also a vector, the lax is allowed by the condition above. Handle 7714 // the case where LHS is a scalar. 7715 if (LHSType->isScalarType()) { 7716 const VectorType *VecType = RHSType->getAs<VectorType>(); 7717 if (VecType && VecType->getNumElements() == 1 && 7718 isLaxVectorConversion(RHSType, LHSType)) { 7719 ExprResult *VecExpr = &RHS; 7720 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7721 Kind = CK_BitCast; 7722 return Compatible; 7723 } 7724 } 7725 7726 return Incompatible; 7727 } 7728 7729 // Diagnose attempts to convert between __float128 and long double where 7730 // such conversions currently can't be handled. 7731 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7732 return Incompatible; 7733 7734 // Disallow assigning a _Complex to a real type in C++ mode since it simply 7735 // discards the imaginary part. 7736 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 7737 !LHSType->getAs<ComplexType>()) 7738 return Incompatible; 7739 7740 // Arithmetic conversions. 7741 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7742 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7743 if (ConvertRHS) 7744 Kind = PrepareScalarCast(RHS, LHSType); 7745 return Compatible; 7746 } 7747 7748 // Conversions to normal pointers. 7749 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7750 // U* -> T* 7751 if (isa<PointerType>(RHSType)) { 7752 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7753 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7754 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7755 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7756 } 7757 7758 // int -> T* 7759 if (RHSType->isIntegerType()) { 7760 Kind = CK_IntegralToPointer; // FIXME: null? 7761 return IntToPointer; 7762 } 7763 7764 // C pointers are not compatible with ObjC object pointers, 7765 // with two exceptions: 7766 if (isa<ObjCObjectPointerType>(RHSType)) { 7767 // - conversions to void* 7768 if (LHSPointer->getPointeeType()->isVoidType()) { 7769 Kind = CK_BitCast; 7770 return Compatible; 7771 } 7772 7773 // - conversions from 'Class' to the redefinition type 7774 if (RHSType->isObjCClassType() && 7775 Context.hasSameType(LHSType, 7776 Context.getObjCClassRedefinitionType())) { 7777 Kind = CK_BitCast; 7778 return Compatible; 7779 } 7780 7781 Kind = CK_BitCast; 7782 return IncompatiblePointer; 7783 } 7784 7785 // U^ -> void* 7786 if (RHSType->getAs<BlockPointerType>()) { 7787 if (LHSPointer->getPointeeType()->isVoidType()) { 7788 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7789 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7790 ->getPointeeType() 7791 .getAddressSpace(); 7792 Kind = 7793 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7794 return Compatible; 7795 } 7796 } 7797 7798 return Incompatible; 7799 } 7800 7801 // Conversions to block pointers. 7802 if (isa<BlockPointerType>(LHSType)) { 7803 // U^ -> T^ 7804 if (RHSType->isBlockPointerType()) { 7805 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 7806 ->getPointeeType() 7807 .getAddressSpace(); 7808 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7809 ->getPointeeType() 7810 .getAddressSpace(); 7811 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7812 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7813 } 7814 7815 // int or null -> T^ 7816 if (RHSType->isIntegerType()) { 7817 Kind = CK_IntegralToPointer; // FIXME: null 7818 return IntToBlockPointer; 7819 } 7820 7821 // id -> T^ 7822 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7823 Kind = CK_AnyPointerToBlockPointerCast; 7824 return Compatible; 7825 } 7826 7827 // void* -> T^ 7828 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7829 if (RHSPT->getPointeeType()->isVoidType()) { 7830 Kind = CK_AnyPointerToBlockPointerCast; 7831 return Compatible; 7832 } 7833 7834 return Incompatible; 7835 } 7836 7837 // Conversions to Objective-C pointers. 7838 if (isa<ObjCObjectPointerType>(LHSType)) { 7839 // A* -> B* 7840 if (RHSType->isObjCObjectPointerType()) { 7841 Kind = CK_BitCast; 7842 Sema::AssignConvertType result = 7843 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7844 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7845 result == Compatible && 7846 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7847 result = IncompatibleObjCWeakRef; 7848 return result; 7849 } 7850 7851 // int or null -> A* 7852 if (RHSType->isIntegerType()) { 7853 Kind = CK_IntegralToPointer; // FIXME: null 7854 return IntToPointer; 7855 } 7856 7857 // In general, C pointers are not compatible with ObjC object pointers, 7858 // with two exceptions: 7859 if (isa<PointerType>(RHSType)) { 7860 Kind = CK_CPointerToObjCPointerCast; 7861 7862 // - conversions from 'void*' 7863 if (RHSType->isVoidPointerType()) { 7864 return Compatible; 7865 } 7866 7867 // - conversions to 'Class' from its redefinition type 7868 if (LHSType->isObjCClassType() && 7869 Context.hasSameType(RHSType, 7870 Context.getObjCClassRedefinitionType())) { 7871 return Compatible; 7872 } 7873 7874 return IncompatiblePointer; 7875 } 7876 7877 // Only under strict condition T^ is compatible with an Objective-C pointer. 7878 if (RHSType->isBlockPointerType() && 7879 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7880 if (ConvertRHS) 7881 maybeExtendBlockObject(RHS); 7882 Kind = CK_BlockPointerToObjCPointerCast; 7883 return Compatible; 7884 } 7885 7886 return Incompatible; 7887 } 7888 7889 // Conversions from pointers that are not covered by the above. 7890 if (isa<PointerType>(RHSType)) { 7891 // T* -> _Bool 7892 if (LHSType == Context.BoolTy) { 7893 Kind = CK_PointerToBoolean; 7894 return Compatible; 7895 } 7896 7897 // T* -> int 7898 if (LHSType->isIntegerType()) { 7899 Kind = CK_PointerToIntegral; 7900 return PointerToInt; 7901 } 7902 7903 return Incompatible; 7904 } 7905 7906 // Conversions from Objective-C pointers that are not covered by the above. 7907 if (isa<ObjCObjectPointerType>(RHSType)) { 7908 // T* -> _Bool 7909 if (LHSType == Context.BoolTy) { 7910 Kind = CK_PointerToBoolean; 7911 return Compatible; 7912 } 7913 7914 // T* -> int 7915 if (LHSType->isIntegerType()) { 7916 Kind = CK_PointerToIntegral; 7917 return PointerToInt; 7918 } 7919 7920 return Incompatible; 7921 } 7922 7923 // struct A -> struct B 7924 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7925 if (Context.typesAreCompatible(LHSType, RHSType)) { 7926 Kind = CK_NoOp; 7927 return Compatible; 7928 } 7929 } 7930 7931 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 7932 Kind = CK_IntToOCLSampler; 7933 return Compatible; 7934 } 7935 7936 return Incompatible; 7937 } 7938 7939 /// Constructs a transparent union from an expression that is 7940 /// used to initialize the transparent union. 7941 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7942 ExprResult &EResult, QualType UnionType, 7943 FieldDecl *Field) { 7944 // Build an initializer list that designates the appropriate member 7945 // of the transparent union. 7946 Expr *E = EResult.get(); 7947 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7948 E, SourceLocation()); 7949 Initializer->setType(UnionType); 7950 Initializer->setInitializedFieldInUnion(Field); 7951 7952 // Build a compound literal constructing a value of the transparent 7953 // union type from this initializer list. 7954 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7955 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7956 VK_RValue, Initializer, false); 7957 } 7958 7959 Sema::AssignConvertType 7960 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7961 ExprResult &RHS) { 7962 QualType RHSType = RHS.get()->getType(); 7963 7964 // If the ArgType is a Union type, we want to handle a potential 7965 // transparent_union GCC extension. 7966 const RecordType *UT = ArgType->getAsUnionType(); 7967 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7968 return Incompatible; 7969 7970 // The field to initialize within the transparent union. 7971 RecordDecl *UD = UT->getDecl(); 7972 FieldDecl *InitField = nullptr; 7973 // It's compatible if the expression matches any of the fields. 7974 for (auto *it : UD->fields()) { 7975 if (it->getType()->isPointerType()) { 7976 // If the transparent union contains a pointer type, we allow: 7977 // 1) void pointer 7978 // 2) null pointer constant 7979 if (RHSType->isPointerType()) 7980 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7981 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7982 InitField = it; 7983 break; 7984 } 7985 7986 if (RHS.get()->isNullPointerConstant(Context, 7987 Expr::NPC_ValueDependentIsNull)) { 7988 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7989 CK_NullToPointer); 7990 InitField = it; 7991 break; 7992 } 7993 } 7994 7995 CastKind Kind; 7996 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7997 == Compatible) { 7998 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7999 InitField = it; 8000 break; 8001 } 8002 } 8003 8004 if (!InitField) 8005 return Incompatible; 8006 8007 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 8008 return Compatible; 8009 } 8010 8011 Sema::AssignConvertType 8012 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 8013 bool Diagnose, 8014 bool DiagnoseCFAudited, 8015 bool ConvertRHS) { 8016 // We need to be able to tell the caller whether we diagnosed a problem, if 8017 // they ask us to issue diagnostics. 8018 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 8019 8020 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 8021 // we can't avoid *all* modifications at the moment, so we need some somewhere 8022 // to put the updated value. 8023 ExprResult LocalRHS = CallerRHS; 8024 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 8025 8026 if (getLangOpts().CPlusPlus) { 8027 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 8028 // C++ 5.17p3: If the left operand is not of class type, the 8029 // expression is implicitly converted (C++ 4) to the 8030 // cv-unqualified type of the left operand. 8031 QualType RHSType = RHS.get()->getType(); 8032 if (Diagnose) { 8033 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8034 AA_Assigning); 8035 } else { 8036 ImplicitConversionSequence ICS = 8037 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8038 /*SuppressUserConversions=*/false, 8039 /*AllowExplicit=*/false, 8040 /*InOverloadResolution=*/false, 8041 /*CStyle=*/false, 8042 /*AllowObjCWritebackConversion=*/false); 8043 if (ICS.isFailure()) 8044 return Incompatible; 8045 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8046 ICS, AA_Assigning); 8047 } 8048 if (RHS.isInvalid()) 8049 return Incompatible; 8050 Sema::AssignConvertType result = Compatible; 8051 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8052 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 8053 result = IncompatibleObjCWeakRef; 8054 return result; 8055 } 8056 8057 // FIXME: Currently, we fall through and treat C++ classes like C 8058 // structures. 8059 // FIXME: We also fall through for atomics; not sure what should 8060 // happen there, though. 8061 } else if (RHS.get()->getType() == Context.OverloadTy) { 8062 // As a set of extensions to C, we support overloading on functions. These 8063 // functions need to be resolved here. 8064 DeclAccessPair DAP; 8065 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 8066 RHS.get(), LHSType, /*Complain=*/false, DAP)) 8067 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 8068 else 8069 return Incompatible; 8070 } 8071 8072 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8073 // a null pointer constant. 8074 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8075 LHSType->isBlockPointerType()) && 8076 RHS.get()->isNullPointerConstant(Context, 8077 Expr::NPC_ValueDependentIsNull)) { 8078 if (Diagnose || ConvertRHS) { 8079 CastKind Kind; 8080 CXXCastPath Path; 8081 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8082 /*IgnoreBaseAccess=*/false, Diagnose); 8083 if (ConvertRHS) 8084 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8085 } 8086 return Compatible; 8087 } 8088 8089 // This check seems unnatural, however it is necessary to ensure the proper 8090 // conversion of functions/arrays. If the conversion were done for all 8091 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8092 // expressions that suppress this implicit conversion (&, sizeof). 8093 // 8094 // Suppress this for references: C++ 8.5.3p5. 8095 if (!LHSType->isReferenceType()) { 8096 // FIXME: We potentially allocate here even if ConvertRHS is false. 8097 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8098 if (RHS.isInvalid()) 8099 return Incompatible; 8100 } 8101 CastKind Kind; 8102 Sema::AssignConvertType result = 8103 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8104 8105 // C99 6.5.16.1p2: The value of the right operand is converted to the 8106 // type of the assignment expression. 8107 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8108 // so that we can use references in built-in functions even in C. 8109 // The getNonReferenceType() call makes sure that the resulting expression 8110 // does not have reference type. 8111 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8112 QualType Ty = LHSType.getNonLValueExprType(Context); 8113 Expr *E = RHS.get(); 8114 8115 // Check for various Objective-C errors. If we are not reporting 8116 // diagnostics and just checking for errors, e.g., during overload 8117 // resolution, return Incompatible to indicate the failure. 8118 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8119 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8120 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8121 if (!Diagnose) 8122 return Incompatible; 8123 } 8124 if (getLangOpts().ObjC1 && 8125 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 8126 E->getType(), E, Diagnose) || 8127 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8128 if (!Diagnose) 8129 return Incompatible; 8130 // Replace the expression with a corrected version and continue so we 8131 // can find further errors. 8132 RHS = E; 8133 return Compatible; 8134 } 8135 8136 if (ConvertRHS) 8137 RHS = ImpCastExprToType(E, Ty, Kind); 8138 } 8139 return result; 8140 } 8141 8142 namespace { 8143 /// The original operand to an operator, prior to the application of the usual 8144 /// arithmetic conversions and converting the arguments of a builtin operator 8145 /// candidate. 8146 struct OriginalOperand { 8147 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 8148 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 8149 Op = MTE->GetTemporaryExpr(); 8150 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 8151 Op = BTE->getSubExpr(); 8152 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 8153 Orig = ICE->getSubExprAsWritten(); 8154 Conversion = ICE->getConversionFunction(); 8155 } 8156 } 8157 8158 QualType getType() const { return Orig->getType(); } 8159 8160 Expr *Orig; 8161 NamedDecl *Conversion; 8162 }; 8163 } 8164 8165 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8166 ExprResult &RHS) { 8167 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 8168 8169 Diag(Loc, diag::err_typecheck_invalid_operands) 8170 << OrigLHS.getType() << OrigRHS.getType() 8171 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8172 8173 // If a user-defined conversion was applied to either of the operands prior 8174 // to applying the built-in operator rules, tell the user about it. 8175 if (OrigLHS.Conversion) { 8176 Diag(OrigLHS.Conversion->getLocation(), 8177 diag::note_typecheck_invalid_operands_converted) 8178 << 0 << LHS.get()->getType(); 8179 } 8180 if (OrigRHS.Conversion) { 8181 Diag(OrigRHS.Conversion->getLocation(), 8182 diag::note_typecheck_invalid_operands_converted) 8183 << 1 << RHS.get()->getType(); 8184 } 8185 8186 return QualType(); 8187 } 8188 8189 // Diagnose cases where a scalar was implicitly converted to a vector and 8190 // diagnose the underlying types. Otherwise, diagnose the error 8191 // as invalid vector logical operands for non-C++ cases. 8192 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8193 ExprResult &RHS) { 8194 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8195 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8196 8197 bool LHSNatVec = LHSType->isVectorType(); 8198 bool RHSNatVec = RHSType->isVectorType(); 8199 8200 if (!(LHSNatVec && RHSNatVec)) { 8201 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8202 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8203 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8204 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8205 << Vector->getSourceRange(); 8206 return QualType(); 8207 } 8208 8209 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8210 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8211 << RHS.get()->getSourceRange(); 8212 8213 return QualType(); 8214 } 8215 8216 /// Try to convert a value of non-vector type to a vector type by converting 8217 /// the type to the element type of the vector and then performing a splat. 8218 /// If the language is OpenCL, we only use conversions that promote scalar 8219 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8220 /// for float->int. 8221 /// 8222 /// OpenCL V2.0 6.2.6.p2: 8223 /// An error shall occur if any scalar operand type has greater rank 8224 /// than the type of the vector element. 8225 /// 8226 /// \param scalar - if non-null, actually perform the conversions 8227 /// \return true if the operation fails (but without diagnosing the failure) 8228 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8229 QualType scalarTy, 8230 QualType vectorEltTy, 8231 QualType vectorTy, 8232 unsigned &DiagID) { 8233 // The conversion to apply to the scalar before splatting it, 8234 // if necessary. 8235 CastKind scalarCast = CK_NoOp; 8236 8237 if (vectorEltTy->isIntegralType(S.Context)) { 8238 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8239 (scalarTy->isIntegerType() && 8240 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8241 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8242 return true; 8243 } 8244 if (!scalarTy->isIntegralType(S.Context)) 8245 return true; 8246 scalarCast = CK_IntegralCast; 8247 } else if (vectorEltTy->isRealFloatingType()) { 8248 if (scalarTy->isRealFloatingType()) { 8249 if (S.getLangOpts().OpenCL && 8250 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8251 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8252 return true; 8253 } 8254 scalarCast = CK_FloatingCast; 8255 } 8256 else if (scalarTy->isIntegralType(S.Context)) 8257 scalarCast = CK_IntegralToFloating; 8258 else 8259 return true; 8260 } else { 8261 return true; 8262 } 8263 8264 // Adjust scalar if desired. 8265 if (scalar) { 8266 if (scalarCast != CK_NoOp) 8267 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8268 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8269 } 8270 return false; 8271 } 8272 8273 /// Convert vector E to a vector with the same number of elements but different 8274 /// element type. 8275 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8276 const auto *VecTy = E->getType()->getAs<VectorType>(); 8277 assert(VecTy && "Expression E must be a vector"); 8278 QualType NewVecTy = S.Context.getVectorType(ElementType, 8279 VecTy->getNumElements(), 8280 VecTy->getVectorKind()); 8281 8282 // Look through the implicit cast. Return the subexpression if its type is 8283 // NewVecTy. 8284 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8285 if (ICE->getSubExpr()->getType() == NewVecTy) 8286 return ICE->getSubExpr(); 8287 8288 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8289 return S.ImpCastExprToType(E, NewVecTy, Cast); 8290 } 8291 8292 /// Test if a (constant) integer Int can be casted to another integer type 8293 /// IntTy without losing precision. 8294 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8295 QualType OtherIntTy) { 8296 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8297 8298 // Reject cases where the value of the Int is unknown as that would 8299 // possibly cause truncation, but accept cases where the scalar can be 8300 // demoted without loss of precision. 8301 llvm::APSInt Result; 8302 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8303 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8304 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8305 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8306 8307 if (CstInt) { 8308 // If the scalar is constant and is of a higher order and has more active 8309 // bits that the vector element type, reject it. 8310 unsigned NumBits = IntSigned 8311 ? (Result.isNegative() ? Result.getMinSignedBits() 8312 : Result.getActiveBits()) 8313 : Result.getActiveBits(); 8314 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8315 return true; 8316 8317 // If the signedness of the scalar type and the vector element type 8318 // differs and the number of bits is greater than that of the vector 8319 // element reject it. 8320 return (IntSigned != OtherIntSigned && 8321 NumBits > S.Context.getIntWidth(OtherIntTy)); 8322 } 8323 8324 // Reject cases where the value of the scalar is not constant and it's 8325 // order is greater than that of the vector element type. 8326 return (Order < 0); 8327 } 8328 8329 /// Test if a (constant) integer Int can be casted to floating point type 8330 /// FloatTy without losing precision. 8331 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8332 QualType FloatTy) { 8333 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8334 8335 // Determine if the integer constant can be expressed as a floating point 8336 // number of the appropriate type. 8337 llvm::APSInt Result; 8338 bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context); 8339 uint64_t Bits = 0; 8340 if (CstInt) { 8341 // Reject constants that would be truncated if they were converted to 8342 // the floating point type. Test by simple to/from conversion. 8343 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8344 // could be avoided if there was a convertFromAPInt method 8345 // which could signal back if implicit truncation occurred. 8346 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8347 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8348 llvm::APFloat::rmTowardZero); 8349 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8350 !IntTy->hasSignedIntegerRepresentation()); 8351 bool Ignored = false; 8352 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8353 &Ignored); 8354 if (Result != ConvertBack) 8355 return true; 8356 } else { 8357 // Reject types that cannot be fully encoded into the mantissa of 8358 // the float. 8359 Bits = S.Context.getTypeSize(IntTy); 8360 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8361 S.Context.getFloatTypeSemantics(FloatTy)); 8362 if (Bits > FloatPrec) 8363 return true; 8364 } 8365 8366 return false; 8367 } 8368 8369 /// Attempt to convert and splat Scalar into a vector whose types matches 8370 /// Vector following GCC conversion rules. The rule is that implicit 8371 /// conversion can occur when Scalar can be casted to match Vector's element 8372 /// type without causing truncation of Scalar. 8373 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8374 ExprResult *Vector) { 8375 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8376 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8377 const VectorType *VT = VectorTy->getAs<VectorType>(); 8378 8379 assert(!isa<ExtVectorType>(VT) && 8380 "ExtVectorTypes should not be handled here!"); 8381 8382 QualType VectorEltTy = VT->getElementType(); 8383 8384 // Reject cases where the vector element type or the scalar element type are 8385 // not integral or floating point types. 8386 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8387 return true; 8388 8389 // The conversion to apply to the scalar before splatting it, 8390 // if necessary. 8391 CastKind ScalarCast = CK_NoOp; 8392 8393 // Accept cases where the vector elements are integers and the scalar is 8394 // an integer. 8395 // FIXME: Notionally if the scalar was a floating point value with a precise 8396 // integral representation, we could cast it to an appropriate integer 8397 // type and then perform the rest of the checks here. GCC will perform 8398 // this conversion in some cases as determined by the input language. 8399 // We should accept it on a language independent basis. 8400 if (VectorEltTy->isIntegralType(S.Context) && 8401 ScalarTy->isIntegralType(S.Context) && 8402 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8403 8404 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8405 return true; 8406 8407 ScalarCast = CK_IntegralCast; 8408 } else if (VectorEltTy->isRealFloatingType()) { 8409 if (ScalarTy->isRealFloatingType()) { 8410 8411 // Reject cases where the scalar type is not a constant and has a higher 8412 // Order than the vector element type. 8413 llvm::APFloat Result(0.0); 8414 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8415 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8416 if (!CstScalar && Order < 0) 8417 return true; 8418 8419 // If the scalar cannot be safely casted to the vector element type, 8420 // reject it. 8421 if (CstScalar) { 8422 bool Truncated = false; 8423 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8424 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8425 if (Truncated) 8426 return true; 8427 } 8428 8429 ScalarCast = CK_FloatingCast; 8430 } else if (ScalarTy->isIntegralType(S.Context)) { 8431 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8432 return true; 8433 8434 ScalarCast = CK_IntegralToFloating; 8435 } else 8436 return true; 8437 } 8438 8439 // Adjust scalar if desired. 8440 if (Scalar) { 8441 if (ScalarCast != CK_NoOp) 8442 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8443 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8444 } 8445 return false; 8446 } 8447 8448 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8449 SourceLocation Loc, bool IsCompAssign, 8450 bool AllowBothBool, 8451 bool AllowBoolConversions) { 8452 if (!IsCompAssign) { 8453 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8454 if (LHS.isInvalid()) 8455 return QualType(); 8456 } 8457 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8458 if (RHS.isInvalid()) 8459 return QualType(); 8460 8461 // For conversion purposes, we ignore any qualifiers. 8462 // For example, "const float" and "float" are equivalent. 8463 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8464 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8465 8466 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8467 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8468 assert(LHSVecType || RHSVecType); 8469 8470 // AltiVec-style "vector bool op vector bool" combinations are allowed 8471 // for some operators but not others. 8472 if (!AllowBothBool && 8473 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8474 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8475 return InvalidOperands(Loc, LHS, RHS); 8476 8477 // If the vector types are identical, return. 8478 if (Context.hasSameType(LHSType, RHSType)) 8479 return LHSType; 8480 8481 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8482 if (LHSVecType && RHSVecType && 8483 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8484 if (isa<ExtVectorType>(LHSVecType)) { 8485 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8486 return LHSType; 8487 } 8488 8489 if (!IsCompAssign) 8490 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8491 return RHSType; 8492 } 8493 8494 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8495 // can be mixed, with the result being the non-bool type. The non-bool 8496 // operand must have integer element type. 8497 if (AllowBoolConversions && LHSVecType && RHSVecType && 8498 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8499 (Context.getTypeSize(LHSVecType->getElementType()) == 8500 Context.getTypeSize(RHSVecType->getElementType()))) { 8501 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8502 LHSVecType->getElementType()->isIntegerType() && 8503 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8504 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8505 return LHSType; 8506 } 8507 if (!IsCompAssign && 8508 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8509 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8510 RHSVecType->getElementType()->isIntegerType()) { 8511 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8512 return RHSType; 8513 } 8514 } 8515 8516 // If there's a vector type and a scalar, try to convert the scalar to 8517 // the vector element type and splat. 8518 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 8519 if (!RHSVecType) { 8520 if (isa<ExtVectorType>(LHSVecType)) { 8521 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8522 LHSVecType->getElementType(), LHSType, 8523 DiagID)) 8524 return LHSType; 8525 } else { 8526 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 8527 return LHSType; 8528 } 8529 } 8530 if (!LHSVecType) { 8531 if (isa<ExtVectorType>(RHSVecType)) { 8532 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8533 LHSType, RHSVecType->getElementType(), 8534 RHSType, DiagID)) 8535 return RHSType; 8536 } else { 8537 if (LHS.get()->getValueKind() == VK_LValue || 8538 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 8539 return RHSType; 8540 } 8541 } 8542 8543 // FIXME: The code below also handles conversion between vectors and 8544 // non-scalars, we should break this down into fine grained specific checks 8545 // and emit proper diagnostics. 8546 QualType VecType = LHSVecType ? LHSType : RHSType; 8547 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8548 QualType OtherType = LHSVecType ? RHSType : LHSType; 8549 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8550 if (isLaxVectorConversion(OtherType, VecType)) { 8551 // If we're allowing lax vector conversions, only the total (data) size 8552 // needs to be the same. For non compound assignment, if one of the types is 8553 // scalar, the result is always the vector type. 8554 if (!IsCompAssign) { 8555 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8556 return VecType; 8557 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8558 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8559 // type. Note that this is already done by non-compound assignments in 8560 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8561 // <1 x T> -> T. The result is also a vector type. 8562 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 8563 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8564 ExprResult *RHSExpr = &RHS; 8565 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8566 return VecType; 8567 } 8568 } 8569 8570 // Okay, the expression is invalid. 8571 8572 // If there's a non-vector, non-real operand, diagnose that. 8573 if ((!RHSVecType && !RHSType->isRealType()) || 8574 (!LHSVecType && !LHSType->isRealType())) { 8575 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8576 << LHSType << RHSType 8577 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8578 return QualType(); 8579 } 8580 8581 // OpenCL V1.1 6.2.6.p1: 8582 // If the operands are of more than one vector type, then an error shall 8583 // occur. Implicit conversions between vector types are not permitted, per 8584 // section 6.2.1. 8585 if (getLangOpts().OpenCL && 8586 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8587 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8588 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8589 << RHSType; 8590 return QualType(); 8591 } 8592 8593 8594 // If there is a vector type that is not a ExtVector and a scalar, we reach 8595 // this point if scalar could not be converted to the vector's element type 8596 // without truncation. 8597 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 8598 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 8599 QualType Scalar = LHSVecType ? RHSType : LHSType; 8600 QualType Vector = LHSVecType ? LHSType : RHSType; 8601 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 8602 Diag(Loc, 8603 diag::err_typecheck_vector_not_convertable_implict_truncation) 8604 << ScalarOrVector << Scalar << Vector; 8605 8606 return QualType(); 8607 } 8608 8609 // Otherwise, use the generic diagnostic. 8610 Diag(Loc, DiagID) 8611 << LHSType << RHSType 8612 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8613 return QualType(); 8614 } 8615 8616 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8617 // expression. These are mainly cases where the null pointer is used as an 8618 // integer instead of a pointer. 8619 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8620 SourceLocation Loc, bool IsCompare) { 8621 // The canonical way to check for a GNU null is with isNullPointerConstant, 8622 // but we use a bit of a hack here for speed; this is a relatively 8623 // hot path, and isNullPointerConstant is slow. 8624 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8625 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8626 8627 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8628 8629 // Avoid analyzing cases where the result will either be invalid (and 8630 // diagnosed as such) or entirely valid and not something to warn about. 8631 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8632 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8633 return; 8634 8635 // Comparison operations would not make sense with a null pointer no matter 8636 // what the other expression is. 8637 if (!IsCompare) { 8638 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8639 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8640 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8641 return; 8642 } 8643 8644 // The rest of the operations only make sense with a null pointer 8645 // if the other expression is a pointer. 8646 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8647 NonNullType->canDecayToPointerType()) 8648 return; 8649 8650 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8651 << LHSNull /* LHS is NULL */ << NonNullType 8652 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8653 } 8654 8655 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8656 ExprResult &RHS, 8657 SourceLocation Loc, bool IsDiv) { 8658 // Check for division/remainder by zero. 8659 llvm::APSInt RHSValue; 8660 if (!RHS.get()->isValueDependent() && 8661 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 8662 S.DiagRuntimeBehavior(Loc, RHS.get(), 8663 S.PDiag(diag::warn_remainder_division_by_zero) 8664 << IsDiv << RHS.get()->getSourceRange()); 8665 } 8666 8667 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8668 SourceLocation Loc, 8669 bool IsCompAssign, bool IsDiv) { 8670 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8671 8672 if (LHS.get()->getType()->isVectorType() || 8673 RHS.get()->getType()->isVectorType()) 8674 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8675 /*AllowBothBool*/getLangOpts().AltiVec, 8676 /*AllowBoolConversions*/false); 8677 8678 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8679 if (LHS.isInvalid() || RHS.isInvalid()) 8680 return QualType(); 8681 8682 8683 if (compType.isNull() || !compType->isArithmeticType()) 8684 return InvalidOperands(Loc, LHS, RHS); 8685 if (IsDiv) 8686 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8687 return compType; 8688 } 8689 8690 QualType Sema::CheckRemainderOperands( 8691 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8692 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8693 8694 if (LHS.get()->getType()->isVectorType() || 8695 RHS.get()->getType()->isVectorType()) { 8696 if (LHS.get()->getType()->hasIntegerRepresentation() && 8697 RHS.get()->getType()->hasIntegerRepresentation()) 8698 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8699 /*AllowBothBool*/getLangOpts().AltiVec, 8700 /*AllowBoolConversions*/false); 8701 return InvalidOperands(Loc, LHS, RHS); 8702 } 8703 8704 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8705 if (LHS.isInvalid() || RHS.isInvalid()) 8706 return QualType(); 8707 8708 if (compType.isNull() || !compType->isIntegerType()) 8709 return InvalidOperands(Loc, LHS, RHS); 8710 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8711 return compType; 8712 } 8713 8714 /// Diagnose invalid arithmetic on two void pointers. 8715 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8716 Expr *LHSExpr, Expr *RHSExpr) { 8717 S.Diag(Loc, S.getLangOpts().CPlusPlus 8718 ? diag::err_typecheck_pointer_arith_void_type 8719 : diag::ext_gnu_void_ptr) 8720 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8721 << RHSExpr->getSourceRange(); 8722 } 8723 8724 /// Diagnose invalid arithmetic on a void pointer. 8725 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8726 Expr *Pointer) { 8727 S.Diag(Loc, S.getLangOpts().CPlusPlus 8728 ? diag::err_typecheck_pointer_arith_void_type 8729 : diag::ext_gnu_void_ptr) 8730 << 0 /* one pointer */ << Pointer->getSourceRange(); 8731 } 8732 8733 /// Diagnose invalid arithmetic on a null pointer. 8734 /// 8735 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 8736 /// idiom, which we recognize as a GNU extension. 8737 /// 8738 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 8739 Expr *Pointer, bool IsGNUIdiom) { 8740 if (IsGNUIdiom) 8741 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 8742 << Pointer->getSourceRange(); 8743 else 8744 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 8745 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 8746 } 8747 8748 /// Diagnose invalid arithmetic on two function pointers. 8749 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8750 Expr *LHS, Expr *RHS) { 8751 assert(LHS->getType()->isAnyPointerType()); 8752 assert(RHS->getType()->isAnyPointerType()); 8753 S.Diag(Loc, S.getLangOpts().CPlusPlus 8754 ? diag::err_typecheck_pointer_arith_function_type 8755 : diag::ext_gnu_ptr_func_arith) 8756 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8757 // We only show the second type if it differs from the first. 8758 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8759 RHS->getType()) 8760 << RHS->getType()->getPointeeType() 8761 << LHS->getSourceRange() << RHS->getSourceRange(); 8762 } 8763 8764 /// Diagnose invalid arithmetic on a function pointer. 8765 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8766 Expr *Pointer) { 8767 assert(Pointer->getType()->isAnyPointerType()); 8768 S.Diag(Loc, S.getLangOpts().CPlusPlus 8769 ? diag::err_typecheck_pointer_arith_function_type 8770 : diag::ext_gnu_ptr_func_arith) 8771 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8772 << 0 /* one pointer, so only one type */ 8773 << Pointer->getSourceRange(); 8774 } 8775 8776 /// Emit error if Operand is incomplete pointer type 8777 /// 8778 /// \returns True if pointer has incomplete type 8779 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8780 Expr *Operand) { 8781 QualType ResType = Operand->getType(); 8782 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8783 ResType = ResAtomicType->getValueType(); 8784 8785 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8786 QualType PointeeTy = ResType->getPointeeType(); 8787 return S.RequireCompleteType(Loc, PointeeTy, 8788 diag::err_typecheck_arithmetic_incomplete_type, 8789 PointeeTy, Operand->getSourceRange()); 8790 } 8791 8792 /// Check the validity of an arithmetic pointer operand. 8793 /// 8794 /// If the operand has pointer type, this code will check for pointer types 8795 /// which are invalid in arithmetic operations. These will be diagnosed 8796 /// appropriately, including whether or not the use is supported as an 8797 /// extension. 8798 /// 8799 /// \returns True when the operand is valid to use (even if as an extension). 8800 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8801 Expr *Operand) { 8802 QualType ResType = Operand->getType(); 8803 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8804 ResType = ResAtomicType->getValueType(); 8805 8806 if (!ResType->isAnyPointerType()) return true; 8807 8808 QualType PointeeTy = ResType->getPointeeType(); 8809 if (PointeeTy->isVoidType()) { 8810 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8811 return !S.getLangOpts().CPlusPlus; 8812 } 8813 if (PointeeTy->isFunctionType()) { 8814 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8815 return !S.getLangOpts().CPlusPlus; 8816 } 8817 8818 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8819 8820 return true; 8821 } 8822 8823 /// Check the validity of a binary arithmetic operation w.r.t. pointer 8824 /// operands. 8825 /// 8826 /// This routine will diagnose any invalid arithmetic on pointer operands much 8827 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 8828 /// for emitting a single diagnostic even for operations where both LHS and RHS 8829 /// are (potentially problematic) pointers. 8830 /// 8831 /// \returns True when the operand is valid to use (even if as an extension). 8832 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 8833 Expr *LHSExpr, Expr *RHSExpr) { 8834 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 8835 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 8836 if (!isLHSPointer && !isRHSPointer) return true; 8837 8838 QualType LHSPointeeTy, RHSPointeeTy; 8839 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 8840 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 8841 8842 // if both are pointers check if operation is valid wrt address spaces 8843 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 8844 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 8845 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 8846 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 8847 S.Diag(Loc, 8848 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8849 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 8850 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 8851 return false; 8852 } 8853 } 8854 8855 // Check for arithmetic on pointers to incomplete types. 8856 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 8857 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 8858 if (isLHSVoidPtr || isRHSVoidPtr) { 8859 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 8860 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 8861 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 8862 8863 return !S.getLangOpts().CPlusPlus; 8864 } 8865 8866 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 8867 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 8868 if (isLHSFuncPtr || isRHSFuncPtr) { 8869 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 8870 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 8871 RHSExpr); 8872 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 8873 8874 return !S.getLangOpts().CPlusPlus; 8875 } 8876 8877 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 8878 return false; 8879 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 8880 return false; 8881 8882 return true; 8883 } 8884 8885 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 8886 /// literal. 8887 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 8888 Expr *LHSExpr, Expr *RHSExpr) { 8889 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 8890 Expr* IndexExpr = RHSExpr; 8891 if (!StrExpr) { 8892 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 8893 IndexExpr = LHSExpr; 8894 } 8895 8896 bool IsStringPlusInt = StrExpr && 8897 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 8898 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 8899 return; 8900 8901 llvm::APSInt index; 8902 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 8903 unsigned StrLenWithNull = StrExpr->getLength() + 1; 8904 if (index.isNonNegative() && 8905 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 8906 index.isUnsigned())) 8907 return; 8908 } 8909 8910 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 8911 Self.Diag(OpLoc, diag::warn_string_plus_int) 8912 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 8913 8914 // Only print a fixit for "str" + int, not for int + "str". 8915 if (IndexExpr == RHSExpr) { 8916 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 8917 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8918 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 8919 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8920 << FixItHint::CreateInsertion(EndLoc, "]"); 8921 } else 8922 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8923 } 8924 8925 /// Emit a warning when adding a char literal to a string. 8926 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 8927 Expr *LHSExpr, Expr *RHSExpr) { 8928 const Expr *StringRefExpr = LHSExpr; 8929 const CharacterLiteral *CharExpr = 8930 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 8931 8932 if (!CharExpr) { 8933 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 8934 StringRefExpr = RHSExpr; 8935 } 8936 8937 if (!CharExpr || !StringRefExpr) 8938 return; 8939 8940 const QualType StringType = StringRefExpr->getType(); 8941 8942 // Return if not a PointerType. 8943 if (!StringType->isAnyPointerType()) 8944 return; 8945 8946 // Return if not a CharacterType. 8947 if (!StringType->getPointeeType()->isAnyCharacterType()) 8948 return; 8949 8950 ASTContext &Ctx = Self.getASTContext(); 8951 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 8952 8953 const QualType CharType = CharExpr->getType(); 8954 if (!CharType->isAnyCharacterType() && 8955 CharType->isIntegerType() && 8956 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 8957 Self.Diag(OpLoc, diag::warn_string_plus_char) 8958 << DiagRange << Ctx.CharTy; 8959 } else { 8960 Self.Diag(OpLoc, diag::warn_string_plus_char) 8961 << DiagRange << CharExpr->getType(); 8962 } 8963 8964 // Only print a fixit for str + char, not for char + str. 8965 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 8966 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 8967 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 8968 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 8969 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 8970 << FixItHint::CreateInsertion(EndLoc, "]"); 8971 } else { 8972 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 8973 } 8974 } 8975 8976 /// Emit error when two pointers are incompatible. 8977 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 8978 Expr *LHSExpr, Expr *RHSExpr) { 8979 assert(LHSExpr->getType()->isAnyPointerType()); 8980 assert(RHSExpr->getType()->isAnyPointerType()); 8981 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 8982 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 8983 << RHSExpr->getSourceRange(); 8984 } 8985 8986 // C99 6.5.6 8987 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 8988 SourceLocation Loc, BinaryOperatorKind Opc, 8989 QualType* CompLHSTy) { 8990 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8991 8992 if (LHS.get()->getType()->isVectorType() || 8993 RHS.get()->getType()->isVectorType()) { 8994 QualType compType = CheckVectorOperands( 8995 LHS, RHS, Loc, CompLHSTy, 8996 /*AllowBothBool*/getLangOpts().AltiVec, 8997 /*AllowBoolConversions*/getLangOpts().ZVector); 8998 if (CompLHSTy) *CompLHSTy = compType; 8999 return compType; 9000 } 9001 9002 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9003 if (LHS.isInvalid() || RHS.isInvalid()) 9004 return QualType(); 9005 9006 // Diagnose "string literal" '+' int and string '+' "char literal". 9007 if (Opc == BO_Add) { 9008 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 9009 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 9010 } 9011 9012 // handle the common case first (both operands are arithmetic). 9013 if (!compType.isNull() && compType->isArithmeticType()) { 9014 if (CompLHSTy) *CompLHSTy = compType; 9015 return compType; 9016 } 9017 9018 // Type-checking. Ultimately the pointer's going to be in PExp; 9019 // note that we bias towards the LHS being the pointer. 9020 Expr *PExp = LHS.get(), *IExp = RHS.get(); 9021 9022 bool isObjCPointer; 9023 if (PExp->getType()->isPointerType()) { 9024 isObjCPointer = false; 9025 } else if (PExp->getType()->isObjCObjectPointerType()) { 9026 isObjCPointer = true; 9027 } else { 9028 std::swap(PExp, IExp); 9029 if (PExp->getType()->isPointerType()) { 9030 isObjCPointer = false; 9031 } else if (PExp->getType()->isObjCObjectPointerType()) { 9032 isObjCPointer = true; 9033 } else { 9034 return InvalidOperands(Loc, LHS, RHS); 9035 } 9036 } 9037 assert(PExp->getType()->isAnyPointerType()); 9038 9039 if (!IExp->getType()->isIntegerType()) 9040 return InvalidOperands(Loc, LHS, RHS); 9041 9042 // Adding to a null pointer results in undefined behavior. 9043 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 9044 Context, Expr::NPC_ValueDependentIsNotNull)) { 9045 // In C++ adding zero to a null pointer is defined. 9046 llvm::APSInt KnownVal; 9047 if (!getLangOpts().CPlusPlus || 9048 (!IExp->isValueDependent() && 9049 (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 9050 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 9051 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 9052 Context, BO_Add, PExp, IExp); 9053 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 9054 } 9055 } 9056 9057 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 9058 return QualType(); 9059 9060 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 9061 return QualType(); 9062 9063 // Check array bounds for pointer arithemtic 9064 CheckArrayAccess(PExp, IExp); 9065 9066 if (CompLHSTy) { 9067 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 9068 if (LHSTy.isNull()) { 9069 LHSTy = LHS.get()->getType(); 9070 if (LHSTy->isPromotableIntegerType()) 9071 LHSTy = Context.getPromotedIntegerType(LHSTy); 9072 } 9073 *CompLHSTy = LHSTy; 9074 } 9075 9076 return PExp->getType(); 9077 } 9078 9079 // C99 6.5.6 9080 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 9081 SourceLocation Loc, 9082 QualType* CompLHSTy) { 9083 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9084 9085 if (LHS.get()->getType()->isVectorType() || 9086 RHS.get()->getType()->isVectorType()) { 9087 QualType compType = CheckVectorOperands( 9088 LHS, RHS, Loc, CompLHSTy, 9089 /*AllowBothBool*/getLangOpts().AltiVec, 9090 /*AllowBoolConversions*/getLangOpts().ZVector); 9091 if (CompLHSTy) *CompLHSTy = compType; 9092 return compType; 9093 } 9094 9095 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9096 if (LHS.isInvalid() || RHS.isInvalid()) 9097 return QualType(); 9098 9099 // Enforce type constraints: C99 6.5.6p3. 9100 9101 // Handle the common case first (both operands are arithmetic). 9102 if (!compType.isNull() && compType->isArithmeticType()) { 9103 if (CompLHSTy) *CompLHSTy = compType; 9104 return compType; 9105 } 9106 9107 // Either ptr - int or ptr - ptr. 9108 if (LHS.get()->getType()->isAnyPointerType()) { 9109 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9110 9111 // Diagnose bad cases where we step over interface counts. 9112 if (LHS.get()->getType()->isObjCObjectPointerType() && 9113 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9114 return QualType(); 9115 9116 // The result type of a pointer-int computation is the pointer type. 9117 if (RHS.get()->getType()->isIntegerType()) { 9118 // Subtracting from a null pointer should produce a warning. 9119 // The last argument to the diagnose call says this doesn't match the 9120 // GNU int-to-pointer idiom. 9121 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9122 Expr::NPC_ValueDependentIsNotNull)) { 9123 // In C++ adding zero to a null pointer is defined. 9124 llvm::APSInt KnownVal; 9125 if (!getLangOpts().CPlusPlus || 9126 (!RHS.get()->isValueDependent() && 9127 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) { 9128 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9129 } 9130 } 9131 9132 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9133 return QualType(); 9134 9135 // Check array bounds for pointer arithemtic 9136 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9137 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9138 9139 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9140 return LHS.get()->getType(); 9141 } 9142 9143 // Handle pointer-pointer subtractions. 9144 if (const PointerType *RHSPTy 9145 = RHS.get()->getType()->getAs<PointerType>()) { 9146 QualType rpointee = RHSPTy->getPointeeType(); 9147 9148 if (getLangOpts().CPlusPlus) { 9149 // Pointee types must be the same: C++ [expr.add] 9150 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9151 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9152 } 9153 } else { 9154 // Pointee types must be compatible C99 6.5.6p3 9155 if (!Context.typesAreCompatible( 9156 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9157 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9158 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9159 return QualType(); 9160 } 9161 } 9162 9163 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9164 LHS.get(), RHS.get())) 9165 return QualType(); 9166 9167 // FIXME: Add warnings for nullptr - ptr. 9168 9169 // The pointee type may have zero size. As an extension, a structure or 9170 // union may have zero size or an array may have zero length. In this 9171 // case subtraction does not make sense. 9172 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9173 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9174 if (ElementSize.isZero()) { 9175 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9176 << rpointee.getUnqualifiedType() 9177 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9178 } 9179 } 9180 9181 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9182 return Context.getPointerDiffType(); 9183 } 9184 } 9185 9186 return InvalidOperands(Loc, LHS, RHS); 9187 } 9188 9189 static bool isScopedEnumerationType(QualType T) { 9190 if (const EnumType *ET = T->getAs<EnumType>()) 9191 return ET->getDecl()->isScoped(); 9192 return false; 9193 } 9194 9195 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9196 SourceLocation Loc, BinaryOperatorKind Opc, 9197 QualType LHSType) { 9198 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9199 // so skip remaining warnings as we don't want to modify values within Sema. 9200 if (S.getLangOpts().OpenCL) 9201 return; 9202 9203 llvm::APSInt Right; 9204 // Check right/shifter operand 9205 if (RHS.get()->isValueDependent() || 9206 !RHS.get()->EvaluateAsInt(Right, S.Context)) 9207 return; 9208 9209 if (Right.isNegative()) { 9210 S.DiagRuntimeBehavior(Loc, RHS.get(), 9211 S.PDiag(diag::warn_shift_negative) 9212 << RHS.get()->getSourceRange()); 9213 return; 9214 } 9215 llvm::APInt LeftBits(Right.getBitWidth(), 9216 S.Context.getTypeSize(LHS.get()->getType())); 9217 if (Right.uge(LeftBits)) { 9218 S.DiagRuntimeBehavior(Loc, RHS.get(), 9219 S.PDiag(diag::warn_shift_gt_typewidth) 9220 << RHS.get()->getSourceRange()); 9221 return; 9222 } 9223 if (Opc != BO_Shl) 9224 return; 9225 9226 // When left shifting an ICE which is signed, we can check for overflow which 9227 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 9228 // integers have defined behavior modulo one more than the maximum value 9229 // representable in the result type, so never warn for those. 9230 llvm::APSInt Left; 9231 if (LHS.get()->isValueDependent() || 9232 LHSType->hasUnsignedIntegerRepresentation() || 9233 !LHS.get()->EvaluateAsInt(Left, S.Context)) 9234 return; 9235 9236 // If LHS does not have a signed type and non-negative value 9237 // then, the behavior is undefined. Warn about it. 9238 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 9239 S.DiagRuntimeBehavior(Loc, LHS.get(), 9240 S.PDiag(diag::warn_shift_lhs_negative) 9241 << LHS.get()->getSourceRange()); 9242 return; 9243 } 9244 9245 llvm::APInt ResultBits = 9246 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9247 if (LeftBits.uge(ResultBits)) 9248 return; 9249 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9250 Result = Result.shl(Right); 9251 9252 // Print the bit representation of the signed integer as an unsigned 9253 // hexadecimal number. 9254 SmallString<40> HexResult; 9255 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9256 9257 // If we are only missing a sign bit, this is less likely to result in actual 9258 // bugs -- if the result is cast back to an unsigned type, it will have the 9259 // expected value. Thus we place this behind a different warning that can be 9260 // turned off separately if needed. 9261 if (LeftBits == ResultBits - 1) { 9262 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9263 << HexResult << LHSType 9264 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9265 return; 9266 } 9267 9268 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9269 << HexResult.str() << Result.getMinSignedBits() << LHSType 9270 << Left.getBitWidth() << LHS.get()->getSourceRange() 9271 << RHS.get()->getSourceRange(); 9272 } 9273 9274 /// Return the resulting type when a vector is shifted 9275 /// by a scalar or vector shift amount. 9276 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9277 SourceLocation Loc, bool IsCompAssign) { 9278 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9279 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9280 !LHS.get()->getType()->isVectorType()) { 9281 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9282 << RHS.get()->getType() << LHS.get()->getType() 9283 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9284 return QualType(); 9285 } 9286 9287 if (!IsCompAssign) { 9288 LHS = S.UsualUnaryConversions(LHS.get()); 9289 if (LHS.isInvalid()) return QualType(); 9290 } 9291 9292 RHS = S.UsualUnaryConversions(RHS.get()); 9293 if (RHS.isInvalid()) return QualType(); 9294 9295 QualType LHSType = LHS.get()->getType(); 9296 // Note that LHS might be a scalar because the routine calls not only in 9297 // OpenCL case. 9298 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9299 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9300 9301 // Note that RHS might not be a vector. 9302 QualType RHSType = RHS.get()->getType(); 9303 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9304 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9305 9306 // The operands need to be integers. 9307 if (!LHSEleType->isIntegerType()) { 9308 S.Diag(Loc, diag::err_typecheck_expect_int) 9309 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9310 return QualType(); 9311 } 9312 9313 if (!RHSEleType->isIntegerType()) { 9314 S.Diag(Loc, diag::err_typecheck_expect_int) 9315 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9316 return QualType(); 9317 } 9318 9319 if (!LHSVecTy) { 9320 assert(RHSVecTy); 9321 if (IsCompAssign) 9322 return RHSType; 9323 if (LHSEleType != RHSEleType) { 9324 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9325 LHSEleType = RHSEleType; 9326 } 9327 QualType VecTy = 9328 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9329 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9330 LHSType = VecTy; 9331 } else if (RHSVecTy) { 9332 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9333 // are applied component-wise. So if RHS is a vector, then ensure 9334 // that the number of elements is the same as LHS... 9335 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9336 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9337 << LHS.get()->getType() << RHS.get()->getType() 9338 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9339 return QualType(); 9340 } 9341 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9342 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9343 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9344 if (LHSBT != RHSBT && 9345 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9346 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9347 << LHS.get()->getType() << RHS.get()->getType() 9348 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9349 } 9350 } 9351 } else { 9352 // ...else expand RHS to match the number of elements in LHS. 9353 QualType VecTy = 9354 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9355 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9356 } 9357 9358 return LHSType; 9359 } 9360 9361 // C99 6.5.7 9362 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9363 SourceLocation Loc, BinaryOperatorKind Opc, 9364 bool IsCompAssign) { 9365 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9366 9367 // Vector shifts promote their scalar inputs to vector type. 9368 if (LHS.get()->getType()->isVectorType() || 9369 RHS.get()->getType()->isVectorType()) { 9370 if (LangOpts.ZVector) { 9371 // The shift operators for the z vector extensions work basically 9372 // like general shifts, except that neither the LHS nor the RHS is 9373 // allowed to be a "vector bool". 9374 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9375 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9376 return InvalidOperands(Loc, LHS, RHS); 9377 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9378 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9379 return InvalidOperands(Loc, LHS, RHS); 9380 } 9381 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9382 } 9383 9384 // Shifts don't perform usual arithmetic conversions, they just do integer 9385 // promotions on each operand. C99 6.5.7p3 9386 9387 // For the LHS, do usual unary conversions, but then reset them away 9388 // if this is a compound assignment. 9389 ExprResult OldLHS = LHS; 9390 LHS = UsualUnaryConversions(LHS.get()); 9391 if (LHS.isInvalid()) 9392 return QualType(); 9393 QualType LHSType = LHS.get()->getType(); 9394 if (IsCompAssign) LHS = OldLHS; 9395 9396 // The RHS is simpler. 9397 RHS = UsualUnaryConversions(RHS.get()); 9398 if (RHS.isInvalid()) 9399 return QualType(); 9400 QualType RHSType = RHS.get()->getType(); 9401 9402 // C99 6.5.7p2: Each of the operands shall have integer type. 9403 if (!LHSType->hasIntegerRepresentation() || 9404 !RHSType->hasIntegerRepresentation()) 9405 return InvalidOperands(Loc, LHS, RHS); 9406 9407 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9408 // hasIntegerRepresentation() above instead of this. 9409 if (isScopedEnumerationType(LHSType) || 9410 isScopedEnumerationType(RHSType)) { 9411 return InvalidOperands(Loc, LHS, RHS); 9412 } 9413 // Sanity-check shift operands 9414 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9415 9416 // "The type of the result is that of the promoted left operand." 9417 return LHSType; 9418 } 9419 9420 /// If two different enums are compared, raise a warning. 9421 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9422 Expr *RHS) { 9423 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9424 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9425 9426 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9427 if (!LHSEnumType) 9428 return; 9429 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9430 if (!RHSEnumType) 9431 return; 9432 9433 // Ignore anonymous enums. 9434 if (!LHSEnumType->getDecl()->getIdentifier() && 9435 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9436 return; 9437 if (!RHSEnumType->getDecl()->getIdentifier() && 9438 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9439 return; 9440 9441 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9442 return; 9443 9444 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9445 << LHSStrippedType << RHSStrippedType 9446 << LHS->getSourceRange() << RHS->getSourceRange(); 9447 } 9448 9449 /// Diagnose bad pointer comparisons. 9450 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9451 ExprResult &LHS, ExprResult &RHS, 9452 bool IsError) { 9453 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9454 : diag::ext_typecheck_comparison_of_distinct_pointers) 9455 << LHS.get()->getType() << RHS.get()->getType() 9456 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9457 } 9458 9459 /// Returns false if the pointers are converted to a composite type, 9460 /// true otherwise. 9461 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9462 ExprResult &LHS, ExprResult &RHS) { 9463 // C++ [expr.rel]p2: 9464 // [...] Pointer conversions (4.10) and qualification 9465 // conversions (4.4) are performed on pointer operands (or on 9466 // a pointer operand and a null pointer constant) to bring 9467 // them to their composite pointer type. [...] 9468 // 9469 // C++ [expr.eq]p1 uses the same notion for (in)equality 9470 // comparisons of pointers. 9471 9472 QualType LHSType = LHS.get()->getType(); 9473 QualType RHSType = RHS.get()->getType(); 9474 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9475 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9476 9477 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9478 if (T.isNull()) { 9479 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9480 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9481 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9482 else 9483 S.InvalidOperands(Loc, LHS, RHS); 9484 return true; 9485 } 9486 9487 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9488 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9489 return false; 9490 } 9491 9492 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9493 ExprResult &LHS, 9494 ExprResult &RHS, 9495 bool IsError) { 9496 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9497 : diag::ext_typecheck_comparison_of_fptr_to_void) 9498 << LHS.get()->getType() << RHS.get()->getType() 9499 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9500 } 9501 9502 static bool isObjCObjectLiteral(ExprResult &E) { 9503 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9504 case Stmt::ObjCArrayLiteralClass: 9505 case Stmt::ObjCDictionaryLiteralClass: 9506 case Stmt::ObjCStringLiteralClass: 9507 case Stmt::ObjCBoxedExprClass: 9508 return true; 9509 default: 9510 // Note that ObjCBoolLiteral is NOT an object literal! 9511 return false; 9512 } 9513 } 9514 9515 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9516 const ObjCObjectPointerType *Type = 9517 LHS->getType()->getAs<ObjCObjectPointerType>(); 9518 9519 // If this is not actually an Objective-C object, bail out. 9520 if (!Type) 9521 return false; 9522 9523 // Get the LHS object's interface type. 9524 QualType InterfaceType = Type->getPointeeType(); 9525 9526 // If the RHS isn't an Objective-C object, bail out. 9527 if (!RHS->getType()->isObjCObjectPointerType()) 9528 return false; 9529 9530 // Try to find the -isEqual: method. 9531 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9532 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9533 InterfaceType, 9534 /*instance=*/true); 9535 if (!Method) { 9536 if (Type->isObjCIdType()) { 9537 // For 'id', just check the global pool. 9538 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9539 /*receiverId=*/true); 9540 } else { 9541 // Check protocols. 9542 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9543 /*instance=*/true); 9544 } 9545 } 9546 9547 if (!Method) 9548 return false; 9549 9550 QualType T = Method->parameters()[0]->getType(); 9551 if (!T->isObjCObjectPointerType()) 9552 return false; 9553 9554 QualType R = Method->getReturnType(); 9555 if (!R->isScalarType()) 9556 return false; 9557 9558 return true; 9559 } 9560 9561 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9562 FromE = FromE->IgnoreParenImpCasts(); 9563 switch (FromE->getStmtClass()) { 9564 default: 9565 break; 9566 case Stmt::ObjCStringLiteralClass: 9567 // "string literal" 9568 return LK_String; 9569 case Stmt::ObjCArrayLiteralClass: 9570 // "array literal" 9571 return LK_Array; 9572 case Stmt::ObjCDictionaryLiteralClass: 9573 // "dictionary literal" 9574 return LK_Dictionary; 9575 case Stmt::BlockExprClass: 9576 return LK_Block; 9577 case Stmt::ObjCBoxedExprClass: { 9578 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9579 switch (Inner->getStmtClass()) { 9580 case Stmt::IntegerLiteralClass: 9581 case Stmt::FloatingLiteralClass: 9582 case Stmt::CharacterLiteralClass: 9583 case Stmt::ObjCBoolLiteralExprClass: 9584 case Stmt::CXXBoolLiteralExprClass: 9585 // "numeric literal" 9586 return LK_Numeric; 9587 case Stmt::ImplicitCastExprClass: { 9588 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9589 // Boolean literals can be represented by implicit casts. 9590 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9591 return LK_Numeric; 9592 break; 9593 } 9594 default: 9595 break; 9596 } 9597 return LK_Boxed; 9598 } 9599 } 9600 return LK_None; 9601 } 9602 9603 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9604 ExprResult &LHS, ExprResult &RHS, 9605 BinaryOperator::Opcode Opc){ 9606 Expr *Literal; 9607 Expr *Other; 9608 if (isObjCObjectLiteral(LHS)) { 9609 Literal = LHS.get(); 9610 Other = RHS.get(); 9611 } else { 9612 Literal = RHS.get(); 9613 Other = LHS.get(); 9614 } 9615 9616 // Don't warn on comparisons against nil. 9617 Other = Other->IgnoreParenCasts(); 9618 if (Other->isNullPointerConstant(S.getASTContext(), 9619 Expr::NPC_ValueDependentIsNotNull)) 9620 return; 9621 9622 // This should be kept in sync with warn_objc_literal_comparison. 9623 // LK_String should always be after the other literals, since it has its own 9624 // warning flag. 9625 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9626 assert(LiteralKind != Sema::LK_Block); 9627 if (LiteralKind == Sema::LK_None) { 9628 llvm_unreachable("Unknown Objective-C object literal kind"); 9629 } 9630 9631 if (LiteralKind == Sema::LK_String) 9632 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9633 << Literal->getSourceRange(); 9634 else 9635 S.Diag(Loc, diag::warn_objc_literal_comparison) 9636 << LiteralKind << Literal->getSourceRange(); 9637 9638 if (BinaryOperator::isEqualityOp(Opc) && 9639 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9640 SourceLocation Start = LHS.get()->getBeginLoc(); 9641 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 9642 CharSourceRange OpRange = 9643 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9644 9645 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9646 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9647 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9648 << FixItHint::CreateInsertion(End, "]"); 9649 } 9650 } 9651 9652 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9653 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9654 ExprResult &RHS, SourceLocation Loc, 9655 BinaryOperatorKind Opc) { 9656 // Check that left hand side is !something. 9657 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9658 if (!UO || UO->getOpcode() != UO_LNot) return; 9659 9660 // Only check if the right hand side is non-bool arithmetic type. 9661 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9662 9663 // Make sure that the something in !something is not bool. 9664 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9665 if (SubExpr->isKnownToHaveBooleanValue()) return; 9666 9667 // Emit warning. 9668 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9669 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9670 << Loc << IsBitwiseOp; 9671 9672 // First note suggest !(x < y) 9673 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 9674 SourceLocation FirstClose = RHS.get()->getEndLoc(); 9675 FirstClose = S.getLocForEndOfToken(FirstClose); 9676 if (FirstClose.isInvalid()) 9677 FirstOpen = SourceLocation(); 9678 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9679 << IsBitwiseOp 9680 << FixItHint::CreateInsertion(FirstOpen, "(") 9681 << FixItHint::CreateInsertion(FirstClose, ")"); 9682 9683 // Second note suggests (!x) < y 9684 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 9685 SourceLocation SecondClose = LHS.get()->getEndLoc(); 9686 SecondClose = S.getLocForEndOfToken(SecondClose); 9687 if (SecondClose.isInvalid()) 9688 SecondOpen = SourceLocation(); 9689 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9690 << FixItHint::CreateInsertion(SecondOpen, "(") 9691 << FixItHint::CreateInsertion(SecondClose, ")"); 9692 } 9693 9694 // Get the decl for a simple expression: a reference to a variable, 9695 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9696 static ValueDecl *getCompareDecl(Expr *E) { 9697 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) 9698 return DR->getDecl(); 9699 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9700 if (Ivar->isFreeIvar()) 9701 return Ivar->getDecl(); 9702 } 9703 if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 9704 if (Mem->isImplicitAccess()) 9705 return Mem->getMemberDecl(); 9706 } 9707 return nullptr; 9708 } 9709 9710 /// Diagnose some forms of syntactically-obvious tautological comparison. 9711 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 9712 Expr *LHS, Expr *RHS, 9713 BinaryOperatorKind Opc) { 9714 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 9715 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 9716 9717 QualType LHSType = LHS->getType(); 9718 QualType RHSType = RHS->getType(); 9719 if (LHSType->hasFloatingRepresentation() || 9720 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 9721 LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() || 9722 S.inTemplateInstantiation()) 9723 return; 9724 9725 // Comparisons between two array types are ill-formed for operator<=>, so 9726 // we shouldn't emit any additional warnings about it. 9727 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 9728 return; 9729 9730 // For non-floating point types, check for self-comparisons of the form 9731 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9732 // often indicate logic errors in the program. 9733 // 9734 // NOTE: Don't warn about comparison expressions resulting from macro 9735 // expansion. Also don't warn about comparisons which are only self 9736 // comparisons within a template instantiation. The warnings should catch 9737 // obvious cases in the definition of the template anyways. The idea is to 9738 // warn when the typed comparison operator will always evaluate to the same 9739 // result. 9740 ValueDecl *DL = getCompareDecl(LHSStripped); 9741 ValueDecl *DR = getCompareDecl(RHSStripped); 9742 if (DL && DR && declaresSameEntity(DL, DR)) { 9743 StringRef Result; 9744 switch (Opc) { 9745 case BO_EQ: case BO_LE: case BO_GE: 9746 Result = "true"; 9747 break; 9748 case BO_NE: case BO_LT: case BO_GT: 9749 Result = "false"; 9750 break; 9751 case BO_Cmp: 9752 Result = "'std::strong_ordering::equal'"; 9753 break; 9754 default: 9755 break; 9756 } 9757 S.DiagRuntimeBehavior(Loc, nullptr, 9758 S.PDiag(diag::warn_comparison_always) 9759 << 0 /*self-comparison*/ << !Result.empty() 9760 << Result); 9761 } else if (DL && DR && 9762 DL->getType()->isArrayType() && DR->getType()->isArrayType() && 9763 !DL->isWeak() && !DR->isWeak()) { 9764 // What is it always going to evaluate to? 9765 StringRef Result; 9766 switch(Opc) { 9767 case BO_EQ: // e.g. array1 == array2 9768 Result = "false"; 9769 break; 9770 case BO_NE: // e.g. array1 != array2 9771 Result = "true"; 9772 break; 9773 default: // e.g. array1 <= array2 9774 // The best we can say is 'a constant' 9775 break; 9776 } 9777 S.DiagRuntimeBehavior(Loc, nullptr, 9778 S.PDiag(diag::warn_comparison_always) 9779 << 1 /*array comparison*/ 9780 << !Result.empty() << Result); 9781 } 9782 9783 if (isa<CastExpr>(LHSStripped)) 9784 LHSStripped = LHSStripped->IgnoreParenCasts(); 9785 if (isa<CastExpr>(RHSStripped)) 9786 RHSStripped = RHSStripped->IgnoreParenCasts(); 9787 9788 // Warn about comparisons against a string constant (unless the other 9789 // operand is null); the user probably wants strcmp. 9790 Expr *LiteralString = nullptr; 9791 Expr *LiteralStringStripped = nullptr; 9792 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9793 !RHSStripped->isNullPointerConstant(S.Context, 9794 Expr::NPC_ValueDependentIsNull)) { 9795 LiteralString = LHS; 9796 LiteralStringStripped = LHSStripped; 9797 } else if ((isa<StringLiteral>(RHSStripped) || 9798 isa<ObjCEncodeExpr>(RHSStripped)) && 9799 !LHSStripped->isNullPointerConstant(S.Context, 9800 Expr::NPC_ValueDependentIsNull)) { 9801 LiteralString = RHS; 9802 LiteralStringStripped = RHSStripped; 9803 } 9804 9805 if (LiteralString) { 9806 S.DiagRuntimeBehavior(Loc, nullptr, 9807 S.PDiag(diag::warn_stringcompare) 9808 << isa<ObjCEncodeExpr>(LiteralStringStripped) 9809 << LiteralString->getSourceRange()); 9810 } 9811 } 9812 9813 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 9814 switch (CK) { 9815 default: { 9816 #ifndef NDEBUG 9817 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 9818 << "\n"; 9819 #endif 9820 llvm_unreachable("unhandled cast kind"); 9821 } 9822 case CK_UserDefinedConversion: 9823 return ICK_Identity; 9824 case CK_LValueToRValue: 9825 return ICK_Lvalue_To_Rvalue; 9826 case CK_ArrayToPointerDecay: 9827 return ICK_Array_To_Pointer; 9828 case CK_FunctionToPointerDecay: 9829 return ICK_Function_To_Pointer; 9830 case CK_IntegralCast: 9831 return ICK_Integral_Conversion; 9832 case CK_FloatingCast: 9833 return ICK_Floating_Conversion; 9834 case CK_IntegralToFloating: 9835 case CK_FloatingToIntegral: 9836 return ICK_Floating_Integral; 9837 case CK_IntegralComplexCast: 9838 case CK_FloatingComplexCast: 9839 case CK_FloatingComplexToIntegralComplex: 9840 case CK_IntegralComplexToFloatingComplex: 9841 return ICK_Complex_Conversion; 9842 case CK_FloatingComplexToReal: 9843 case CK_FloatingRealToComplex: 9844 case CK_IntegralComplexToReal: 9845 case CK_IntegralRealToComplex: 9846 return ICK_Complex_Real; 9847 } 9848 } 9849 9850 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 9851 QualType FromType, 9852 SourceLocation Loc) { 9853 // Check for a narrowing implicit conversion. 9854 StandardConversionSequence SCS; 9855 SCS.setAsIdentityConversion(); 9856 SCS.setToType(0, FromType); 9857 SCS.setToType(1, ToType); 9858 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 9859 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 9860 9861 APValue PreNarrowingValue; 9862 QualType PreNarrowingType; 9863 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 9864 PreNarrowingType, 9865 /*IgnoreFloatToIntegralConversion*/ true)) { 9866 case NK_Dependent_Narrowing: 9867 // Implicit conversion to a narrower type, but the expression is 9868 // value-dependent so we can't tell whether it's actually narrowing. 9869 case NK_Not_Narrowing: 9870 return false; 9871 9872 case NK_Constant_Narrowing: 9873 // Implicit conversion to a narrower type, and the value is not a constant 9874 // expression. 9875 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 9876 << /*Constant*/ 1 9877 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 9878 return true; 9879 9880 case NK_Variable_Narrowing: 9881 // Implicit conversion to a narrower type, and the value is not a constant 9882 // expression. 9883 case NK_Type_Narrowing: 9884 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 9885 << /*Constant*/ 0 << FromType << ToType; 9886 // TODO: It's not a constant expression, but what if the user intended it 9887 // to be? Can we produce notes to help them figure out why it isn't? 9888 return true; 9889 } 9890 llvm_unreachable("unhandled case in switch"); 9891 } 9892 9893 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 9894 ExprResult &LHS, 9895 ExprResult &RHS, 9896 SourceLocation Loc) { 9897 using CCT = ComparisonCategoryType; 9898 9899 QualType LHSType = LHS.get()->getType(); 9900 QualType RHSType = RHS.get()->getType(); 9901 // Dig out the original argument type and expression before implicit casts 9902 // were applied. These are the types/expressions we need to check the 9903 // [expr.spaceship] requirements against. 9904 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 9905 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 9906 QualType LHSStrippedType = LHSStripped.get()->getType(); 9907 QualType RHSStrippedType = RHSStripped.get()->getType(); 9908 9909 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 9910 // other is not, the program is ill-formed. 9911 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 9912 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 9913 return QualType(); 9914 } 9915 9916 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 9917 RHSStrippedType->isEnumeralType(); 9918 if (NumEnumArgs == 1) { 9919 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 9920 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 9921 if (OtherTy->hasFloatingRepresentation()) { 9922 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 9923 return QualType(); 9924 } 9925 } 9926 if (NumEnumArgs == 2) { 9927 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 9928 // type E, the operator yields the result of converting the operands 9929 // to the underlying type of E and applying <=> to the converted operands. 9930 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 9931 S.InvalidOperands(Loc, LHS, RHS); 9932 return QualType(); 9933 } 9934 QualType IntType = 9935 LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType(); 9936 assert(IntType->isArithmeticType()); 9937 9938 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 9939 // promote the boolean type, and all other promotable integer types, to 9940 // avoid this. 9941 if (IntType->isPromotableIntegerType()) 9942 IntType = S.Context.getPromotedIntegerType(IntType); 9943 9944 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 9945 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 9946 LHSType = RHSType = IntType; 9947 } 9948 9949 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 9950 // usual arithmetic conversions are applied to the operands. 9951 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 9952 if (LHS.isInvalid() || RHS.isInvalid()) 9953 return QualType(); 9954 if (Type.isNull()) 9955 return S.InvalidOperands(Loc, LHS, RHS); 9956 assert(Type->isArithmeticType() || Type->isEnumeralType()); 9957 9958 bool HasNarrowing = checkThreeWayNarrowingConversion( 9959 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 9960 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 9961 RHS.get()->getBeginLoc()); 9962 if (HasNarrowing) 9963 return QualType(); 9964 9965 assert(!Type.isNull() && "composite type for <=> has not been set"); 9966 9967 auto TypeKind = [&]() { 9968 if (const ComplexType *CT = Type->getAs<ComplexType>()) { 9969 if (CT->getElementType()->hasFloatingRepresentation()) 9970 return CCT::WeakEquality; 9971 return CCT::StrongEquality; 9972 } 9973 if (Type->isIntegralOrEnumerationType()) 9974 return CCT::StrongOrdering; 9975 if (Type->hasFloatingRepresentation()) 9976 return CCT::PartialOrdering; 9977 llvm_unreachable("other types are unimplemented"); 9978 }(); 9979 9980 return S.CheckComparisonCategoryType(TypeKind, Loc); 9981 } 9982 9983 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 9984 ExprResult &RHS, 9985 SourceLocation Loc, 9986 BinaryOperatorKind Opc) { 9987 if (Opc == BO_Cmp) 9988 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 9989 9990 // C99 6.5.8p3 / C99 6.5.9p4 9991 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 9992 if (LHS.isInvalid() || RHS.isInvalid()) 9993 return QualType(); 9994 if (Type.isNull()) 9995 return S.InvalidOperands(Loc, LHS, RHS); 9996 assert(Type->isArithmeticType() || Type->isEnumeralType()); 9997 9998 checkEnumComparison(S, Loc, LHS.get(), RHS.get()); 9999 10000 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 10001 return S.InvalidOperands(Loc, LHS, RHS); 10002 10003 // Check for comparisons of floating point operands using != and ==. 10004 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 10005 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10006 10007 // The result of comparisons is 'bool' in C++, 'int' in C. 10008 return S.Context.getLogicalOperationType(); 10009 } 10010 10011 // C99 6.5.8, C++ [expr.rel] 10012 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 10013 SourceLocation Loc, 10014 BinaryOperatorKind Opc) { 10015 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 10016 bool IsThreeWay = Opc == BO_Cmp; 10017 auto IsAnyPointerType = [](ExprResult E) { 10018 QualType Ty = E.get()->getType(); 10019 return Ty->isPointerType() || Ty->isMemberPointerType(); 10020 }; 10021 10022 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 10023 // type, array-to-pointer, ..., conversions are performed on both operands to 10024 // bring them to their composite type. 10025 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 10026 // any type-related checks. 10027 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 10028 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10029 if (LHS.isInvalid()) 10030 return QualType(); 10031 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10032 if (RHS.isInvalid()) 10033 return QualType(); 10034 } else { 10035 LHS = DefaultLvalueConversion(LHS.get()); 10036 if (LHS.isInvalid()) 10037 return QualType(); 10038 RHS = DefaultLvalueConversion(RHS.get()); 10039 if (RHS.isInvalid()) 10040 return QualType(); 10041 } 10042 10043 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 10044 10045 // Handle vector comparisons separately. 10046 if (LHS.get()->getType()->isVectorType() || 10047 RHS.get()->getType()->isVectorType()) 10048 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 10049 10050 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10051 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10052 10053 QualType LHSType = LHS.get()->getType(); 10054 QualType RHSType = RHS.get()->getType(); 10055 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 10056 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 10057 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 10058 10059 const Expr::NullPointerConstantKind LHSNullKind = 10060 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10061 const Expr::NullPointerConstantKind RHSNullKind = 10062 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10063 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 10064 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 10065 10066 auto computeResultTy = [&]() { 10067 if (Opc != BO_Cmp) 10068 return Context.getLogicalOperationType(); 10069 assert(getLangOpts().CPlusPlus); 10070 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 10071 10072 QualType CompositeTy = LHS.get()->getType(); 10073 assert(!CompositeTy->isReferenceType()); 10074 10075 auto buildResultTy = [&](ComparisonCategoryType Kind) { 10076 return CheckComparisonCategoryType(Kind, Loc); 10077 }; 10078 10079 // C++2a [expr.spaceship]p7: If the composite pointer type is a function 10080 // pointer type, a pointer-to-member type, or std::nullptr_t, the 10081 // result is of type std::strong_equality 10082 if (CompositeTy->isFunctionPointerType() || 10083 CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType()) 10084 // FIXME: consider making the function pointer case produce 10085 // strong_ordering not strong_equality, per P0946R0-Jax18 discussion 10086 // and direction polls 10087 return buildResultTy(ComparisonCategoryType::StrongEquality); 10088 10089 // C++2a [expr.spaceship]p8: If the composite pointer type is an object 10090 // pointer type, p <=> q is of type std::strong_ordering. 10091 if (CompositeTy->isPointerType()) { 10092 // P0946R0: Comparisons between a null pointer constant and an object 10093 // pointer result in std::strong_equality 10094 if (LHSIsNull != RHSIsNull) 10095 return buildResultTy(ComparisonCategoryType::StrongEquality); 10096 return buildResultTy(ComparisonCategoryType::StrongOrdering); 10097 } 10098 // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed. 10099 // TODO: Extend support for operator<=> to ObjC types. 10100 return InvalidOperands(Loc, LHS, RHS); 10101 }; 10102 10103 10104 if (!IsRelational && LHSIsNull != RHSIsNull) { 10105 bool IsEquality = Opc == BO_EQ; 10106 if (RHSIsNull) 10107 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 10108 RHS.get()->getSourceRange()); 10109 else 10110 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 10111 LHS.get()->getSourceRange()); 10112 } 10113 10114 if ((LHSType->isIntegerType() && !LHSIsNull) || 10115 (RHSType->isIntegerType() && !RHSIsNull)) { 10116 // Skip normal pointer conversion checks in this case; we have better 10117 // diagnostics for this below. 10118 } else if (getLangOpts().CPlusPlus) { 10119 // Equality comparison of a function pointer to a void pointer is invalid, 10120 // but we allow it as an extension. 10121 // FIXME: If we really want to allow this, should it be part of composite 10122 // pointer type computation so it works in conditionals too? 10123 if (!IsRelational && 10124 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 10125 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 10126 // This is a gcc extension compatibility comparison. 10127 // In a SFINAE context, we treat this as a hard error to maintain 10128 // conformance with the C++ standard. 10129 diagnoseFunctionPointerToVoidComparison( 10130 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 10131 10132 if (isSFINAEContext()) 10133 return QualType(); 10134 10135 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10136 return computeResultTy(); 10137 } 10138 10139 // C++ [expr.eq]p2: 10140 // If at least one operand is a pointer [...] bring them to their 10141 // composite pointer type. 10142 // C++ [expr.spaceship]p6 10143 // If at least one of the operands is of pointer type, [...] bring them 10144 // to their composite pointer type. 10145 // C++ [expr.rel]p2: 10146 // If both operands are pointers, [...] bring them to their composite 10147 // pointer type. 10148 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 10149 (IsRelational ? 2 : 1) && 10150 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 10151 RHSType->isObjCObjectPointerType()))) { 10152 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10153 return QualType(); 10154 return computeResultTy(); 10155 } 10156 } else if (LHSType->isPointerType() && 10157 RHSType->isPointerType()) { // C99 6.5.8p2 10158 // All of the following pointer-related warnings are GCC extensions, except 10159 // when handling null pointer constants. 10160 QualType LCanPointeeTy = 10161 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10162 QualType RCanPointeeTy = 10163 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10164 10165 // C99 6.5.9p2 and C99 6.5.8p2 10166 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 10167 RCanPointeeTy.getUnqualifiedType())) { 10168 // Valid unless a relational comparison of function pointers 10169 if (IsRelational && LCanPointeeTy->isFunctionType()) { 10170 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 10171 << LHSType << RHSType << LHS.get()->getSourceRange() 10172 << RHS.get()->getSourceRange(); 10173 } 10174 } else if (!IsRelational && 10175 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 10176 // Valid unless comparison between non-null pointer and function pointer 10177 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 10178 && !LHSIsNull && !RHSIsNull) 10179 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 10180 /*isError*/false); 10181 } else { 10182 // Invalid 10183 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 10184 } 10185 if (LCanPointeeTy != RCanPointeeTy) { 10186 // Treat NULL constant as a special case in OpenCL. 10187 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 10188 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 10189 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 10190 Diag(Loc, 10191 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10192 << LHSType << RHSType << 0 /* comparison */ 10193 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10194 } 10195 } 10196 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 10197 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 10198 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 10199 : CK_BitCast; 10200 if (LHSIsNull && !RHSIsNull) 10201 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 10202 else 10203 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 10204 } 10205 return computeResultTy(); 10206 } 10207 10208 if (getLangOpts().CPlusPlus) { 10209 // C++ [expr.eq]p4: 10210 // Two operands of type std::nullptr_t or one operand of type 10211 // std::nullptr_t and the other a null pointer constant compare equal. 10212 if (!IsRelational && LHSIsNull && RHSIsNull) { 10213 if (LHSType->isNullPtrType()) { 10214 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10215 return computeResultTy(); 10216 } 10217 if (RHSType->isNullPtrType()) { 10218 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10219 return computeResultTy(); 10220 } 10221 } 10222 10223 // Comparison of Objective-C pointers and block pointers against nullptr_t. 10224 // These aren't covered by the composite pointer type rules. 10225 if (!IsRelational && RHSType->isNullPtrType() && 10226 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 10227 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10228 return computeResultTy(); 10229 } 10230 if (!IsRelational && LHSType->isNullPtrType() && 10231 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 10232 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10233 return computeResultTy(); 10234 } 10235 10236 if (IsRelational && 10237 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 10238 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 10239 // HACK: Relational comparison of nullptr_t against a pointer type is 10240 // invalid per DR583, but we allow it within std::less<> and friends, 10241 // since otherwise common uses of it break. 10242 // FIXME: Consider removing this hack once LWG fixes std::less<> and 10243 // friends to have std::nullptr_t overload candidates. 10244 DeclContext *DC = CurContext; 10245 if (isa<FunctionDecl>(DC)) 10246 DC = DC->getParent(); 10247 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 10248 if (CTSD->isInStdNamespace() && 10249 llvm::StringSwitch<bool>(CTSD->getName()) 10250 .Cases("less", "less_equal", "greater", "greater_equal", true) 10251 .Default(false)) { 10252 if (RHSType->isNullPtrType()) 10253 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10254 else 10255 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10256 return computeResultTy(); 10257 } 10258 } 10259 } 10260 10261 // C++ [expr.eq]p2: 10262 // If at least one operand is a pointer to member, [...] bring them to 10263 // their composite pointer type. 10264 if (!IsRelational && 10265 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 10266 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10267 return QualType(); 10268 else 10269 return computeResultTy(); 10270 } 10271 } 10272 10273 // Handle block pointer types. 10274 if (!IsRelational && LHSType->isBlockPointerType() && 10275 RHSType->isBlockPointerType()) { 10276 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 10277 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 10278 10279 if (!LHSIsNull && !RHSIsNull && 10280 !Context.typesAreCompatible(lpointee, rpointee)) { 10281 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10282 << LHSType << RHSType << LHS.get()->getSourceRange() 10283 << RHS.get()->getSourceRange(); 10284 } 10285 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10286 return computeResultTy(); 10287 } 10288 10289 // Allow block pointers to be compared with null pointer constants. 10290 if (!IsRelational 10291 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 10292 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 10293 if (!LHSIsNull && !RHSIsNull) { 10294 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 10295 ->getPointeeType()->isVoidType()) 10296 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 10297 ->getPointeeType()->isVoidType()))) 10298 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10299 << LHSType << RHSType << LHS.get()->getSourceRange() 10300 << RHS.get()->getSourceRange(); 10301 } 10302 if (LHSIsNull && !RHSIsNull) 10303 LHS = ImpCastExprToType(LHS.get(), RHSType, 10304 RHSType->isPointerType() ? CK_BitCast 10305 : CK_AnyPointerToBlockPointerCast); 10306 else 10307 RHS = ImpCastExprToType(RHS.get(), LHSType, 10308 LHSType->isPointerType() ? CK_BitCast 10309 : CK_AnyPointerToBlockPointerCast); 10310 return computeResultTy(); 10311 } 10312 10313 if (LHSType->isObjCObjectPointerType() || 10314 RHSType->isObjCObjectPointerType()) { 10315 const PointerType *LPT = LHSType->getAs<PointerType>(); 10316 const PointerType *RPT = RHSType->getAs<PointerType>(); 10317 if (LPT || RPT) { 10318 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 10319 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 10320 10321 if (!LPtrToVoid && !RPtrToVoid && 10322 !Context.typesAreCompatible(LHSType, RHSType)) { 10323 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10324 /*isError*/false); 10325 } 10326 if (LHSIsNull && !RHSIsNull) { 10327 Expr *E = LHS.get(); 10328 if (getLangOpts().ObjCAutoRefCount) 10329 CheckObjCConversion(SourceRange(), RHSType, E, 10330 CCK_ImplicitConversion); 10331 LHS = ImpCastExprToType(E, RHSType, 10332 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10333 } 10334 else { 10335 Expr *E = RHS.get(); 10336 if (getLangOpts().ObjCAutoRefCount) 10337 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 10338 /*Diagnose=*/true, 10339 /*DiagnoseCFAudited=*/false, Opc); 10340 RHS = ImpCastExprToType(E, LHSType, 10341 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10342 } 10343 return computeResultTy(); 10344 } 10345 if (LHSType->isObjCObjectPointerType() && 10346 RHSType->isObjCObjectPointerType()) { 10347 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 10348 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10349 /*isError*/false); 10350 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 10351 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 10352 10353 if (LHSIsNull && !RHSIsNull) 10354 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10355 else 10356 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10357 return computeResultTy(); 10358 } 10359 10360 if (!IsRelational && LHSType->isBlockPointerType() && 10361 RHSType->isBlockCompatibleObjCPointerType(Context)) { 10362 LHS = ImpCastExprToType(LHS.get(), RHSType, 10363 CK_BlockPointerToObjCPointerCast); 10364 return computeResultTy(); 10365 } else if (!IsRelational && 10366 LHSType->isBlockCompatibleObjCPointerType(Context) && 10367 RHSType->isBlockPointerType()) { 10368 RHS = ImpCastExprToType(RHS.get(), LHSType, 10369 CK_BlockPointerToObjCPointerCast); 10370 return computeResultTy(); 10371 } 10372 } 10373 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 10374 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 10375 unsigned DiagID = 0; 10376 bool isError = false; 10377 if (LangOpts.DebuggerSupport) { 10378 // Under a debugger, allow the comparison of pointers to integers, 10379 // since users tend to want to compare addresses. 10380 } else if ((LHSIsNull && LHSType->isIntegerType()) || 10381 (RHSIsNull && RHSType->isIntegerType())) { 10382 if (IsRelational) { 10383 isError = getLangOpts().CPlusPlus; 10384 DiagID = 10385 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 10386 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 10387 } 10388 } else if (getLangOpts().CPlusPlus) { 10389 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 10390 isError = true; 10391 } else if (IsRelational) 10392 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 10393 else 10394 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 10395 10396 if (DiagID) { 10397 Diag(Loc, DiagID) 10398 << LHSType << RHSType << LHS.get()->getSourceRange() 10399 << RHS.get()->getSourceRange(); 10400 if (isError) 10401 return QualType(); 10402 } 10403 10404 if (LHSType->isIntegerType()) 10405 LHS = ImpCastExprToType(LHS.get(), RHSType, 10406 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10407 else 10408 RHS = ImpCastExprToType(RHS.get(), LHSType, 10409 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10410 return computeResultTy(); 10411 } 10412 10413 // Handle block pointers. 10414 if (!IsRelational && RHSIsNull 10415 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 10416 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10417 return computeResultTy(); 10418 } 10419 if (!IsRelational && LHSIsNull 10420 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 10421 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10422 return computeResultTy(); 10423 } 10424 10425 if (getLangOpts().OpenCLVersion >= 200) { 10426 if (LHSIsNull && RHSType->isQueueT()) { 10427 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10428 return computeResultTy(); 10429 } 10430 10431 if (LHSType->isQueueT() && RHSIsNull) { 10432 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10433 return computeResultTy(); 10434 } 10435 } 10436 10437 return InvalidOperands(Loc, LHS, RHS); 10438 } 10439 10440 // Return a signed ext_vector_type that is of identical size and number of 10441 // elements. For floating point vectors, return an integer type of identical 10442 // size and number of elements. In the non ext_vector_type case, search from 10443 // the largest type to the smallest type to avoid cases where long long == long, 10444 // where long gets picked over long long. 10445 QualType Sema::GetSignedVectorType(QualType V) { 10446 const VectorType *VTy = V->getAs<VectorType>(); 10447 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 10448 10449 if (isa<ExtVectorType>(VTy)) { 10450 if (TypeSize == Context.getTypeSize(Context.CharTy)) 10451 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 10452 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10453 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 10454 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10455 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 10456 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10457 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 10458 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 10459 "Unhandled vector element size in vector compare"); 10460 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 10461 } 10462 10463 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 10464 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 10465 VectorType::GenericVector); 10466 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10467 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 10468 VectorType::GenericVector); 10469 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10470 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 10471 VectorType::GenericVector); 10472 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10473 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 10474 VectorType::GenericVector); 10475 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 10476 "Unhandled vector element size in vector compare"); 10477 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 10478 VectorType::GenericVector); 10479 } 10480 10481 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 10482 /// operates on extended vector types. Instead of producing an IntTy result, 10483 /// like a scalar comparison, a vector comparison produces a vector of integer 10484 /// types. 10485 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 10486 SourceLocation Loc, 10487 BinaryOperatorKind Opc) { 10488 // Check to make sure we're operating on vectors of the same type and width, 10489 // Allowing one side to be a scalar of element type. 10490 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 10491 /*AllowBothBool*/true, 10492 /*AllowBoolConversions*/getLangOpts().ZVector); 10493 if (vType.isNull()) 10494 return vType; 10495 10496 QualType LHSType = LHS.get()->getType(); 10497 10498 // If AltiVec, the comparison results in a numeric type, i.e. 10499 // bool for C++, int for C 10500 if (getLangOpts().AltiVec && 10501 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 10502 return Context.getLogicalOperationType(); 10503 10504 // For non-floating point types, check for self-comparisons of the form 10505 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10506 // often indicate logic errors in the program. 10507 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10508 10509 // Check for comparisons of floating point operands using != and ==. 10510 if (BinaryOperator::isEqualityOp(Opc) && 10511 LHSType->hasFloatingRepresentation()) { 10512 assert(RHS.get()->getType()->hasFloatingRepresentation()); 10513 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10514 } 10515 10516 // Return a signed type for the vector. 10517 return GetSignedVectorType(vType); 10518 } 10519 10520 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10521 SourceLocation Loc) { 10522 // Ensure that either both operands are of the same vector type, or 10523 // one operand is of a vector type and the other is of its element type. 10524 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 10525 /*AllowBothBool*/true, 10526 /*AllowBoolConversions*/false); 10527 if (vType.isNull()) 10528 return InvalidOperands(Loc, LHS, RHS); 10529 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 10530 vType->hasFloatingRepresentation()) 10531 return InvalidOperands(Loc, LHS, RHS); 10532 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 10533 // usage of the logical operators && and || with vectors in C. This 10534 // check could be notionally dropped. 10535 if (!getLangOpts().CPlusPlus && 10536 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 10537 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 10538 10539 return GetSignedVectorType(LHS.get()->getType()); 10540 } 10541 10542 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 10543 SourceLocation Loc, 10544 BinaryOperatorKind Opc) { 10545 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 10546 10547 bool IsCompAssign = 10548 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 10549 10550 if (LHS.get()->getType()->isVectorType() || 10551 RHS.get()->getType()->isVectorType()) { 10552 if (LHS.get()->getType()->hasIntegerRepresentation() && 10553 RHS.get()->getType()->hasIntegerRepresentation()) 10554 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10555 /*AllowBothBool*/true, 10556 /*AllowBoolConversions*/getLangOpts().ZVector); 10557 return InvalidOperands(Loc, LHS, RHS); 10558 } 10559 10560 if (Opc == BO_And) 10561 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10562 10563 ExprResult LHSResult = LHS, RHSResult = RHS; 10564 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 10565 IsCompAssign); 10566 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 10567 return QualType(); 10568 LHS = LHSResult.get(); 10569 RHS = RHSResult.get(); 10570 10571 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 10572 return compType; 10573 return InvalidOperands(Loc, LHS, RHS); 10574 } 10575 10576 // C99 6.5.[13,14] 10577 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10578 SourceLocation Loc, 10579 BinaryOperatorKind Opc) { 10580 // Check vector operands differently. 10581 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 10582 return CheckVectorLogicalOperands(LHS, RHS, Loc); 10583 10584 // Diagnose cases where the user write a logical and/or but probably meant a 10585 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 10586 // is a constant. 10587 if (LHS.get()->getType()->isIntegerType() && 10588 !LHS.get()->getType()->isBooleanType() && 10589 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 10590 // Don't warn in macros or template instantiations. 10591 !Loc.isMacroID() && !inTemplateInstantiation()) { 10592 // If the RHS can be constant folded, and if it constant folds to something 10593 // that isn't 0 or 1 (which indicate a potential logical operation that 10594 // happened to fold to true/false) then warn. 10595 // Parens on the RHS are ignored. 10596 llvm::APSInt Result; 10597 if (RHS.get()->EvaluateAsInt(Result, Context)) 10598 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 10599 !RHS.get()->getExprLoc().isMacroID()) || 10600 (Result != 0 && Result != 1)) { 10601 Diag(Loc, diag::warn_logical_instead_of_bitwise) 10602 << RHS.get()->getSourceRange() 10603 << (Opc == BO_LAnd ? "&&" : "||"); 10604 // Suggest replacing the logical operator with the bitwise version 10605 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 10606 << (Opc == BO_LAnd ? "&" : "|") 10607 << FixItHint::CreateReplacement(SourceRange( 10608 Loc, getLocForEndOfToken(Loc)), 10609 Opc == BO_LAnd ? "&" : "|"); 10610 if (Opc == BO_LAnd) 10611 // Suggest replacing "Foo() && kNonZero" with "Foo()" 10612 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 10613 << FixItHint::CreateRemoval( 10614 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 10615 RHS.get()->getEndLoc())); 10616 } 10617 } 10618 10619 if (!Context.getLangOpts().CPlusPlus) { 10620 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 10621 // not operate on the built-in scalar and vector float types. 10622 if (Context.getLangOpts().OpenCL && 10623 Context.getLangOpts().OpenCLVersion < 120) { 10624 if (LHS.get()->getType()->isFloatingType() || 10625 RHS.get()->getType()->isFloatingType()) 10626 return InvalidOperands(Loc, LHS, RHS); 10627 } 10628 10629 LHS = UsualUnaryConversions(LHS.get()); 10630 if (LHS.isInvalid()) 10631 return QualType(); 10632 10633 RHS = UsualUnaryConversions(RHS.get()); 10634 if (RHS.isInvalid()) 10635 return QualType(); 10636 10637 if (!LHS.get()->getType()->isScalarType() || 10638 !RHS.get()->getType()->isScalarType()) 10639 return InvalidOperands(Loc, LHS, RHS); 10640 10641 return Context.IntTy; 10642 } 10643 10644 // The following is safe because we only use this method for 10645 // non-overloadable operands. 10646 10647 // C++ [expr.log.and]p1 10648 // C++ [expr.log.or]p1 10649 // The operands are both contextually converted to type bool. 10650 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 10651 if (LHSRes.isInvalid()) 10652 return InvalidOperands(Loc, LHS, RHS); 10653 LHS = LHSRes; 10654 10655 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 10656 if (RHSRes.isInvalid()) 10657 return InvalidOperands(Loc, LHS, RHS); 10658 RHS = RHSRes; 10659 10660 // C++ [expr.log.and]p2 10661 // C++ [expr.log.or]p2 10662 // The result is a bool. 10663 return Context.BoolTy; 10664 } 10665 10666 static bool IsReadonlyMessage(Expr *E, Sema &S) { 10667 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 10668 if (!ME) return false; 10669 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 10670 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 10671 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 10672 if (!Base) return false; 10673 return Base->getMethodDecl() != nullptr; 10674 } 10675 10676 /// Is the given expression (which must be 'const') a reference to a 10677 /// variable which was originally non-const, but which has become 10678 /// 'const' due to being captured within a block? 10679 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 10680 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 10681 assert(E->isLValue() && E->getType().isConstQualified()); 10682 E = E->IgnoreParens(); 10683 10684 // Must be a reference to a declaration from an enclosing scope. 10685 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 10686 if (!DRE) return NCCK_None; 10687 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 10688 10689 // The declaration must be a variable which is not declared 'const'. 10690 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 10691 if (!var) return NCCK_None; 10692 if (var->getType().isConstQualified()) return NCCK_None; 10693 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 10694 10695 // Decide whether the first capture was for a block or a lambda. 10696 DeclContext *DC = S.CurContext, *Prev = nullptr; 10697 // Decide whether the first capture was for a block or a lambda. 10698 while (DC) { 10699 // For init-capture, it is possible that the variable belongs to the 10700 // template pattern of the current context. 10701 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 10702 if (var->isInitCapture() && 10703 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 10704 break; 10705 if (DC == var->getDeclContext()) 10706 break; 10707 Prev = DC; 10708 DC = DC->getParent(); 10709 } 10710 // Unless we have an init-capture, we've gone one step too far. 10711 if (!var->isInitCapture()) 10712 DC = Prev; 10713 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 10714 } 10715 10716 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 10717 Ty = Ty.getNonReferenceType(); 10718 if (IsDereference && Ty->isPointerType()) 10719 Ty = Ty->getPointeeType(); 10720 return !Ty.isConstQualified(); 10721 } 10722 10723 // Update err_typecheck_assign_const and note_typecheck_assign_const 10724 // when this enum is changed. 10725 enum { 10726 ConstFunction, 10727 ConstVariable, 10728 ConstMember, 10729 ConstMethod, 10730 NestedConstMember, 10731 ConstUnknown, // Keep as last element 10732 }; 10733 10734 /// Emit the "read-only variable not assignable" error and print notes to give 10735 /// more information about why the variable is not assignable, such as pointing 10736 /// to the declaration of a const variable, showing that a method is const, or 10737 /// that the function is returning a const reference. 10738 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 10739 SourceLocation Loc) { 10740 SourceRange ExprRange = E->getSourceRange(); 10741 10742 // Only emit one error on the first const found. All other consts will emit 10743 // a note to the error. 10744 bool DiagnosticEmitted = false; 10745 10746 // Track if the current expression is the result of a dereference, and if the 10747 // next checked expression is the result of a dereference. 10748 bool IsDereference = false; 10749 bool NextIsDereference = false; 10750 10751 // Loop to process MemberExpr chains. 10752 while (true) { 10753 IsDereference = NextIsDereference; 10754 10755 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 10756 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10757 NextIsDereference = ME->isArrow(); 10758 const ValueDecl *VD = ME->getMemberDecl(); 10759 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 10760 // Mutable fields can be modified even if the class is const. 10761 if (Field->isMutable()) { 10762 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 10763 break; 10764 } 10765 10766 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 10767 if (!DiagnosticEmitted) { 10768 S.Diag(Loc, diag::err_typecheck_assign_const) 10769 << ExprRange << ConstMember << false /*static*/ << Field 10770 << Field->getType(); 10771 DiagnosticEmitted = true; 10772 } 10773 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10774 << ConstMember << false /*static*/ << Field << Field->getType() 10775 << Field->getSourceRange(); 10776 } 10777 E = ME->getBase(); 10778 continue; 10779 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 10780 if (VDecl->getType().isConstQualified()) { 10781 if (!DiagnosticEmitted) { 10782 S.Diag(Loc, diag::err_typecheck_assign_const) 10783 << ExprRange << ConstMember << true /*static*/ << VDecl 10784 << VDecl->getType(); 10785 DiagnosticEmitted = true; 10786 } 10787 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10788 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 10789 << VDecl->getSourceRange(); 10790 } 10791 // Static fields do not inherit constness from parents. 10792 break; 10793 } 10794 break; // End MemberExpr 10795 } else if (const ArraySubscriptExpr *ASE = 10796 dyn_cast<ArraySubscriptExpr>(E)) { 10797 E = ASE->getBase()->IgnoreParenImpCasts(); 10798 continue; 10799 } else if (const ExtVectorElementExpr *EVE = 10800 dyn_cast<ExtVectorElementExpr>(E)) { 10801 E = EVE->getBase()->IgnoreParenImpCasts(); 10802 continue; 10803 } 10804 break; 10805 } 10806 10807 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10808 // Function calls 10809 const FunctionDecl *FD = CE->getDirectCallee(); 10810 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 10811 if (!DiagnosticEmitted) { 10812 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10813 << ConstFunction << FD; 10814 DiagnosticEmitted = true; 10815 } 10816 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 10817 diag::note_typecheck_assign_const) 10818 << ConstFunction << FD << FD->getReturnType() 10819 << FD->getReturnTypeSourceRange(); 10820 } 10821 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10822 // Point to variable declaration. 10823 if (const ValueDecl *VD = DRE->getDecl()) { 10824 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 10825 if (!DiagnosticEmitted) { 10826 S.Diag(Loc, diag::err_typecheck_assign_const) 10827 << ExprRange << ConstVariable << VD << VD->getType(); 10828 DiagnosticEmitted = true; 10829 } 10830 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10831 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 10832 } 10833 } 10834 } else if (isa<CXXThisExpr>(E)) { 10835 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 10836 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 10837 if (MD->isConst()) { 10838 if (!DiagnosticEmitted) { 10839 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 10840 << ConstMethod << MD; 10841 DiagnosticEmitted = true; 10842 } 10843 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 10844 << ConstMethod << MD << MD->getSourceRange(); 10845 } 10846 } 10847 } 10848 } 10849 10850 if (DiagnosticEmitted) 10851 return; 10852 10853 // Can't determine a more specific message, so display the generic error. 10854 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 10855 } 10856 10857 enum OriginalExprKind { 10858 OEK_Variable, 10859 OEK_Member, 10860 OEK_LValue 10861 }; 10862 10863 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 10864 const RecordType *Ty, 10865 SourceLocation Loc, SourceRange Range, 10866 OriginalExprKind OEK, 10867 bool &DiagnosticEmitted, 10868 bool IsNested = false) { 10869 // We walk the record hierarchy breadth-first to ensure that we print 10870 // diagnostics in field nesting order. 10871 // First, check every field for constness. 10872 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10873 if (Field->getType().isConstQualified()) { 10874 if (!DiagnosticEmitted) { 10875 S.Diag(Loc, diag::err_typecheck_assign_const) 10876 << Range << NestedConstMember << OEK << VD 10877 << IsNested << Field; 10878 DiagnosticEmitted = true; 10879 } 10880 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 10881 << NestedConstMember << IsNested << Field 10882 << Field->getType() << Field->getSourceRange(); 10883 } 10884 } 10885 // Then, recurse. 10886 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 10887 QualType FTy = Field->getType(); 10888 if (const RecordType *FieldRecTy = FTy->getAs<RecordType>()) 10889 DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range, 10890 OEK, DiagnosticEmitted, true); 10891 } 10892 } 10893 10894 /// Emit an error for the case where a record we are trying to assign to has a 10895 /// const-qualified field somewhere in its hierarchy. 10896 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 10897 SourceLocation Loc) { 10898 QualType Ty = E->getType(); 10899 assert(Ty->isRecordType() && "lvalue was not record?"); 10900 SourceRange Range = E->getSourceRange(); 10901 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 10902 bool DiagEmitted = false; 10903 10904 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 10905 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 10906 Range, OEK_Member, DiagEmitted); 10907 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 10908 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 10909 Range, OEK_Variable, DiagEmitted); 10910 else 10911 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 10912 Range, OEK_LValue, DiagEmitted); 10913 if (!DiagEmitted) 10914 DiagnoseConstAssignment(S, E, Loc); 10915 } 10916 10917 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 10918 /// emit an error and return true. If so, return false. 10919 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 10920 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 10921 10922 S.CheckShadowingDeclModification(E, Loc); 10923 10924 SourceLocation OrigLoc = Loc; 10925 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 10926 &Loc); 10927 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 10928 IsLV = Expr::MLV_InvalidMessageExpression; 10929 if (IsLV == Expr::MLV_Valid) 10930 return false; 10931 10932 unsigned DiagID = 0; 10933 bool NeedType = false; 10934 switch (IsLV) { // C99 6.5.16p2 10935 case Expr::MLV_ConstQualified: 10936 // Use a specialized diagnostic when we're assigning to an object 10937 // from an enclosing function or block. 10938 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 10939 if (NCCK == NCCK_Block) 10940 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 10941 else 10942 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 10943 break; 10944 } 10945 10946 // In ARC, use some specialized diagnostics for occasions where we 10947 // infer 'const'. These are always pseudo-strong variables. 10948 if (S.getLangOpts().ObjCAutoRefCount) { 10949 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 10950 if (declRef && isa<VarDecl>(declRef->getDecl())) { 10951 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 10952 10953 // Use the normal diagnostic if it's pseudo-__strong but the 10954 // user actually wrote 'const'. 10955 if (var->isARCPseudoStrong() && 10956 (!var->getTypeSourceInfo() || 10957 !var->getTypeSourceInfo()->getType().isConstQualified())) { 10958 // There are two pseudo-strong cases: 10959 // - self 10960 ObjCMethodDecl *method = S.getCurMethodDecl(); 10961 if (method && var == method->getSelfDecl()) 10962 DiagID = method->isClassMethod() 10963 ? diag::err_typecheck_arc_assign_self_class_method 10964 : diag::err_typecheck_arc_assign_self; 10965 10966 // - fast enumeration variables 10967 else 10968 DiagID = diag::err_typecheck_arr_assign_enumeration; 10969 10970 SourceRange Assign; 10971 if (Loc != OrigLoc) 10972 Assign = SourceRange(OrigLoc, OrigLoc); 10973 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 10974 // We need to preserve the AST regardless, so migration tool 10975 // can do its job. 10976 return false; 10977 } 10978 } 10979 } 10980 10981 // If none of the special cases above are triggered, then this is a 10982 // simple const assignment. 10983 if (DiagID == 0) { 10984 DiagnoseConstAssignment(S, E, Loc); 10985 return true; 10986 } 10987 10988 break; 10989 case Expr::MLV_ConstAddrSpace: 10990 DiagnoseConstAssignment(S, E, Loc); 10991 return true; 10992 case Expr::MLV_ConstQualifiedField: 10993 DiagnoseRecursiveConstFields(S, E, Loc); 10994 return true; 10995 case Expr::MLV_ArrayType: 10996 case Expr::MLV_ArrayTemporary: 10997 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 10998 NeedType = true; 10999 break; 11000 case Expr::MLV_NotObjectType: 11001 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 11002 NeedType = true; 11003 break; 11004 case Expr::MLV_LValueCast: 11005 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 11006 break; 11007 case Expr::MLV_Valid: 11008 llvm_unreachable("did not take early return for MLV_Valid"); 11009 case Expr::MLV_InvalidExpression: 11010 case Expr::MLV_MemberFunction: 11011 case Expr::MLV_ClassTemporary: 11012 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 11013 break; 11014 case Expr::MLV_IncompleteType: 11015 case Expr::MLV_IncompleteVoidType: 11016 return S.RequireCompleteType(Loc, E->getType(), 11017 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 11018 case Expr::MLV_DuplicateVectorComponents: 11019 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 11020 break; 11021 case Expr::MLV_NoSetterProperty: 11022 llvm_unreachable("readonly properties should be processed differently"); 11023 case Expr::MLV_InvalidMessageExpression: 11024 DiagID = diag::err_readonly_message_assignment; 11025 break; 11026 case Expr::MLV_SubObjCPropertySetting: 11027 DiagID = diag::err_no_subobject_property_setting; 11028 break; 11029 } 11030 11031 SourceRange Assign; 11032 if (Loc != OrigLoc) 11033 Assign = SourceRange(OrigLoc, OrigLoc); 11034 if (NeedType) 11035 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 11036 else 11037 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11038 return true; 11039 } 11040 11041 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 11042 SourceLocation Loc, 11043 Sema &Sema) { 11044 if (Sema.inTemplateInstantiation()) 11045 return; 11046 if (Sema.isUnevaluatedContext()) 11047 return; 11048 if (Loc.isInvalid() || Loc.isMacroID()) 11049 return; 11050 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 11051 return; 11052 11053 // C / C++ fields 11054 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 11055 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 11056 if (ML && MR) { 11057 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 11058 return; 11059 const ValueDecl *LHSDecl = 11060 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 11061 const ValueDecl *RHSDecl = 11062 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 11063 if (LHSDecl != RHSDecl) 11064 return; 11065 if (LHSDecl->getType().isVolatileQualified()) 11066 return; 11067 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11068 if (RefTy->getPointeeType().isVolatileQualified()) 11069 return; 11070 11071 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 11072 } 11073 11074 // Objective-C instance variables 11075 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 11076 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 11077 if (OL && OR && OL->getDecl() == OR->getDecl()) { 11078 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 11079 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 11080 if (RL && RR && RL->getDecl() == RR->getDecl()) 11081 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 11082 } 11083 } 11084 11085 // C99 6.5.16.1 11086 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 11087 SourceLocation Loc, 11088 QualType CompoundType) { 11089 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 11090 11091 // Verify that LHS is a modifiable lvalue, and emit error if not. 11092 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 11093 return QualType(); 11094 11095 QualType LHSType = LHSExpr->getType(); 11096 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 11097 CompoundType; 11098 // OpenCL v1.2 s6.1.1.1 p2: 11099 // The half data type can only be used to declare a pointer to a buffer that 11100 // contains half values 11101 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 11102 LHSType->isHalfType()) { 11103 Diag(Loc, diag::err_opencl_half_load_store) << 1 11104 << LHSType.getUnqualifiedType(); 11105 return QualType(); 11106 } 11107 11108 AssignConvertType ConvTy; 11109 if (CompoundType.isNull()) { 11110 Expr *RHSCheck = RHS.get(); 11111 11112 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 11113 11114 QualType LHSTy(LHSType); 11115 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 11116 if (RHS.isInvalid()) 11117 return QualType(); 11118 // Special case of NSObject attributes on c-style pointer types. 11119 if (ConvTy == IncompatiblePointer && 11120 ((Context.isObjCNSObjectType(LHSType) && 11121 RHSType->isObjCObjectPointerType()) || 11122 (Context.isObjCNSObjectType(RHSType) && 11123 LHSType->isObjCObjectPointerType()))) 11124 ConvTy = Compatible; 11125 11126 if (ConvTy == Compatible && 11127 LHSType->isObjCObjectType()) 11128 Diag(Loc, diag::err_objc_object_assignment) 11129 << LHSType; 11130 11131 // If the RHS is a unary plus or minus, check to see if they = and + are 11132 // right next to each other. If so, the user may have typo'd "x =+ 4" 11133 // instead of "x += 4". 11134 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 11135 RHSCheck = ICE->getSubExpr(); 11136 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 11137 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 11138 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 11139 // Only if the two operators are exactly adjacent. 11140 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 11141 // And there is a space or other character before the subexpr of the 11142 // unary +/-. We don't want to warn on "x=-1". 11143 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 11144 UO->getSubExpr()->getBeginLoc().isFileID()) { 11145 Diag(Loc, diag::warn_not_compound_assign) 11146 << (UO->getOpcode() == UO_Plus ? "+" : "-") 11147 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 11148 } 11149 } 11150 11151 if (ConvTy == Compatible) { 11152 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 11153 // Warn about retain cycles where a block captures the LHS, but 11154 // not if the LHS is a simple variable into which the block is 11155 // being stored...unless that variable can be captured by reference! 11156 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 11157 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 11158 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 11159 checkRetainCycles(LHSExpr, RHS.get()); 11160 } 11161 11162 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 11163 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 11164 // It is safe to assign a weak reference into a strong variable. 11165 // Although this code can still have problems: 11166 // id x = self.weakProp; 11167 // id y = self.weakProp; 11168 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11169 // paths through the function. This should be revisited if 11170 // -Wrepeated-use-of-weak is made flow-sensitive. 11171 // For ObjCWeak only, we do not warn if the assign is to a non-weak 11172 // variable, which will be valid for the current autorelease scope. 11173 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11174 RHS.get()->getBeginLoc())) 11175 getCurFunction()->markSafeWeakUse(RHS.get()); 11176 11177 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 11178 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 11179 } 11180 } 11181 } else { 11182 // Compound assignment "x += y" 11183 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 11184 } 11185 11186 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 11187 RHS.get(), AA_Assigning)) 11188 return QualType(); 11189 11190 CheckForNullPointerDereference(*this, LHSExpr); 11191 11192 // C99 6.5.16p3: The type of an assignment expression is the type of the 11193 // left operand unless the left operand has qualified type, in which case 11194 // it is the unqualified version of the type of the left operand. 11195 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 11196 // is converted to the type of the assignment expression (above). 11197 // C++ 5.17p1: the type of the assignment expression is that of its left 11198 // operand. 11199 return (getLangOpts().CPlusPlus 11200 ? LHSType : LHSType.getUnqualifiedType()); 11201 } 11202 11203 // Only ignore explicit casts to void. 11204 static bool IgnoreCommaOperand(const Expr *E) { 11205 E = E->IgnoreParens(); 11206 11207 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 11208 if (CE->getCastKind() == CK_ToVoid) { 11209 return true; 11210 } 11211 } 11212 11213 return false; 11214 } 11215 11216 // Look for instances where it is likely the comma operator is confused with 11217 // another operator. There is a whitelist of acceptable expressions for the 11218 // left hand side of the comma operator, otherwise emit a warning. 11219 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 11220 // No warnings in macros 11221 if (Loc.isMacroID()) 11222 return; 11223 11224 // Don't warn in template instantiations. 11225 if (inTemplateInstantiation()) 11226 return; 11227 11228 // Scope isn't fine-grained enough to whitelist the specific cases, so 11229 // instead, skip more than needed, then call back into here with the 11230 // CommaVisitor in SemaStmt.cpp. 11231 // The whitelisted locations are the initialization and increment portions 11232 // of a for loop. The additional checks are on the condition of 11233 // if statements, do/while loops, and for loops. 11234 const unsigned ForIncrementFlags = 11235 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope; 11236 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 11237 const unsigned ScopeFlags = getCurScope()->getFlags(); 11238 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 11239 (ScopeFlags & ForInitFlags) == ForInitFlags) 11240 return; 11241 11242 // If there are multiple comma operators used together, get the RHS of the 11243 // of the comma operator as the LHS. 11244 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 11245 if (BO->getOpcode() != BO_Comma) 11246 break; 11247 LHS = BO->getRHS(); 11248 } 11249 11250 // Only allow some expressions on LHS to not warn. 11251 if (IgnoreCommaOperand(LHS)) 11252 return; 11253 11254 Diag(Loc, diag::warn_comma_operator); 11255 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 11256 << LHS->getSourceRange() 11257 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 11258 LangOpts.CPlusPlus ? "static_cast<void>(" 11259 : "(void)(") 11260 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 11261 ")"); 11262 } 11263 11264 // C99 6.5.17 11265 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 11266 SourceLocation Loc) { 11267 LHS = S.CheckPlaceholderExpr(LHS.get()); 11268 RHS = S.CheckPlaceholderExpr(RHS.get()); 11269 if (LHS.isInvalid() || RHS.isInvalid()) 11270 return QualType(); 11271 11272 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 11273 // operands, but not unary promotions. 11274 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 11275 11276 // So we treat the LHS as a ignored value, and in C++ we allow the 11277 // containing site to determine what should be done with the RHS. 11278 LHS = S.IgnoredValueConversions(LHS.get()); 11279 if (LHS.isInvalid()) 11280 return QualType(); 11281 11282 S.DiagnoseUnusedExprResult(LHS.get()); 11283 11284 if (!S.getLangOpts().CPlusPlus) { 11285 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 11286 if (RHS.isInvalid()) 11287 return QualType(); 11288 if (!RHS.get()->getType()->isVoidType()) 11289 S.RequireCompleteType(Loc, RHS.get()->getType(), 11290 diag::err_incomplete_type); 11291 } 11292 11293 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 11294 S.DiagnoseCommaOperator(LHS.get(), Loc); 11295 11296 return RHS.get()->getType(); 11297 } 11298 11299 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 11300 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 11301 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 11302 ExprValueKind &VK, 11303 ExprObjectKind &OK, 11304 SourceLocation OpLoc, 11305 bool IsInc, bool IsPrefix) { 11306 if (Op->isTypeDependent()) 11307 return S.Context.DependentTy; 11308 11309 QualType ResType = Op->getType(); 11310 // Atomic types can be used for increment / decrement where the non-atomic 11311 // versions can, so ignore the _Atomic() specifier for the purpose of 11312 // checking. 11313 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 11314 ResType = ResAtomicType->getValueType(); 11315 11316 assert(!ResType.isNull() && "no type for increment/decrement expression"); 11317 11318 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 11319 // Decrement of bool is not allowed. 11320 if (!IsInc) { 11321 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 11322 return QualType(); 11323 } 11324 // Increment of bool sets it to true, but is deprecated. 11325 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 11326 : diag::warn_increment_bool) 11327 << Op->getSourceRange(); 11328 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 11329 // Error on enum increments and decrements in C++ mode 11330 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 11331 return QualType(); 11332 } else if (ResType->isRealType()) { 11333 // OK! 11334 } else if (ResType->isPointerType()) { 11335 // C99 6.5.2.4p2, 6.5.6p2 11336 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 11337 return QualType(); 11338 } else if (ResType->isObjCObjectPointerType()) { 11339 // On modern runtimes, ObjC pointer arithmetic is forbidden. 11340 // Otherwise, we just need a complete type. 11341 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 11342 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 11343 return QualType(); 11344 } else if (ResType->isAnyComplexType()) { 11345 // C99 does not support ++/-- on complex types, we allow as an extension. 11346 S.Diag(OpLoc, diag::ext_integer_increment_complex) 11347 << ResType << Op->getSourceRange(); 11348 } else if (ResType->isPlaceholderType()) { 11349 ExprResult PR = S.CheckPlaceholderExpr(Op); 11350 if (PR.isInvalid()) return QualType(); 11351 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 11352 IsInc, IsPrefix); 11353 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 11354 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 11355 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 11356 (ResType->getAs<VectorType>()->getVectorKind() != 11357 VectorType::AltiVecBool)) { 11358 // The z vector extensions allow ++ and -- for non-bool vectors. 11359 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 11360 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 11361 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 11362 } else { 11363 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 11364 << ResType << int(IsInc) << Op->getSourceRange(); 11365 return QualType(); 11366 } 11367 // At this point, we know we have a real, complex or pointer type. 11368 // Now make sure the operand is a modifiable lvalue. 11369 if (CheckForModifiableLvalue(Op, OpLoc, S)) 11370 return QualType(); 11371 // In C++, a prefix increment is the same type as the operand. Otherwise 11372 // (in C or with postfix), the increment is the unqualified type of the 11373 // operand. 11374 if (IsPrefix && S.getLangOpts().CPlusPlus) { 11375 VK = VK_LValue; 11376 OK = Op->getObjectKind(); 11377 return ResType; 11378 } else { 11379 VK = VK_RValue; 11380 return ResType.getUnqualifiedType(); 11381 } 11382 } 11383 11384 11385 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 11386 /// This routine allows us to typecheck complex/recursive expressions 11387 /// where the declaration is needed for type checking. We only need to 11388 /// handle cases when the expression references a function designator 11389 /// or is an lvalue. Here are some examples: 11390 /// - &(x) => x 11391 /// - &*****f => f for f a function designator. 11392 /// - &s.xx => s 11393 /// - &s.zz[1].yy -> s, if zz is an array 11394 /// - *(x + 1) -> x, if x is an array 11395 /// - &"123"[2] -> 0 11396 /// - & __real__ x -> x 11397 static ValueDecl *getPrimaryDecl(Expr *E) { 11398 switch (E->getStmtClass()) { 11399 case Stmt::DeclRefExprClass: 11400 return cast<DeclRefExpr>(E)->getDecl(); 11401 case Stmt::MemberExprClass: 11402 // If this is an arrow operator, the address is an offset from 11403 // the base's value, so the object the base refers to is 11404 // irrelevant. 11405 if (cast<MemberExpr>(E)->isArrow()) 11406 return nullptr; 11407 // Otherwise, the expression refers to a part of the base 11408 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 11409 case Stmt::ArraySubscriptExprClass: { 11410 // FIXME: This code shouldn't be necessary! We should catch the implicit 11411 // promotion of register arrays earlier. 11412 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 11413 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 11414 if (ICE->getSubExpr()->getType()->isArrayType()) 11415 return getPrimaryDecl(ICE->getSubExpr()); 11416 } 11417 return nullptr; 11418 } 11419 case Stmt::UnaryOperatorClass: { 11420 UnaryOperator *UO = cast<UnaryOperator>(E); 11421 11422 switch(UO->getOpcode()) { 11423 case UO_Real: 11424 case UO_Imag: 11425 case UO_Extension: 11426 return getPrimaryDecl(UO->getSubExpr()); 11427 default: 11428 return nullptr; 11429 } 11430 } 11431 case Stmt::ParenExprClass: 11432 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 11433 case Stmt::ImplicitCastExprClass: 11434 // If the result of an implicit cast is an l-value, we care about 11435 // the sub-expression; otherwise, the result here doesn't matter. 11436 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 11437 default: 11438 return nullptr; 11439 } 11440 } 11441 11442 namespace { 11443 enum { 11444 AO_Bit_Field = 0, 11445 AO_Vector_Element = 1, 11446 AO_Property_Expansion = 2, 11447 AO_Register_Variable = 3, 11448 AO_No_Error = 4 11449 }; 11450 } 11451 /// Diagnose invalid operand for address of operations. 11452 /// 11453 /// \param Type The type of operand which cannot have its address taken. 11454 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 11455 Expr *E, unsigned Type) { 11456 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 11457 } 11458 11459 /// CheckAddressOfOperand - The operand of & must be either a function 11460 /// designator or an lvalue designating an object. If it is an lvalue, the 11461 /// object cannot be declared with storage class register or be a bit field. 11462 /// Note: The usual conversions are *not* applied to the operand of the & 11463 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 11464 /// In C++, the operand might be an overloaded function name, in which case 11465 /// we allow the '&' but retain the overloaded-function type. 11466 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 11467 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 11468 if (PTy->getKind() == BuiltinType::Overload) { 11469 Expr *E = OrigOp.get()->IgnoreParens(); 11470 if (!isa<OverloadExpr>(E)) { 11471 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 11472 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 11473 << OrigOp.get()->getSourceRange(); 11474 return QualType(); 11475 } 11476 11477 OverloadExpr *Ovl = cast<OverloadExpr>(E); 11478 if (isa<UnresolvedMemberExpr>(Ovl)) 11479 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 11480 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11481 << OrigOp.get()->getSourceRange(); 11482 return QualType(); 11483 } 11484 11485 return Context.OverloadTy; 11486 } 11487 11488 if (PTy->getKind() == BuiltinType::UnknownAny) 11489 return Context.UnknownAnyTy; 11490 11491 if (PTy->getKind() == BuiltinType::BoundMember) { 11492 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11493 << OrigOp.get()->getSourceRange(); 11494 return QualType(); 11495 } 11496 11497 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 11498 if (OrigOp.isInvalid()) return QualType(); 11499 } 11500 11501 if (OrigOp.get()->isTypeDependent()) 11502 return Context.DependentTy; 11503 11504 assert(!OrigOp.get()->getType()->isPlaceholderType()); 11505 11506 // Make sure to ignore parentheses in subsequent checks 11507 Expr *op = OrigOp.get()->IgnoreParens(); 11508 11509 // In OpenCL captures for blocks called as lambda functions 11510 // are located in the private address space. Blocks used in 11511 // enqueue_kernel can be located in a different address space 11512 // depending on a vendor implementation. Thus preventing 11513 // taking an address of the capture to avoid invalid AS casts. 11514 if (LangOpts.OpenCL) { 11515 auto* VarRef = dyn_cast<DeclRefExpr>(op); 11516 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 11517 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 11518 return QualType(); 11519 } 11520 } 11521 11522 if (getLangOpts().C99) { 11523 // Implement C99-only parts of addressof rules. 11524 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 11525 if (uOp->getOpcode() == UO_Deref) 11526 // Per C99 6.5.3.2, the address of a deref always returns a valid result 11527 // (assuming the deref expression is valid). 11528 return uOp->getSubExpr()->getType(); 11529 } 11530 // Technically, there should be a check for array subscript 11531 // expressions here, but the result of one is always an lvalue anyway. 11532 } 11533 ValueDecl *dcl = getPrimaryDecl(op); 11534 11535 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 11536 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11537 op->getBeginLoc())) 11538 return QualType(); 11539 11540 Expr::LValueClassification lval = op->ClassifyLValue(Context); 11541 unsigned AddressOfError = AO_No_Error; 11542 11543 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 11544 bool sfinae = (bool)isSFINAEContext(); 11545 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 11546 : diag::ext_typecheck_addrof_temporary) 11547 << op->getType() << op->getSourceRange(); 11548 if (sfinae) 11549 return QualType(); 11550 // Materialize the temporary as an lvalue so that we can take its address. 11551 OrigOp = op = 11552 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 11553 } else if (isa<ObjCSelectorExpr>(op)) { 11554 return Context.getPointerType(op->getType()); 11555 } else if (lval == Expr::LV_MemberFunction) { 11556 // If it's an instance method, make a member pointer. 11557 // The expression must have exactly the form &A::foo. 11558 11559 // If the underlying expression isn't a decl ref, give up. 11560 if (!isa<DeclRefExpr>(op)) { 11561 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11562 << OrigOp.get()->getSourceRange(); 11563 return QualType(); 11564 } 11565 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 11566 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 11567 11568 // The id-expression was parenthesized. 11569 if (OrigOp.get() != DRE) { 11570 Diag(OpLoc, diag::err_parens_pointer_member_function) 11571 << OrigOp.get()->getSourceRange(); 11572 11573 // The method was named without a qualifier. 11574 } else if (!DRE->getQualifier()) { 11575 if (MD->getParent()->getName().empty()) 11576 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11577 << op->getSourceRange(); 11578 else { 11579 SmallString<32> Str; 11580 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 11581 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11582 << op->getSourceRange() 11583 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 11584 } 11585 } 11586 11587 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 11588 if (isa<CXXDestructorDecl>(MD)) 11589 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 11590 11591 QualType MPTy = Context.getMemberPointerType( 11592 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 11593 // Under the MS ABI, lock down the inheritance model now. 11594 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11595 (void)isCompleteType(OpLoc, MPTy); 11596 return MPTy; 11597 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 11598 // C99 6.5.3.2p1 11599 // The operand must be either an l-value or a function designator 11600 if (!op->getType()->isFunctionType()) { 11601 // Use a special diagnostic for loads from property references. 11602 if (isa<PseudoObjectExpr>(op)) { 11603 AddressOfError = AO_Property_Expansion; 11604 } else { 11605 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 11606 << op->getType() << op->getSourceRange(); 11607 return QualType(); 11608 } 11609 } 11610 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 11611 // The operand cannot be a bit-field 11612 AddressOfError = AO_Bit_Field; 11613 } else if (op->getObjectKind() == OK_VectorComponent) { 11614 // The operand cannot be an element of a vector 11615 AddressOfError = AO_Vector_Element; 11616 } else if (dcl) { // C99 6.5.3.2p1 11617 // We have an lvalue with a decl. Make sure the decl is not declared 11618 // with the register storage-class specifier. 11619 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 11620 // in C++ it is not error to take address of a register 11621 // variable (c++03 7.1.1P3) 11622 if (vd->getStorageClass() == SC_Register && 11623 !getLangOpts().CPlusPlus) { 11624 AddressOfError = AO_Register_Variable; 11625 } 11626 } else if (isa<MSPropertyDecl>(dcl)) { 11627 AddressOfError = AO_Property_Expansion; 11628 } else if (isa<FunctionTemplateDecl>(dcl)) { 11629 return Context.OverloadTy; 11630 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 11631 // Okay: we can take the address of a field. 11632 // Could be a pointer to member, though, if there is an explicit 11633 // scope qualifier for the class. 11634 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 11635 DeclContext *Ctx = dcl->getDeclContext(); 11636 if (Ctx && Ctx->isRecord()) { 11637 if (dcl->getType()->isReferenceType()) { 11638 Diag(OpLoc, 11639 diag::err_cannot_form_pointer_to_member_of_reference_type) 11640 << dcl->getDeclName() << dcl->getType(); 11641 return QualType(); 11642 } 11643 11644 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 11645 Ctx = Ctx->getParent(); 11646 11647 QualType MPTy = Context.getMemberPointerType( 11648 op->getType(), 11649 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 11650 // Under the MS ABI, lock down the inheritance model now. 11651 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11652 (void)isCompleteType(OpLoc, MPTy); 11653 return MPTy; 11654 } 11655 } 11656 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 11657 !isa<BindingDecl>(dcl)) 11658 llvm_unreachable("Unknown/unexpected decl type"); 11659 } 11660 11661 if (AddressOfError != AO_No_Error) { 11662 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 11663 return QualType(); 11664 } 11665 11666 if (lval == Expr::LV_IncompleteVoidType) { 11667 // Taking the address of a void variable is technically illegal, but we 11668 // allow it in cases which are otherwise valid. 11669 // Example: "extern void x; void* y = &x;". 11670 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 11671 } 11672 11673 // If the operand has type "type", the result has type "pointer to type". 11674 if (op->getType()->isObjCObjectType()) 11675 return Context.getObjCObjectPointerType(op->getType()); 11676 11677 CheckAddressOfPackedMember(op); 11678 11679 return Context.getPointerType(op->getType()); 11680 } 11681 11682 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 11683 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 11684 if (!DRE) 11685 return; 11686 const Decl *D = DRE->getDecl(); 11687 if (!D) 11688 return; 11689 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 11690 if (!Param) 11691 return; 11692 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 11693 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 11694 return; 11695 if (FunctionScopeInfo *FD = S.getCurFunction()) 11696 if (!FD->ModifiedNonNullParams.count(Param)) 11697 FD->ModifiedNonNullParams.insert(Param); 11698 } 11699 11700 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 11701 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 11702 SourceLocation OpLoc) { 11703 if (Op->isTypeDependent()) 11704 return S.Context.DependentTy; 11705 11706 ExprResult ConvResult = S.UsualUnaryConversions(Op); 11707 if (ConvResult.isInvalid()) 11708 return QualType(); 11709 Op = ConvResult.get(); 11710 QualType OpTy = Op->getType(); 11711 QualType Result; 11712 11713 if (isa<CXXReinterpretCastExpr>(Op)) { 11714 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 11715 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 11716 Op->getSourceRange()); 11717 } 11718 11719 if (const PointerType *PT = OpTy->getAs<PointerType>()) 11720 { 11721 Result = PT->getPointeeType(); 11722 } 11723 else if (const ObjCObjectPointerType *OPT = 11724 OpTy->getAs<ObjCObjectPointerType>()) 11725 Result = OPT->getPointeeType(); 11726 else { 11727 ExprResult PR = S.CheckPlaceholderExpr(Op); 11728 if (PR.isInvalid()) return QualType(); 11729 if (PR.get() != Op) 11730 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 11731 } 11732 11733 if (Result.isNull()) { 11734 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 11735 << OpTy << Op->getSourceRange(); 11736 return QualType(); 11737 } 11738 11739 // Note that per both C89 and C99, indirection is always legal, even if Result 11740 // is an incomplete type or void. It would be possible to warn about 11741 // dereferencing a void pointer, but it's completely well-defined, and such a 11742 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 11743 // for pointers to 'void' but is fine for any other pointer type: 11744 // 11745 // C++ [expr.unary.op]p1: 11746 // [...] the expression to which [the unary * operator] is applied shall 11747 // be a pointer to an object type, or a pointer to a function type 11748 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 11749 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 11750 << OpTy << Op->getSourceRange(); 11751 11752 // Dereferences are usually l-values... 11753 VK = VK_LValue; 11754 11755 // ...except that certain expressions are never l-values in C. 11756 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 11757 VK = VK_RValue; 11758 11759 return Result; 11760 } 11761 11762 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 11763 BinaryOperatorKind Opc; 11764 switch (Kind) { 11765 default: llvm_unreachable("Unknown binop!"); 11766 case tok::periodstar: Opc = BO_PtrMemD; break; 11767 case tok::arrowstar: Opc = BO_PtrMemI; break; 11768 case tok::star: Opc = BO_Mul; break; 11769 case tok::slash: Opc = BO_Div; break; 11770 case tok::percent: Opc = BO_Rem; break; 11771 case tok::plus: Opc = BO_Add; break; 11772 case tok::minus: Opc = BO_Sub; break; 11773 case tok::lessless: Opc = BO_Shl; break; 11774 case tok::greatergreater: Opc = BO_Shr; break; 11775 case tok::lessequal: Opc = BO_LE; break; 11776 case tok::less: Opc = BO_LT; break; 11777 case tok::greaterequal: Opc = BO_GE; break; 11778 case tok::greater: Opc = BO_GT; break; 11779 case tok::exclaimequal: Opc = BO_NE; break; 11780 case tok::equalequal: Opc = BO_EQ; break; 11781 case tok::spaceship: Opc = BO_Cmp; break; 11782 case tok::amp: Opc = BO_And; break; 11783 case tok::caret: Opc = BO_Xor; break; 11784 case tok::pipe: Opc = BO_Or; break; 11785 case tok::ampamp: Opc = BO_LAnd; break; 11786 case tok::pipepipe: Opc = BO_LOr; break; 11787 case tok::equal: Opc = BO_Assign; break; 11788 case tok::starequal: Opc = BO_MulAssign; break; 11789 case tok::slashequal: Opc = BO_DivAssign; break; 11790 case tok::percentequal: Opc = BO_RemAssign; break; 11791 case tok::plusequal: Opc = BO_AddAssign; break; 11792 case tok::minusequal: Opc = BO_SubAssign; break; 11793 case tok::lesslessequal: Opc = BO_ShlAssign; break; 11794 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 11795 case tok::ampequal: Opc = BO_AndAssign; break; 11796 case tok::caretequal: Opc = BO_XorAssign; break; 11797 case tok::pipeequal: Opc = BO_OrAssign; break; 11798 case tok::comma: Opc = BO_Comma; break; 11799 } 11800 return Opc; 11801 } 11802 11803 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 11804 tok::TokenKind Kind) { 11805 UnaryOperatorKind Opc; 11806 switch (Kind) { 11807 default: llvm_unreachable("Unknown unary op!"); 11808 case tok::plusplus: Opc = UO_PreInc; break; 11809 case tok::minusminus: Opc = UO_PreDec; break; 11810 case tok::amp: Opc = UO_AddrOf; break; 11811 case tok::star: Opc = UO_Deref; break; 11812 case tok::plus: Opc = UO_Plus; break; 11813 case tok::minus: Opc = UO_Minus; break; 11814 case tok::tilde: Opc = UO_Not; break; 11815 case tok::exclaim: Opc = UO_LNot; break; 11816 case tok::kw___real: Opc = UO_Real; break; 11817 case tok::kw___imag: Opc = UO_Imag; break; 11818 case tok::kw___extension__: Opc = UO_Extension; break; 11819 } 11820 return Opc; 11821 } 11822 11823 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 11824 /// This warning suppressed in the event of macro expansions. 11825 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 11826 SourceLocation OpLoc, bool IsBuiltin) { 11827 if (S.inTemplateInstantiation()) 11828 return; 11829 if (S.isUnevaluatedContext()) 11830 return; 11831 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 11832 return; 11833 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 11834 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 11835 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 11836 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 11837 if (!LHSDeclRef || !RHSDeclRef || 11838 LHSDeclRef->getLocation().isMacroID() || 11839 RHSDeclRef->getLocation().isMacroID()) 11840 return; 11841 const ValueDecl *LHSDecl = 11842 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 11843 const ValueDecl *RHSDecl = 11844 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 11845 if (LHSDecl != RHSDecl) 11846 return; 11847 if (LHSDecl->getType().isVolatileQualified()) 11848 return; 11849 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11850 if (RefTy->getPointeeType().isVolatileQualified()) 11851 return; 11852 11853 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 11854 : diag::warn_self_assignment_overloaded) 11855 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 11856 << RHSExpr->getSourceRange(); 11857 } 11858 11859 /// Check if a bitwise-& is performed on an Objective-C pointer. This 11860 /// is usually indicative of introspection within the Objective-C pointer. 11861 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 11862 SourceLocation OpLoc) { 11863 if (!S.getLangOpts().ObjC1) 11864 return; 11865 11866 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 11867 const Expr *LHS = L.get(); 11868 const Expr *RHS = R.get(); 11869 11870 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11871 ObjCPointerExpr = LHS; 11872 OtherExpr = RHS; 11873 } 11874 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 11875 ObjCPointerExpr = RHS; 11876 OtherExpr = LHS; 11877 } 11878 11879 // This warning is deliberately made very specific to reduce false 11880 // positives with logic that uses '&' for hashing. This logic mainly 11881 // looks for code trying to introspect into tagged pointers, which 11882 // code should generally never do. 11883 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 11884 unsigned Diag = diag::warn_objc_pointer_masking; 11885 // Determine if we are introspecting the result of performSelectorXXX. 11886 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 11887 // Special case messages to -performSelector and friends, which 11888 // can return non-pointer values boxed in a pointer value. 11889 // Some clients may wish to silence warnings in this subcase. 11890 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 11891 Selector S = ME->getSelector(); 11892 StringRef SelArg0 = S.getNameForSlot(0); 11893 if (SelArg0.startswith("performSelector")) 11894 Diag = diag::warn_objc_pointer_masking_performSelector; 11895 } 11896 11897 S.Diag(OpLoc, Diag) 11898 << ObjCPointerExpr->getSourceRange(); 11899 } 11900 } 11901 11902 static NamedDecl *getDeclFromExpr(Expr *E) { 11903 if (!E) 11904 return nullptr; 11905 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 11906 return DRE->getDecl(); 11907 if (auto *ME = dyn_cast<MemberExpr>(E)) 11908 return ME->getMemberDecl(); 11909 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 11910 return IRE->getDecl(); 11911 return nullptr; 11912 } 11913 11914 // This helper function promotes a binary operator's operands (which are of a 11915 // half vector type) to a vector of floats and then truncates the result to 11916 // a vector of either half or short. 11917 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 11918 BinaryOperatorKind Opc, QualType ResultTy, 11919 ExprValueKind VK, ExprObjectKind OK, 11920 bool IsCompAssign, SourceLocation OpLoc, 11921 FPOptions FPFeatures) { 11922 auto &Context = S.getASTContext(); 11923 assert((isVector(ResultTy, Context.HalfTy) || 11924 isVector(ResultTy, Context.ShortTy)) && 11925 "Result must be a vector of half or short"); 11926 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 11927 isVector(RHS.get()->getType(), Context.HalfTy) && 11928 "both operands expected to be a half vector"); 11929 11930 RHS = convertVector(RHS.get(), Context.FloatTy, S); 11931 QualType BinOpResTy = RHS.get()->getType(); 11932 11933 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 11934 // change BinOpResTy to a vector of ints. 11935 if (isVector(ResultTy, Context.ShortTy)) 11936 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 11937 11938 if (IsCompAssign) 11939 return new (Context) CompoundAssignOperator( 11940 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 11941 OpLoc, FPFeatures); 11942 11943 LHS = convertVector(LHS.get(), Context.FloatTy, S); 11944 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 11945 VK, OK, OpLoc, FPFeatures); 11946 return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S); 11947 } 11948 11949 static std::pair<ExprResult, ExprResult> 11950 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 11951 Expr *RHSExpr) { 11952 ExprResult LHS = LHSExpr, RHS = RHSExpr; 11953 if (!S.getLangOpts().CPlusPlus) { 11954 // C cannot handle TypoExpr nodes on either side of a binop because it 11955 // doesn't handle dependent types properly, so make sure any TypoExprs have 11956 // been dealt with before checking the operands. 11957 LHS = S.CorrectDelayedTyposInExpr(LHS); 11958 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 11959 if (Opc != BO_Assign) 11960 return ExprResult(E); 11961 // Avoid correcting the RHS to the same Expr as the LHS. 11962 Decl *D = getDeclFromExpr(E); 11963 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 11964 }); 11965 } 11966 return std::make_pair(LHS, RHS); 11967 } 11968 11969 /// Returns true if conversion between vectors of halfs and vectors of floats 11970 /// is needed. 11971 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 11972 QualType SrcType) { 11973 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 11974 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 11975 isVector(SrcType, Ctx.HalfTy); 11976 } 11977 11978 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 11979 /// operator @p Opc at location @c TokLoc. This routine only supports 11980 /// built-in operations; ActOnBinOp handles overloaded operators. 11981 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 11982 BinaryOperatorKind Opc, 11983 Expr *LHSExpr, Expr *RHSExpr) { 11984 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 11985 // The syntax only allows initializer lists on the RHS of assignment, 11986 // so we don't need to worry about accepting invalid code for 11987 // non-assignment operators. 11988 // C++11 5.17p9: 11989 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 11990 // of x = {} is x = T(). 11991 InitializationKind Kind = InitializationKind::CreateDirectList( 11992 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 11993 InitializedEntity Entity = 11994 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 11995 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 11996 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 11997 if (Init.isInvalid()) 11998 return Init; 11999 RHSExpr = Init.get(); 12000 } 12001 12002 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12003 QualType ResultTy; // Result type of the binary operator. 12004 // The following two variables are used for compound assignment operators 12005 QualType CompLHSTy; // Type of LHS after promotions for computation 12006 QualType CompResultTy; // Type of computation result 12007 ExprValueKind VK = VK_RValue; 12008 ExprObjectKind OK = OK_Ordinary; 12009 bool ConvertHalfVec = false; 12010 12011 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12012 if (!LHS.isUsable() || !RHS.isUsable()) 12013 return ExprError(); 12014 12015 if (getLangOpts().OpenCL) { 12016 QualType LHSTy = LHSExpr->getType(); 12017 QualType RHSTy = RHSExpr->getType(); 12018 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 12019 // the ATOMIC_VAR_INIT macro. 12020 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 12021 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12022 if (BO_Assign == Opc) 12023 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 12024 else 12025 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12026 return ExprError(); 12027 } 12028 12029 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12030 // only with a builtin functions and therefore should be disallowed here. 12031 if (LHSTy->isImageType() || RHSTy->isImageType() || 12032 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 12033 LHSTy->isPipeType() || RHSTy->isPipeType() || 12034 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 12035 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12036 return ExprError(); 12037 } 12038 } 12039 12040 switch (Opc) { 12041 case BO_Assign: 12042 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 12043 if (getLangOpts().CPlusPlus && 12044 LHS.get()->getObjectKind() != OK_ObjCProperty) { 12045 VK = LHS.get()->getValueKind(); 12046 OK = LHS.get()->getObjectKind(); 12047 } 12048 if (!ResultTy.isNull()) { 12049 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12050 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 12051 } 12052 RecordModifiableNonNullParam(*this, LHS.get()); 12053 break; 12054 case BO_PtrMemD: 12055 case BO_PtrMemI: 12056 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 12057 Opc == BO_PtrMemI); 12058 break; 12059 case BO_Mul: 12060 case BO_Div: 12061 ConvertHalfVec = true; 12062 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 12063 Opc == BO_Div); 12064 break; 12065 case BO_Rem: 12066 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 12067 break; 12068 case BO_Add: 12069 ConvertHalfVec = true; 12070 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 12071 break; 12072 case BO_Sub: 12073 ConvertHalfVec = true; 12074 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 12075 break; 12076 case BO_Shl: 12077 case BO_Shr: 12078 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 12079 break; 12080 case BO_LE: 12081 case BO_LT: 12082 case BO_GE: 12083 case BO_GT: 12084 ConvertHalfVec = true; 12085 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12086 break; 12087 case BO_EQ: 12088 case BO_NE: 12089 ConvertHalfVec = true; 12090 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12091 break; 12092 case BO_Cmp: 12093 ConvertHalfVec = true; 12094 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12095 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 12096 break; 12097 case BO_And: 12098 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 12099 LLVM_FALLTHROUGH; 12100 case BO_Xor: 12101 case BO_Or: 12102 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12103 break; 12104 case BO_LAnd: 12105 case BO_LOr: 12106 ConvertHalfVec = true; 12107 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 12108 break; 12109 case BO_MulAssign: 12110 case BO_DivAssign: 12111 ConvertHalfVec = true; 12112 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 12113 Opc == BO_DivAssign); 12114 CompLHSTy = CompResultTy; 12115 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12116 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12117 break; 12118 case BO_RemAssign: 12119 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 12120 CompLHSTy = CompResultTy; 12121 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12122 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12123 break; 12124 case BO_AddAssign: 12125 ConvertHalfVec = true; 12126 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 12127 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12128 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12129 break; 12130 case BO_SubAssign: 12131 ConvertHalfVec = true; 12132 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 12133 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12134 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12135 break; 12136 case BO_ShlAssign: 12137 case BO_ShrAssign: 12138 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 12139 CompLHSTy = CompResultTy; 12140 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12141 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12142 break; 12143 case BO_AndAssign: 12144 case BO_OrAssign: // fallthrough 12145 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12146 LLVM_FALLTHROUGH; 12147 case BO_XorAssign: 12148 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12149 CompLHSTy = CompResultTy; 12150 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12151 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12152 break; 12153 case BO_Comma: 12154 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 12155 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 12156 VK = RHS.get()->getValueKind(); 12157 OK = RHS.get()->getObjectKind(); 12158 } 12159 break; 12160 } 12161 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 12162 return ExprError(); 12163 12164 // Some of the binary operations require promoting operands of half vector to 12165 // float vectors and truncating the result back to half vector. For now, we do 12166 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 12167 // arm64). 12168 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 12169 isVector(LHS.get()->getType(), Context.HalfTy) && 12170 "both sides are half vectors or neither sides are"); 12171 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 12172 LHS.get()->getType()); 12173 12174 // Check for array bounds violations for both sides of the BinaryOperator 12175 CheckArrayAccess(LHS.get()); 12176 CheckArrayAccess(RHS.get()); 12177 12178 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 12179 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 12180 &Context.Idents.get("object_setClass"), 12181 SourceLocation(), LookupOrdinaryName); 12182 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 12183 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 12184 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 12185 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 12186 "object_setClass(") 12187 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 12188 ",") 12189 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 12190 } 12191 else 12192 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 12193 } 12194 else if (const ObjCIvarRefExpr *OIRE = 12195 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 12196 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 12197 12198 // Opc is not a compound assignment if CompResultTy is null. 12199 if (CompResultTy.isNull()) { 12200 if (ConvertHalfVec) 12201 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 12202 OpLoc, FPFeatures); 12203 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 12204 OK, OpLoc, FPFeatures); 12205 } 12206 12207 // Handle compound assignments. 12208 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 12209 OK_ObjCProperty) { 12210 VK = VK_LValue; 12211 OK = LHS.get()->getObjectKind(); 12212 } 12213 12214 if (ConvertHalfVec) 12215 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 12216 OpLoc, FPFeatures); 12217 12218 return new (Context) CompoundAssignOperator( 12219 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 12220 OpLoc, FPFeatures); 12221 } 12222 12223 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 12224 /// operators are mixed in a way that suggests that the programmer forgot that 12225 /// comparison operators have higher precedence. The most typical example of 12226 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 12227 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 12228 SourceLocation OpLoc, Expr *LHSExpr, 12229 Expr *RHSExpr) { 12230 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 12231 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 12232 12233 // Check that one of the sides is a comparison operator and the other isn't. 12234 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 12235 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 12236 if (isLeftComp == isRightComp) 12237 return; 12238 12239 // Bitwise operations are sometimes used as eager logical ops. 12240 // Don't diagnose this. 12241 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 12242 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 12243 if (isLeftBitwise || isRightBitwise) 12244 return; 12245 12246 SourceRange DiagRange = isLeftComp 12247 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 12248 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 12249 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 12250 SourceRange ParensRange = 12251 isLeftComp 12252 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 12253 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 12254 12255 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 12256 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 12257 SuggestParentheses(Self, OpLoc, 12258 Self.PDiag(diag::note_precedence_silence) << OpStr, 12259 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 12260 SuggestParentheses(Self, OpLoc, 12261 Self.PDiag(diag::note_precedence_bitwise_first) 12262 << BinaryOperator::getOpcodeStr(Opc), 12263 ParensRange); 12264 } 12265 12266 /// It accepts a '&&' expr that is inside a '||' one. 12267 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 12268 /// in parentheses. 12269 static void 12270 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 12271 BinaryOperator *Bop) { 12272 assert(Bop->getOpcode() == BO_LAnd); 12273 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 12274 << Bop->getSourceRange() << OpLoc; 12275 SuggestParentheses(Self, Bop->getOperatorLoc(), 12276 Self.PDiag(diag::note_precedence_silence) 12277 << Bop->getOpcodeStr(), 12278 Bop->getSourceRange()); 12279 } 12280 12281 /// Returns true if the given expression can be evaluated as a constant 12282 /// 'true'. 12283 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 12284 bool Res; 12285 return !E->isValueDependent() && 12286 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 12287 } 12288 12289 /// Returns true if the given expression can be evaluated as a constant 12290 /// 'false'. 12291 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 12292 bool Res; 12293 return !E->isValueDependent() && 12294 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 12295 } 12296 12297 /// Look for '&&' in the left hand of a '||' expr. 12298 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 12299 Expr *LHSExpr, Expr *RHSExpr) { 12300 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 12301 if (Bop->getOpcode() == BO_LAnd) { 12302 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 12303 if (EvaluatesAsFalse(S, RHSExpr)) 12304 return; 12305 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 12306 if (!EvaluatesAsTrue(S, Bop->getLHS())) 12307 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12308 } else if (Bop->getOpcode() == BO_LOr) { 12309 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 12310 // If it's "a || b && 1 || c" we didn't warn earlier for 12311 // "a || b && 1", but warn now. 12312 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 12313 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 12314 } 12315 } 12316 } 12317 } 12318 12319 /// Look for '&&' in the right hand of a '||' expr. 12320 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 12321 Expr *LHSExpr, Expr *RHSExpr) { 12322 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 12323 if (Bop->getOpcode() == BO_LAnd) { 12324 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 12325 if (EvaluatesAsFalse(S, LHSExpr)) 12326 return; 12327 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 12328 if (!EvaluatesAsTrue(S, Bop->getRHS())) 12329 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12330 } 12331 } 12332 } 12333 12334 /// Look for bitwise op in the left or right hand of a bitwise op with 12335 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 12336 /// the '&' expression in parentheses. 12337 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 12338 SourceLocation OpLoc, Expr *SubExpr) { 12339 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12340 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 12341 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 12342 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 12343 << Bop->getSourceRange() << OpLoc; 12344 SuggestParentheses(S, Bop->getOperatorLoc(), 12345 S.PDiag(diag::note_precedence_silence) 12346 << Bop->getOpcodeStr(), 12347 Bop->getSourceRange()); 12348 } 12349 } 12350 } 12351 12352 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 12353 Expr *SubExpr, StringRef Shift) { 12354 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12355 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 12356 StringRef Op = Bop->getOpcodeStr(); 12357 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 12358 << Bop->getSourceRange() << OpLoc << Shift << Op; 12359 SuggestParentheses(S, Bop->getOperatorLoc(), 12360 S.PDiag(diag::note_precedence_silence) << Op, 12361 Bop->getSourceRange()); 12362 } 12363 } 12364 } 12365 12366 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 12367 Expr *LHSExpr, Expr *RHSExpr) { 12368 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 12369 if (!OCE) 12370 return; 12371 12372 FunctionDecl *FD = OCE->getDirectCallee(); 12373 if (!FD || !FD->isOverloadedOperator()) 12374 return; 12375 12376 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 12377 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 12378 return; 12379 12380 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 12381 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 12382 << (Kind == OO_LessLess); 12383 SuggestParentheses(S, OCE->getOperatorLoc(), 12384 S.PDiag(diag::note_precedence_silence) 12385 << (Kind == OO_LessLess ? "<<" : ">>"), 12386 OCE->getSourceRange()); 12387 SuggestParentheses( 12388 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 12389 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 12390 } 12391 12392 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 12393 /// precedence. 12394 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 12395 SourceLocation OpLoc, Expr *LHSExpr, 12396 Expr *RHSExpr){ 12397 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 12398 if (BinaryOperator::isBitwiseOp(Opc)) 12399 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 12400 12401 // Diagnose "arg1 & arg2 | arg3" 12402 if ((Opc == BO_Or || Opc == BO_Xor) && 12403 !OpLoc.isMacroID()/* Don't warn in macros. */) { 12404 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 12405 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 12406 } 12407 12408 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 12409 // We don't warn for 'assert(a || b && "bad")' since this is safe. 12410 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 12411 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 12412 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 12413 } 12414 12415 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 12416 || Opc == BO_Shr) { 12417 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 12418 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 12419 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 12420 } 12421 12422 // Warn on overloaded shift operators and comparisons, such as: 12423 // cout << 5 == 4; 12424 if (BinaryOperator::isComparisonOp(Opc)) 12425 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 12426 } 12427 12428 // Binary Operators. 'Tok' is the token for the operator. 12429 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 12430 tok::TokenKind Kind, 12431 Expr *LHSExpr, Expr *RHSExpr) { 12432 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 12433 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 12434 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 12435 12436 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 12437 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 12438 12439 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 12440 } 12441 12442 /// Build an overloaded binary operator expression in the given scope. 12443 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 12444 BinaryOperatorKind Opc, 12445 Expr *LHS, Expr *RHS) { 12446 switch (Opc) { 12447 case BO_Assign: 12448 case BO_DivAssign: 12449 case BO_RemAssign: 12450 case BO_SubAssign: 12451 case BO_AndAssign: 12452 case BO_OrAssign: 12453 case BO_XorAssign: 12454 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 12455 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 12456 break; 12457 default: 12458 break; 12459 } 12460 12461 // Find all of the overloaded operators visible from this 12462 // point. We perform both an operator-name lookup from the local 12463 // scope and an argument-dependent lookup based on the types of 12464 // the arguments. 12465 UnresolvedSet<16> Functions; 12466 OverloadedOperatorKind OverOp 12467 = BinaryOperator::getOverloadedOperator(Opc); 12468 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 12469 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 12470 RHS->getType(), Functions); 12471 12472 // Build the (potentially-overloaded, potentially-dependent) 12473 // binary operation. 12474 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 12475 } 12476 12477 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 12478 BinaryOperatorKind Opc, 12479 Expr *LHSExpr, Expr *RHSExpr) { 12480 ExprResult LHS, RHS; 12481 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12482 if (!LHS.isUsable() || !RHS.isUsable()) 12483 return ExprError(); 12484 LHSExpr = LHS.get(); 12485 RHSExpr = RHS.get(); 12486 12487 // We want to end up calling one of checkPseudoObjectAssignment 12488 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 12489 // both expressions are overloadable or either is type-dependent), 12490 // or CreateBuiltinBinOp (in any other case). We also want to get 12491 // any placeholder types out of the way. 12492 12493 // Handle pseudo-objects in the LHS. 12494 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 12495 // Assignments with a pseudo-object l-value need special analysis. 12496 if (pty->getKind() == BuiltinType::PseudoObject && 12497 BinaryOperator::isAssignmentOp(Opc)) 12498 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 12499 12500 // Don't resolve overloads if the other type is overloadable. 12501 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 12502 // We can't actually test that if we still have a placeholder, 12503 // though. Fortunately, none of the exceptions we see in that 12504 // code below are valid when the LHS is an overload set. Note 12505 // that an overload set can be dependently-typed, but it never 12506 // instantiates to having an overloadable type. 12507 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12508 if (resolvedRHS.isInvalid()) return ExprError(); 12509 RHSExpr = resolvedRHS.get(); 12510 12511 if (RHSExpr->isTypeDependent() || 12512 RHSExpr->getType()->isOverloadableType()) 12513 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12514 } 12515 12516 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 12517 // template, diagnose the missing 'template' keyword instead of diagnosing 12518 // an invalid use of a bound member function. 12519 // 12520 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 12521 // to C++1z [over.over]/1.4, but we already checked for that case above. 12522 if (Opc == BO_LT && inTemplateInstantiation() && 12523 (pty->getKind() == BuiltinType::BoundMember || 12524 pty->getKind() == BuiltinType::Overload)) { 12525 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 12526 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 12527 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 12528 return isa<FunctionTemplateDecl>(ND); 12529 })) { 12530 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 12531 : OE->getNameLoc(), 12532 diag::err_template_kw_missing) 12533 << OE->getName().getAsString() << ""; 12534 return ExprError(); 12535 } 12536 } 12537 12538 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 12539 if (LHS.isInvalid()) return ExprError(); 12540 LHSExpr = LHS.get(); 12541 } 12542 12543 // Handle pseudo-objects in the RHS. 12544 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 12545 // An overload in the RHS can potentially be resolved by the type 12546 // being assigned to. 12547 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 12548 if (getLangOpts().CPlusPlus && 12549 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 12550 LHSExpr->getType()->isOverloadableType())) 12551 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12552 12553 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12554 } 12555 12556 // Don't resolve overloads if the other type is overloadable. 12557 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 12558 LHSExpr->getType()->isOverloadableType()) 12559 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12560 12561 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12562 if (!resolvedRHS.isUsable()) return ExprError(); 12563 RHSExpr = resolvedRHS.get(); 12564 } 12565 12566 if (getLangOpts().CPlusPlus) { 12567 // If either expression is type-dependent, always build an 12568 // overloaded op. 12569 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 12570 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12571 12572 // Otherwise, build an overloaded op if either expression has an 12573 // overloadable type. 12574 if (LHSExpr->getType()->isOverloadableType() || 12575 RHSExpr->getType()->isOverloadableType()) 12576 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12577 } 12578 12579 // Build a built-in binary operation. 12580 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12581 } 12582 12583 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 12584 if (T.isNull() || T->isDependentType()) 12585 return false; 12586 12587 if (!T->isPromotableIntegerType()) 12588 return true; 12589 12590 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 12591 } 12592 12593 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 12594 UnaryOperatorKind Opc, 12595 Expr *InputExpr) { 12596 ExprResult Input = InputExpr; 12597 ExprValueKind VK = VK_RValue; 12598 ExprObjectKind OK = OK_Ordinary; 12599 QualType resultType; 12600 bool CanOverflow = false; 12601 12602 bool ConvertHalfVec = false; 12603 if (getLangOpts().OpenCL) { 12604 QualType Ty = InputExpr->getType(); 12605 // The only legal unary operation for atomics is '&'. 12606 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 12607 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12608 // only with a builtin functions and therefore should be disallowed here. 12609 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 12610 || Ty->isBlockPointerType())) { 12611 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12612 << InputExpr->getType() 12613 << Input.get()->getSourceRange()); 12614 } 12615 } 12616 switch (Opc) { 12617 case UO_PreInc: 12618 case UO_PreDec: 12619 case UO_PostInc: 12620 case UO_PostDec: 12621 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 12622 OpLoc, 12623 Opc == UO_PreInc || 12624 Opc == UO_PostInc, 12625 Opc == UO_PreInc || 12626 Opc == UO_PreDec); 12627 CanOverflow = isOverflowingIntegerType(Context, resultType); 12628 break; 12629 case UO_AddrOf: 12630 resultType = CheckAddressOfOperand(Input, OpLoc); 12631 RecordModifiableNonNullParam(*this, InputExpr); 12632 break; 12633 case UO_Deref: { 12634 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12635 if (Input.isInvalid()) return ExprError(); 12636 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 12637 break; 12638 } 12639 case UO_Plus: 12640 case UO_Minus: 12641 CanOverflow = Opc == UO_Minus && 12642 isOverflowingIntegerType(Context, Input.get()->getType()); 12643 Input = UsualUnaryConversions(Input.get()); 12644 if (Input.isInvalid()) return ExprError(); 12645 // Unary plus and minus require promoting an operand of half vector to a 12646 // float vector and truncating the result back to a half vector. For now, we 12647 // do this only when HalfArgsAndReturns is set (that is, when the target is 12648 // arm or arm64). 12649 ConvertHalfVec = 12650 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 12651 12652 // If the operand is a half vector, promote it to a float vector. 12653 if (ConvertHalfVec) 12654 Input = convertVector(Input.get(), Context.FloatTy, *this); 12655 resultType = Input.get()->getType(); 12656 if (resultType->isDependentType()) 12657 break; 12658 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 12659 break; 12660 else if (resultType->isVectorType() && 12661 // The z vector extensions don't allow + or - with bool vectors. 12662 (!Context.getLangOpts().ZVector || 12663 resultType->getAs<VectorType>()->getVectorKind() != 12664 VectorType::AltiVecBool)) 12665 break; 12666 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 12667 Opc == UO_Plus && 12668 resultType->isPointerType()) 12669 break; 12670 12671 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12672 << resultType << Input.get()->getSourceRange()); 12673 12674 case UO_Not: // bitwise complement 12675 Input = UsualUnaryConversions(Input.get()); 12676 if (Input.isInvalid()) 12677 return ExprError(); 12678 resultType = Input.get()->getType(); 12679 12680 if (resultType->isDependentType()) 12681 break; 12682 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 12683 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 12684 // C99 does not support '~' for complex conjugation. 12685 Diag(OpLoc, diag::ext_integer_complement_complex) 12686 << resultType << Input.get()->getSourceRange(); 12687 else if (resultType->hasIntegerRepresentation()) 12688 break; 12689 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 12690 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 12691 // on vector float types. 12692 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12693 if (!T->isIntegerType()) 12694 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12695 << resultType << Input.get()->getSourceRange()); 12696 } else { 12697 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12698 << resultType << Input.get()->getSourceRange()); 12699 } 12700 break; 12701 12702 case UO_LNot: // logical negation 12703 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 12704 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12705 if (Input.isInvalid()) return ExprError(); 12706 resultType = Input.get()->getType(); 12707 12708 // Though we still have to promote half FP to float... 12709 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 12710 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 12711 resultType = Context.FloatTy; 12712 } 12713 12714 if (resultType->isDependentType()) 12715 break; 12716 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 12717 // C99 6.5.3.3p1: ok, fallthrough; 12718 if (Context.getLangOpts().CPlusPlus) { 12719 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 12720 // operand contextually converted to bool. 12721 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 12722 ScalarTypeToBooleanCastKind(resultType)); 12723 } else if (Context.getLangOpts().OpenCL && 12724 Context.getLangOpts().OpenCLVersion < 120) { 12725 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12726 // operate on scalar float types. 12727 if (!resultType->isIntegerType() && !resultType->isPointerType()) 12728 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12729 << resultType << Input.get()->getSourceRange()); 12730 } 12731 } else if (resultType->isExtVectorType()) { 12732 if (Context.getLangOpts().OpenCL && 12733 Context.getLangOpts().OpenCLVersion < 120) { 12734 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12735 // operate on vector float types. 12736 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12737 if (!T->isIntegerType()) 12738 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12739 << resultType << Input.get()->getSourceRange()); 12740 } 12741 // Vector logical not returns the signed variant of the operand type. 12742 resultType = GetSignedVectorType(resultType); 12743 break; 12744 } else { 12745 // FIXME: GCC's vector extension permits the usage of '!' with a vector 12746 // type in C++. We should allow that here too. 12747 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12748 << resultType << Input.get()->getSourceRange()); 12749 } 12750 12751 // LNot always has type int. C99 6.5.3.3p5. 12752 // In C++, it's bool. C++ 5.3.1p8 12753 resultType = Context.getLogicalOperationType(); 12754 break; 12755 case UO_Real: 12756 case UO_Imag: 12757 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 12758 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 12759 // complex l-values to ordinary l-values and all other values to r-values. 12760 if (Input.isInvalid()) return ExprError(); 12761 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 12762 if (Input.get()->getValueKind() != VK_RValue && 12763 Input.get()->getObjectKind() == OK_Ordinary) 12764 VK = Input.get()->getValueKind(); 12765 } else if (!getLangOpts().CPlusPlus) { 12766 // In C, a volatile scalar is read by __imag. In C++, it is not. 12767 Input = DefaultLvalueConversion(Input.get()); 12768 } 12769 break; 12770 case UO_Extension: 12771 resultType = Input.get()->getType(); 12772 VK = Input.get()->getValueKind(); 12773 OK = Input.get()->getObjectKind(); 12774 break; 12775 case UO_Coawait: 12776 // It's unnecessary to represent the pass-through operator co_await in the 12777 // AST; just return the input expression instead. 12778 assert(!Input.get()->getType()->isDependentType() && 12779 "the co_await expression must be non-dependant before " 12780 "building operator co_await"); 12781 return Input; 12782 } 12783 if (resultType.isNull() || Input.isInvalid()) 12784 return ExprError(); 12785 12786 // Check for array bounds violations in the operand of the UnaryOperator, 12787 // except for the '*' and '&' operators that have to be handled specially 12788 // by CheckArrayAccess (as there are special cases like &array[arraysize] 12789 // that are explicitly defined as valid by the standard). 12790 if (Opc != UO_AddrOf && Opc != UO_Deref) 12791 CheckArrayAccess(Input.get()); 12792 12793 auto *UO = new (Context) 12794 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 12795 // Convert the result back to a half vector. 12796 if (ConvertHalfVec) 12797 return convertVector(UO, Context.HalfTy, *this); 12798 return UO; 12799 } 12800 12801 /// Determine whether the given expression is a qualified member 12802 /// access expression, of a form that could be turned into a pointer to member 12803 /// with the address-of operator. 12804 bool Sema::isQualifiedMemberAccess(Expr *E) { 12805 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12806 if (!DRE->getQualifier()) 12807 return false; 12808 12809 ValueDecl *VD = DRE->getDecl(); 12810 if (!VD->isCXXClassMember()) 12811 return false; 12812 12813 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 12814 return true; 12815 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 12816 return Method->isInstance(); 12817 12818 return false; 12819 } 12820 12821 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12822 if (!ULE->getQualifier()) 12823 return false; 12824 12825 for (NamedDecl *D : ULE->decls()) { 12826 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 12827 if (Method->isInstance()) 12828 return true; 12829 } else { 12830 // Overload set does not contain methods. 12831 break; 12832 } 12833 } 12834 12835 return false; 12836 } 12837 12838 return false; 12839 } 12840 12841 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 12842 UnaryOperatorKind Opc, Expr *Input) { 12843 // First things first: handle placeholders so that the 12844 // overloaded-operator check considers the right type. 12845 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 12846 // Increment and decrement of pseudo-object references. 12847 if (pty->getKind() == BuiltinType::PseudoObject && 12848 UnaryOperator::isIncrementDecrementOp(Opc)) 12849 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 12850 12851 // extension is always a builtin operator. 12852 if (Opc == UO_Extension) 12853 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12854 12855 // & gets special logic for several kinds of placeholder. 12856 // The builtin code knows what to do. 12857 if (Opc == UO_AddrOf && 12858 (pty->getKind() == BuiltinType::Overload || 12859 pty->getKind() == BuiltinType::UnknownAny || 12860 pty->getKind() == BuiltinType::BoundMember)) 12861 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12862 12863 // Anything else needs to be handled now. 12864 ExprResult Result = CheckPlaceholderExpr(Input); 12865 if (Result.isInvalid()) return ExprError(); 12866 Input = Result.get(); 12867 } 12868 12869 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 12870 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 12871 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 12872 // Find all of the overloaded operators visible from this 12873 // point. We perform both an operator-name lookup from the local 12874 // scope and an argument-dependent lookup based on the types of 12875 // the arguments. 12876 UnresolvedSet<16> Functions; 12877 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 12878 if (S && OverOp != OO_None) 12879 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 12880 Functions); 12881 12882 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 12883 } 12884 12885 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12886 } 12887 12888 // Unary Operators. 'Tok' is the token for the operator. 12889 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 12890 tok::TokenKind Op, Expr *Input) { 12891 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 12892 } 12893 12894 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 12895 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 12896 LabelDecl *TheDecl) { 12897 TheDecl->markUsed(Context); 12898 // Create the AST node. The address of a label always has type 'void*'. 12899 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 12900 Context.getPointerType(Context.VoidTy)); 12901 } 12902 12903 /// Given the last statement in a statement-expression, check whether 12904 /// the result is a producing expression (like a call to an 12905 /// ns_returns_retained function) and, if so, rebuild it to hoist the 12906 /// release out of the full-expression. Otherwise, return null. 12907 /// Cannot fail. 12908 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 12909 // Should always be wrapped with one of these. 12910 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 12911 if (!cleanups) return nullptr; 12912 12913 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 12914 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 12915 return nullptr; 12916 12917 // Splice out the cast. This shouldn't modify any interesting 12918 // features of the statement. 12919 Expr *producer = cast->getSubExpr(); 12920 assert(producer->getType() == cast->getType()); 12921 assert(producer->getValueKind() == cast->getValueKind()); 12922 cleanups->setSubExpr(producer); 12923 return cleanups; 12924 } 12925 12926 void Sema::ActOnStartStmtExpr() { 12927 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 12928 } 12929 12930 void Sema::ActOnStmtExprError() { 12931 // Note that function is also called by TreeTransform when leaving a 12932 // StmtExpr scope without rebuilding anything. 12933 12934 DiscardCleanupsInEvaluationContext(); 12935 PopExpressionEvaluationContext(); 12936 } 12937 12938 ExprResult 12939 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 12940 SourceLocation RPLoc) { // "({..})" 12941 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 12942 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 12943 12944 if (hasAnyUnrecoverableErrorsInThisFunction()) 12945 DiscardCleanupsInEvaluationContext(); 12946 assert(!Cleanup.exprNeedsCleanups() && 12947 "cleanups within StmtExpr not correctly bound!"); 12948 PopExpressionEvaluationContext(); 12949 12950 // FIXME: there are a variety of strange constraints to enforce here, for 12951 // example, it is not possible to goto into a stmt expression apparently. 12952 // More semantic analysis is needed. 12953 12954 // If there are sub-stmts in the compound stmt, take the type of the last one 12955 // as the type of the stmtexpr. 12956 QualType Ty = Context.VoidTy; 12957 bool StmtExprMayBindToTemp = false; 12958 if (!Compound->body_empty()) { 12959 Stmt *LastStmt = Compound->body_back(); 12960 LabelStmt *LastLabelStmt = nullptr; 12961 // If LastStmt is a label, skip down through into the body. 12962 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 12963 LastLabelStmt = Label; 12964 LastStmt = Label->getSubStmt(); 12965 } 12966 12967 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 12968 // Do function/array conversion on the last expression, but not 12969 // lvalue-to-rvalue. However, initialize an unqualified type. 12970 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 12971 if (LastExpr.isInvalid()) 12972 return ExprError(); 12973 Ty = LastExpr.get()->getType().getUnqualifiedType(); 12974 12975 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 12976 // In ARC, if the final expression ends in a consume, splice 12977 // the consume out and bind it later. In the alternate case 12978 // (when dealing with a retainable type), the result 12979 // initialization will create a produce. In both cases the 12980 // result will be +1, and we'll need to balance that out with 12981 // a bind. 12982 if (Expr *rebuiltLastStmt 12983 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 12984 LastExpr = rebuiltLastStmt; 12985 } else { 12986 LastExpr = PerformCopyInitialization( 12987 InitializedEntity::InitializeStmtExprResult(LPLoc, Ty), 12988 SourceLocation(), LastExpr); 12989 } 12990 12991 if (LastExpr.isInvalid()) 12992 return ExprError(); 12993 if (LastExpr.get() != nullptr) { 12994 if (!LastLabelStmt) 12995 Compound->setLastStmt(LastExpr.get()); 12996 else 12997 LastLabelStmt->setSubStmt(LastExpr.get()); 12998 StmtExprMayBindToTemp = true; 12999 } 13000 } 13001 } 13002 } 13003 13004 // FIXME: Check that expression type is complete/non-abstract; statement 13005 // expressions are not lvalues. 13006 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 13007 if (StmtExprMayBindToTemp) 13008 return MaybeBindToTemporary(ResStmtExpr); 13009 return ResStmtExpr; 13010 } 13011 13012 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 13013 TypeSourceInfo *TInfo, 13014 ArrayRef<OffsetOfComponent> Components, 13015 SourceLocation RParenLoc) { 13016 QualType ArgTy = TInfo->getType(); 13017 bool Dependent = ArgTy->isDependentType(); 13018 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 13019 13020 // We must have at least one component that refers to the type, and the first 13021 // one is known to be a field designator. Verify that the ArgTy represents 13022 // a struct/union/class. 13023 if (!Dependent && !ArgTy->isRecordType()) 13024 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 13025 << ArgTy << TypeRange); 13026 13027 // Type must be complete per C99 7.17p3 because a declaring a variable 13028 // with an incomplete type would be ill-formed. 13029 if (!Dependent 13030 && RequireCompleteType(BuiltinLoc, ArgTy, 13031 diag::err_offsetof_incomplete_type, TypeRange)) 13032 return ExprError(); 13033 13034 bool DidWarnAboutNonPOD = false; 13035 QualType CurrentType = ArgTy; 13036 SmallVector<OffsetOfNode, 4> Comps; 13037 SmallVector<Expr*, 4> Exprs; 13038 for (const OffsetOfComponent &OC : Components) { 13039 if (OC.isBrackets) { 13040 // Offset of an array sub-field. TODO: Should we allow vector elements? 13041 if (!CurrentType->isDependentType()) { 13042 const ArrayType *AT = Context.getAsArrayType(CurrentType); 13043 if(!AT) 13044 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 13045 << CurrentType); 13046 CurrentType = AT->getElementType(); 13047 } else 13048 CurrentType = Context.DependentTy; 13049 13050 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 13051 if (IdxRval.isInvalid()) 13052 return ExprError(); 13053 Expr *Idx = IdxRval.get(); 13054 13055 // The expression must be an integral expression. 13056 // FIXME: An integral constant expression? 13057 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 13058 !Idx->getType()->isIntegerType()) 13059 return ExprError( 13060 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 13061 << Idx->getSourceRange()); 13062 13063 // Record this array index. 13064 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 13065 Exprs.push_back(Idx); 13066 continue; 13067 } 13068 13069 // Offset of a field. 13070 if (CurrentType->isDependentType()) { 13071 // We have the offset of a field, but we can't look into the dependent 13072 // type. Just record the identifier of the field. 13073 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 13074 CurrentType = Context.DependentTy; 13075 continue; 13076 } 13077 13078 // We need to have a complete type to look into. 13079 if (RequireCompleteType(OC.LocStart, CurrentType, 13080 diag::err_offsetof_incomplete_type)) 13081 return ExprError(); 13082 13083 // Look for the designated field. 13084 const RecordType *RC = CurrentType->getAs<RecordType>(); 13085 if (!RC) 13086 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 13087 << CurrentType); 13088 RecordDecl *RD = RC->getDecl(); 13089 13090 // C++ [lib.support.types]p5: 13091 // The macro offsetof accepts a restricted set of type arguments in this 13092 // International Standard. type shall be a POD structure or a POD union 13093 // (clause 9). 13094 // C++11 [support.types]p4: 13095 // If type is not a standard-layout class (Clause 9), the results are 13096 // undefined. 13097 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13098 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 13099 unsigned DiagID = 13100 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 13101 : diag::ext_offsetof_non_pod_type; 13102 13103 if (!IsSafe && !DidWarnAboutNonPOD && 13104 DiagRuntimeBehavior(BuiltinLoc, nullptr, 13105 PDiag(DiagID) 13106 << SourceRange(Components[0].LocStart, OC.LocEnd) 13107 << CurrentType)) 13108 DidWarnAboutNonPOD = true; 13109 } 13110 13111 // Look for the field. 13112 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 13113 LookupQualifiedName(R, RD); 13114 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 13115 IndirectFieldDecl *IndirectMemberDecl = nullptr; 13116 if (!MemberDecl) { 13117 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 13118 MemberDecl = IndirectMemberDecl->getAnonField(); 13119 } 13120 13121 if (!MemberDecl) 13122 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 13123 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 13124 OC.LocEnd)); 13125 13126 // C99 7.17p3: 13127 // (If the specified member is a bit-field, the behavior is undefined.) 13128 // 13129 // We diagnose this as an error. 13130 if (MemberDecl->isBitField()) { 13131 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 13132 << MemberDecl->getDeclName() 13133 << SourceRange(BuiltinLoc, RParenLoc); 13134 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 13135 return ExprError(); 13136 } 13137 13138 RecordDecl *Parent = MemberDecl->getParent(); 13139 if (IndirectMemberDecl) 13140 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 13141 13142 // If the member was found in a base class, introduce OffsetOfNodes for 13143 // the base class indirections. 13144 CXXBasePaths Paths; 13145 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 13146 Paths)) { 13147 if (Paths.getDetectedVirtual()) { 13148 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 13149 << MemberDecl->getDeclName() 13150 << SourceRange(BuiltinLoc, RParenLoc); 13151 return ExprError(); 13152 } 13153 13154 CXXBasePath &Path = Paths.front(); 13155 for (const CXXBasePathElement &B : Path) 13156 Comps.push_back(OffsetOfNode(B.Base)); 13157 } 13158 13159 if (IndirectMemberDecl) { 13160 for (auto *FI : IndirectMemberDecl->chain()) { 13161 assert(isa<FieldDecl>(FI)); 13162 Comps.push_back(OffsetOfNode(OC.LocStart, 13163 cast<FieldDecl>(FI), OC.LocEnd)); 13164 } 13165 } else 13166 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 13167 13168 CurrentType = MemberDecl->getType().getNonReferenceType(); 13169 } 13170 13171 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 13172 Comps, Exprs, RParenLoc); 13173 } 13174 13175 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 13176 SourceLocation BuiltinLoc, 13177 SourceLocation TypeLoc, 13178 ParsedType ParsedArgTy, 13179 ArrayRef<OffsetOfComponent> Components, 13180 SourceLocation RParenLoc) { 13181 13182 TypeSourceInfo *ArgTInfo; 13183 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 13184 if (ArgTy.isNull()) 13185 return ExprError(); 13186 13187 if (!ArgTInfo) 13188 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 13189 13190 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 13191 } 13192 13193 13194 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 13195 Expr *CondExpr, 13196 Expr *LHSExpr, Expr *RHSExpr, 13197 SourceLocation RPLoc) { 13198 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 13199 13200 ExprValueKind VK = VK_RValue; 13201 ExprObjectKind OK = OK_Ordinary; 13202 QualType resType; 13203 bool ValueDependent = false; 13204 bool CondIsTrue = false; 13205 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 13206 resType = Context.DependentTy; 13207 ValueDependent = true; 13208 } else { 13209 // The conditional expression is required to be a constant expression. 13210 llvm::APSInt condEval(32); 13211 ExprResult CondICE 13212 = VerifyIntegerConstantExpression(CondExpr, &condEval, 13213 diag::err_typecheck_choose_expr_requires_constant, false); 13214 if (CondICE.isInvalid()) 13215 return ExprError(); 13216 CondExpr = CondICE.get(); 13217 CondIsTrue = condEval.getZExtValue(); 13218 13219 // If the condition is > zero, then the AST type is the same as the LHSExpr. 13220 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 13221 13222 resType = ActiveExpr->getType(); 13223 ValueDependent = ActiveExpr->isValueDependent(); 13224 VK = ActiveExpr->getValueKind(); 13225 OK = ActiveExpr->getObjectKind(); 13226 } 13227 13228 return new (Context) 13229 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 13230 CondIsTrue, resType->isDependentType(), ValueDependent); 13231 } 13232 13233 //===----------------------------------------------------------------------===// 13234 // Clang Extensions. 13235 //===----------------------------------------------------------------------===// 13236 13237 /// ActOnBlockStart - This callback is invoked when a block literal is started. 13238 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 13239 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 13240 13241 if (LangOpts.CPlusPlus) { 13242 Decl *ManglingContextDecl; 13243 if (MangleNumberingContext *MCtx = 13244 getCurrentMangleNumberContext(Block->getDeclContext(), 13245 ManglingContextDecl)) { 13246 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 13247 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 13248 } 13249 } 13250 13251 PushBlockScope(CurScope, Block); 13252 CurContext->addDecl(Block); 13253 if (CurScope) 13254 PushDeclContext(CurScope, Block); 13255 else 13256 CurContext = Block; 13257 13258 getCurBlock()->HasImplicitReturnType = true; 13259 13260 // Enter a new evaluation context to insulate the block from any 13261 // cleanups from the enclosing full-expression. 13262 PushExpressionEvaluationContext( 13263 ExpressionEvaluationContext::PotentiallyEvaluated); 13264 } 13265 13266 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 13267 Scope *CurScope) { 13268 assert(ParamInfo.getIdentifier() == nullptr && 13269 "block-id should have no identifier!"); 13270 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 13271 BlockScopeInfo *CurBlock = getCurBlock(); 13272 13273 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 13274 QualType T = Sig->getType(); 13275 13276 // FIXME: We should allow unexpanded parameter packs here, but that would, 13277 // in turn, make the block expression contain unexpanded parameter packs. 13278 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 13279 // Drop the parameters. 13280 FunctionProtoType::ExtProtoInfo EPI; 13281 EPI.HasTrailingReturn = false; 13282 EPI.TypeQuals |= DeclSpec::TQ_const; 13283 T = Context.getFunctionType(Context.DependentTy, None, EPI); 13284 Sig = Context.getTrivialTypeSourceInfo(T); 13285 } 13286 13287 // GetTypeForDeclarator always produces a function type for a block 13288 // literal signature. Furthermore, it is always a FunctionProtoType 13289 // unless the function was written with a typedef. 13290 assert(T->isFunctionType() && 13291 "GetTypeForDeclarator made a non-function block signature"); 13292 13293 // Look for an explicit signature in that function type. 13294 FunctionProtoTypeLoc ExplicitSignature; 13295 13296 if ((ExplicitSignature = 13297 Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) { 13298 13299 // Check whether that explicit signature was synthesized by 13300 // GetTypeForDeclarator. If so, don't save that as part of the 13301 // written signature. 13302 if (ExplicitSignature.getLocalRangeBegin() == 13303 ExplicitSignature.getLocalRangeEnd()) { 13304 // This would be much cheaper if we stored TypeLocs instead of 13305 // TypeSourceInfos. 13306 TypeLoc Result = ExplicitSignature.getReturnLoc(); 13307 unsigned Size = Result.getFullDataSize(); 13308 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 13309 Sig->getTypeLoc().initializeFullCopy(Result, Size); 13310 13311 ExplicitSignature = FunctionProtoTypeLoc(); 13312 } 13313 } 13314 13315 CurBlock->TheDecl->setSignatureAsWritten(Sig); 13316 CurBlock->FunctionType = T; 13317 13318 const FunctionType *Fn = T->getAs<FunctionType>(); 13319 QualType RetTy = Fn->getReturnType(); 13320 bool isVariadic = 13321 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 13322 13323 CurBlock->TheDecl->setIsVariadic(isVariadic); 13324 13325 // Context.DependentTy is used as a placeholder for a missing block 13326 // return type. TODO: what should we do with declarators like: 13327 // ^ * { ... } 13328 // If the answer is "apply template argument deduction".... 13329 if (RetTy != Context.DependentTy) { 13330 CurBlock->ReturnType = RetTy; 13331 CurBlock->TheDecl->setBlockMissingReturnType(false); 13332 CurBlock->HasImplicitReturnType = false; 13333 } 13334 13335 // Push block parameters from the declarator if we had them. 13336 SmallVector<ParmVarDecl*, 8> Params; 13337 if (ExplicitSignature) { 13338 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 13339 ParmVarDecl *Param = ExplicitSignature.getParam(I); 13340 if (Param->getIdentifier() == nullptr && 13341 !Param->isImplicit() && 13342 !Param->isInvalidDecl() && 13343 !getLangOpts().CPlusPlus) 13344 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 13345 Params.push_back(Param); 13346 } 13347 13348 // Fake up parameter variables if we have a typedef, like 13349 // ^ fntype { ... } 13350 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 13351 for (const auto &I : Fn->param_types()) { 13352 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 13353 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 13354 Params.push_back(Param); 13355 } 13356 } 13357 13358 // Set the parameters on the block decl. 13359 if (!Params.empty()) { 13360 CurBlock->TheDecl->setParams(Params); 13361 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 13362 /*CheckParameterNames=*/false); 13363 } 13364 13365 // Finally we can process decl attributes. 13366 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 13367 13368 // Put the parameter variables in scope. 13369 for (auto AI : CurBlock->TheDecl->parameters()) { 13370 AI->setOwningFunction(CurBlock->TheDecl); 13371 13372 // If this has an identifier, add it to the scope stack. 13373 if (AI->getIdentifier()) { 13374 CheckShadow(CurBlock->TheScope, AI); 13375 13376 PushOnScopeChains(AI, CurBlock->TheScope); 13377 } 13378 } 13379 } 13380 13381 /// ActOnBlockError - If there is an error parsing a block, this callback 13382 /// is invoked to pop the information about the block from the action impl. 13383 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 13384 // Leave the expression-evaluation context. 13385 DiscardCleanupsInEvaluationContext(); 13386 PopExpressionEvaluationContext(); 13387 13388 // Pop off CurBlock, handle nested blocks. 13389 PopDeclContext(); 13390 PopFunctionScopeInfo(); 13391 } 13392 13393 /// ActOnBlockStmtExpr - This is called when the body of a block statement 13394 /// literal was successfully completed. ^(int x){...} 13395 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 13396 Stmt *Body, Scope *CurScope) { 13397 // If blocks are disabled, emit an error. 13398 if (!LangOpts.Blocks) 13399 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 13400 13401 // Leave the expression-evaluation context. 13402 if (hasAnyUnrecoverableErrorsInThisFunction()) 13403 DiscardCleanupsInEvaluationContext(); 13404 assert(!Cleanup.exprNeedsCleanups() && 13405 "cleanups within block not correctly bound!"); 13406 PopExpressionEvaluationContext(); 13407 13408 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 13409 13410 if (BSI->HasImplicitReturnType) 13411 deduceClosureReturnType(*BSI); 13412 13413 PopDeclContext(); 13414 13415 QualType RetTy = Context.VoidTy; 13416 if (!BSI->ReturnType.isNull()) 13417 RetTy = BSI->ReturnType; 13418 13419 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 13420 QualType BlockTy; 13421 13422 // Set the captured variables on the block. 13423 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 13424 SmallVector<BlockDecl::Capture, 4> Captures; 13425 for (Capture &Cap : BSI->Captures) { 13426 if (Cap.isThisCapture()) 13427 continue; 13428 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 13429 Cap.isNested(), Cap.getInitExpr()); 13430 Captures.push_back(NewCap); 13431 } 13432 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 13433 13434 // If the user wrote a function type in some form, try to use that. 13435 if (!BSI->FunctionType.isNull()) { 13436 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 13437 13438 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 13439 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 13440 13441 // Turn protoless block types into nullary block types. 13442 if (isa<FunctionNoProtoType>(FTy)) { 13443 FunctionProtoType::ExtProtoInfo EPI; 13444 EPI.ExtInfo = Ext; 13445 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13446 13447 // Otherwise, if we don't need to change anything about the function type, 13448 // preserve its sugar structure. 13449 } else if (FTy->getReturnType() == RetTy && 13450 (!NoReturn || FTy->getNoReturnAttr())) { 13451 BlockTy = BSI->FunctionType; 13452 13453 // Otherwise, make the minimal modifications to the function type. 13454 } else { 13455 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 13456 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13457 EPI.TypeQuals = 0; // FIXME: silently? 13458 EPI.ExtInfo = Ext; 13459 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 13460 } 13461 13462 // If we don't have a function type, just build one from nothing. 13463 } else { 13464 FunctionProtoType::ExtProtoInfo EPI; 13465 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 13466 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13467 } 13468 13469 DiagnoseUnusedParameters(BSI->TheDecl->parameters()); 13470 BlockTy = Context.getBlockPointerType(BlockTy); 13471 13472 // If needed, diagnose invalid gotos and switches in the block. 13473 if (getCurFunction()->NeedsScopeChecking() && 13474 !PP.isCodeCompletionEnabled()) 13475 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 13476 13477 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 13478 13479 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13480 DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl); 13481 13482 // Try to apply the named return value optimization. We have to check again 13483 // if we can do this, though, because blocks keep return statements around 13484 // to deduce an implicit return type. 13485 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 13486 !BSI->TheDecl->isDependentContext()) 13487 computeNRVO(Body, BSI); 13488 13489 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 13490 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13491 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 13492 13493 // If the block isn't obviously global, i.e. it captures anything at 13494 // all, then we need to do a few things in the surrounding context: 13495 if (Result->getBlockDecl()->hasCaptures()) { 13496 // First, this expression has a new cleanup object. 13497 ExprCleanupObjects.push_back(Result->getBlockDecl()); 13498 Cleanup.setExprNeedsCleanups(true); 13499 13500 // It also gets a branch-protected scope if any of the captured 13501 // variables needs destruction. 13502 for (const auto &CI : Result->getBlockDecl()->captures()) { 13503 const VarDecl *var = CI.getVariable(); 13504 if (var->getType().isDestructedType() != QualType::DK_none) { 13505 setFunctionHasBranchProtectedScope(); 13506 break; 13507 } 13508 } 13509 } 13510 13511 return Result; 13512 } 13513 13514 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 13515 SourceLocation RPLoc) { 13516 TypeSourceInfo *TInfo; 13517 GetTypeFromParser(Ty, &TInfo); 13518 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 13519 } 13520 13521 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 13522 Expr *E, TypeSourceInfo *TInfo, 13523 SourceLocation RPLoc) { 13524 Expr *OrigExpr = E; 13525 bool IsMS = false; 13526 13527 // CUDA device code does not support varargs. 13528 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 13529 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13530 CUDAFunctionTarget T = IdentifyCUDATarget(F); 13531 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 13532 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 13533 } 13534 } 13535 13536 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 13537 // as Microsoft ABI on an actual Microsoft platform, where 13538 // __builtin_ms_va_list and __builtin_va_list are the same.) 13539 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 13540 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 13541 QualType MSVaListType = Context.getBuiltinMSVaListType(); 13542 if (Context.hasSameType(MSVaListType, E->getType())) { 13543 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13544 return ExprError(); 13545 IsMS = true; 13546 } 13547 } 13548 13549 // Get the va_list type 13550 QualType VaListType = Context.getBuiltinVaListType(); 13551 if (!IsMS) { 13552 if (VaListType->isArrayType()) { 13553 // Deal with implicit array decay; for example, on x86-64, 13554 // va_list is an array, but it's supposed to decay to 13555 // a pointer for va_arg. 13556 VaListType = Context.getArrayDecayedType(VaListType); 13557 // Make sure the input expression also decays appropriately. 13558 ExprResult Result = UsualUnaryConversions(E); 13559 if (Result.isInvalid()) 13560 return ExprError(); 13561 E = Result.get(); 13562 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 13563 // If va_list is a record type and we are compiling in C++ mode, 13564 // check the argument using reference binding. 13565 InitializedEntity Entity = InitializedEntity::InitializeParameter( 13566 Context, Context.getLValueReferenceType(VaListType), false); 13567 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 13568 if (Init.isInvalid()) 13569 return ExprError(); 13570 E = Init.getAs<Expr>(); 13571 } else { 13572 // Otherwise, the va_list argument must be an l-value because 13573 // it is modified by va_arg. 13574 if (!E->isTypeDependent() && 13575 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13576 return ExprError(); 13577 } 13578 } 13579 13580 if (!IsMS && !E->isTypeDependent() && 13581 !Context.hasSameType(VaListType, E->getType())) 13582 return ExprError( 13583 Diag(E->getBeginLoc(), 13584 diag::err_first_argument_to_va_arg_not_of_type_va_list) 13585 << OrigExpr->getType() << E->getSourceRange()); 13586 13587 if (!TInfo->getType()->isDependentType()) { 13588 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 13589 diag::err_second_parameter_to_va_arg_incomplete, 13590 TInfo->getTypeLoc())) 13591 return ExprError(); 13592 13593 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 13594 TInfo->getType(), 13595 diag::err_second_parameter_to_va_arg_abstract, 13596 TInfo->getTypeLoc())) 13597 return ExprError(); 13598 13599 if (!TInfo->getType().isPODType(Context)) { 13600 Diag(TInfo->getTypeLoc().getBeginLoc(), 13601 TInfo->getType()->isObjCLifetimeType() 13602 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 13603 : diag::warn_second_parameter_to_va_arg_not_pod) 13604 << TInfo->getType() 13605 << TInfo->getTypeLoc().getSourceRange(); 13606 } 13607 13608 // Check for va_arg where arguments of the given type will be promoted 13609 // (i.e. this va_arg is guaranteed to have undefined behavior). 13610 QualType PromoteType; 13611 if (TInfo->getType()->isPromotableIntegerType()) { 13612 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 13613 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 13614 PromoteType = QualType(); 13615 } 13616 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 13617 PromoteType = Context.DoubleTy; 13618 if (!PromoteType.isNull()) 13619 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 13620 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 13621 << TInfo->getType() 13622 << PromoteType 13623 << TInfo->getTypeLoc().getSourceRange()); 13624 } 13625 13626 QualType T = TInfo->getType().getNonLValueExprType(Context); 13627 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 13628 } 13629 13630 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 13631 // The type of __null will be int or long, depending on the size of 13632 // pointers on the target. 13633 QualType Ty; 13634 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 13635 if (pw == Context.getTargetInfo().getIntWidth()) 13636 Ty = Context.IntTy; 13637 else if (pw == Context.getTargetInfo().getLongWidth()) 13638 Ty = Context.LongTy; 13639 else if (pw == Context.getTargetInfo().getLongLongWidth()) 13640 Ty = Context.LongLongTy; 13641 else { 13642 llvm_unreachable("I don't know size of pointer!"); 13643 } 13644 13645 return new (Context) GNUNullExpr(Ty, TokenLoc); 13646 } 13647 13648 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 13649 bool Diagnose) { 13650 if (!getLangOpts().ObjC1) 13651 return false; 13652 13653 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 13654 if (!PT) 13655 return false; 13656 13657 if (!PT->isObjCIdType()) { 13658 // Check if the destination is the 'NSString' interface. 13659 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 13660 if (!ID || !ID->getIdentifier()->isStr("NSString")) 13661 return false; 13662 } 13663 13664 // Ignore any parens, implicit casts (should only be 13665 // array-to-pointer decays), and not-so-opaque values. The last is 13666 // important for making this trigger for property assignments. 13667 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 13668 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 13669 if (OV->getSourceExpr()) 13670 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 13671 13672 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 13673 if (!SL || !SL->isAscii()) 13674 return false; 13675 if (Diagnose) { 13676 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 13677 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 13678 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 13679 } 13680 return true; 13681 } 13682 13683 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 13684 const Expr *SrcExpr) { 13685 if (!DstType->isFunctionPointerType() || 13686 !SrcExpr->getType()->isFunctionType()) 13687 return false; 13688 13689 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 13690 if (!DRE) 13691 return false; 13692 13693 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13694 if (!FD) 13695 return false; 13696 13697 return !S.checkAddressOfFunctionIsAvailable(FD, 13698 /*Complain=*/true, 13699 SrcExpr->getBeginLoc()); 13700 } 13701 13702 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 13703 SourceLocation Loc, 13704 QualType DstType, QualType SrcType, 13705 Expr *SrcExpr, AssignmentAction Action, 13706 bool *Complained) { 13707 if (Complained) 13708 *Complained = false; 13709 13710 // Decode the result (notice that AST's are still created for extensions). 13711 bool CheckInferredResultType = false; 13712 bool isInvalid = false; 13713 unsigned DiagKind = 0; 13714 FixItHint Hint; 13715 ConversionFixItGenerator ConvHints; 13716 bool MayHaveConvFixit = false; 13717 bool MayHaveFunctionDiff = false; 13718 const ObjCInterfaceDecl *IFace = nullptr; 13719 const ObjCProtocolDecl *PDecl = nullptr; 13720 13721 switch (ConvTy) { 13722 case Compatible: 13723 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 13724 return false; 13725 13726 case PointerToInt: 13727 DiagKind = diag::ext_typecheck_convert_pointer_int; 13728 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13729 MayHaveConvFixit = true; 13730 break; 13731 case IntToPointer: 13732 DiagKind = diag::ext_typecheck_convert_int_pointer; 13733 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13734 MayHaveConvFixit = true; 13735 break; 13736 case IncompatiblePointer: 13737 if (Action == AA_Passing_CFAudited) 13738 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 13739 else if (SrcType->isFunctionPointerType() && 13740 DstType->isFunctionPointerType()) 13741 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 13742 else 13743 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 13744 13745 CheckInferredResultType = DstType->isObjCObjectPointerType() && 13746 SrcType->isObjCObjectPointerType(); 13747 if (Hint.isNull() && !CheckInferredResultType) { 13748 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13749 } 13750 else if (CheckInferredResultType) { 13751 SrcType = SrcType.getUnqualifiedType(); 13752 DstType = DstType.getUnqualifiedType(); 13753 } 13754 MayHaveConvFixit = true; 13755 break; 13756 case IncompatiblePointerSign: 13757 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 13758 break; 13759 case FunctionVoidPointer: 13760 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 13761 break; 13762 case IncompatiblePointerDiscardsQualifiers: { 13763 // Perform array-to-pointer decay if necessary. 13764 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 13765 13766 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 13767 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 13768 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 13769 DiagKind = diag::err_typecheck_incompatible_address_space; 13770 break; 13771 13772 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 13773 DiagKind = diag::err_typecheck_incompatible_ownership; 13774 break; 13775 } 13776 13777 llvm_unreachable("unknown error case for discarding qualifiers!"); 13778 // fallthrough 13779 } 13780 case CompatiblePointerDiscardsQualifiers: 13781 // If the qualifiers lost were because we were applying the 13782 // (deprecated) C++ conversion from a string literal to a char* 13783 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 13784 // Ideally, this check would be performed in 13785 // checkPointerTypesForAssignment. However, that would require a 13786 // bit of refactoring (so that the second argument is an 13787 // expression, rather than a type), which should be done as part 13788 // of a larger effort to fix checkPointerTypesForAssignment for 13789 // C++ semantics. 13790 if (getLangOpts().CPlusPlus && 13791 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 13792 return false; 13793 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 13794 break; 13795 case IncompatibleNestedPointerQualifiers: 13796 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 13797 break; 13798 case IntToBlockPointer: 13799 DiagKind = diag::err_int_to_block_pointer; 13800 break; 13801 case IncompatibleBlockPointer: 13802 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 13803 break; 13804 case IncompatibleObjCQualifiedId: { 13805 if (SrcType->isObjCQualifiedIdType()) { 13806 const ObjCObjectPointerType *srcOPT = 13807 SrcType->getAs<ObjCObjectPointerType>(); 13808 for (auto *srcProto : srcOPT->quals()) { 13809 PDecl = srcProto; 13810 break; 13811 } 13812 if (const ObjCInterfaceType *IFaceT = 13813 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13814 IFace = IFaceT->getDecl(); 13815 } 13816 else if (DstType->isObjCQualifiedIdType()) { 13817 const ObjCObjectPointerType *dstOPT = 13818 DstType->getAs<ObjCObjectPointerType>(); 13819 for (auto *dstProto : dstOPT->quals()) { 13820 PDecl = dstProto; 13821 break; 13822 } 13823 if (const ObjCInterfaceType *IFaceT = 13824 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 13825 IFace = IFaceT->getDecl(); 13826 } 13827 DiagKind = diag::warn_incompatible_qualified_id; 13828 break; 13829 } 13830 case IncompatibleVectors: 13831 DiagKind = diag::warn_incompatible_vectors; 13832 break; 13833 case IncompatibleObjCWeakRef: 13834 DiagKind = diag::err_arc_weak_unavailable_assign; 13835 break; 13836 case Incompatible: 13837 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 13838 if (Complained) 13839 *Complained = true; 13840 return true; 13841 } 13842 13843 DiagKind = diag::err_typecheck_convert_incompatible; 13844 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13845 MayHaveConvFixit = true; 13846 isInvalid = true; 13847 MayHaveFunctionDiff = true; 13848 break; 13849 } 13850 13851 QualType FirstType, SecondType; 13852 switch (Action) { 13853 case AA_Assigning: 13854 case AA_Initializing: 13855 // The destination type comes first. 13856 FirstType = DstType; 13857 SecondType = SrcType; 13858 break; 13859 13860 case AA_Returning: 13861 case AA_Passing: 13862 case AA_Passing_CFAudited: 13863 case AA_Converting: 13864 case AA_Sending: 13865 case AA_Casting: 13866 // The source type comes first. 13867 FirstType = SrcType; 13868 SecondType = DstType; 13869 break; 13870 } 13871 13872 PartialDiagnostic FDiag = PDiag(DiagKind); 13873 if (Action == AA_Passing_CFAudited) 13874 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 13875 else 13876 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 13877 13878 // If we can fix the conversion, suggest the FixIts. 13879 assert(ConvHints.isNull() || Hint.isNull()); 13880 if (!ConvHints.isNull()) { 13881 for (FixItHint &H : ConvHints.Hints) 13882 FDiag << H; 13883 } else { 13884 FDiag << Hint; 13885 } 13886 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 13887 13888 if (MayHaveFunctionDiff) 13889 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 13890 13891 Diag(Loc, FDiag); 13892 if (DiagKind == diag::warn_incompatible_qualified_id && 13893 PDecl && IFace && !IFace->hasDefinition()) 13894 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 13895 << IFace << PDecl; 13896 13897 if (SecondType == Context.OverloadTy) 13898 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 13899 FirstType, /*TakingAddress=*/true); 13900 13901 if (CheckInferredResultType) 13902 EmitRelatedResultTypeNote(SrcExpr); 13903 13904 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 13905 EmitRelatedResultTypeNoteForReturn(DstType); 13906 13907 if (Complained) 13908 *Complained = true; 13909 return isInvalid; 13910 } 13911 13912 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13913 llvm::APSInt *Result) { 13914 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 13915 public: 13916 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13917 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 13918 } 13919 } Diagnoser; 13920 13921 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 13922 } 13923 13924 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 13925 llvm::APSInt *Result, 13926 unsigned DiagID, 13927 bool AllowFold) { 13928 class IDDiagnoser : public VerifyICEDiagnoser { 13929 unsigned DiagID; 13930 13931 public: 13932 IDDiagnoser(unsigned DiagID) 13933 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 13934 13935 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 13936 S.Diag(Loc, DiagID) << SR; 13937 } 13938 } Diagnoser(DiagID); 13939 13940 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 13941 } 13942 13943 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 13944 SourceRange SR) { 13945 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 13946 } 13947 13948 ExprResult 13949 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 13950 VerifyICEDiagnoser &Diagnoser, 13951 bool AllowFold) { 13952 SourceLocation DiagLoc = E->getBeginLoc(); 13953 13954 if (getLangOpts().CPlusPlus11) { 13955 // C++11 [expr.const]p5: 13956 // If an expression of literal class type is used in a context where an 13957 // integral constant expression is required, then that class type shall 13958 // have a single non-explicit conversion function to an integral or 13959 // unscoped enumeration type 13960 ExprResult Converted; 13961 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 13962 public: 13963 CXX11ConvertDiagnoser(bool Silent) 13964 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 13965 Silent, true) {} 13966 13967 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 13968 QualType T) override { 13969 return S.Diag(Loc, diag::err_ice_not_integral) << T; 13970 } 13971 13972 SemaDiagnosticBuilder diagnoseIncomplete( 13973 Sema &S, SourceLocation Loc, QualType T) override { 13974 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 13975 } 13976 13977 SemaDiagnosticBuilder diagnoseExplicitConv( 13978 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 13979 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 13980 } 13981 13982 SemaDiagnosticBuilder noteExplicitConv( 13983 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13984 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13985 << ConvTy->isEnumeralType() << ConvTy; 13986 } 13987 13988 SemaDiagnosticBuilder diagnoseAmbiguous( 13989 Sema &S, SourceLocation Loc, QualType T) override { 13990 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 13991 } 13992 13993 SemaDiagnosticBuilder noteAmbiguous( 13994 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 13995 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 13996 << ConvTy->isEnumeralType() << ConvTy; 13997 } 13998 13999 SemaDiagnosticBuilder diagnoseConversion( 14000 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14001 llvm_unreachable("conversion functions are permitted"); 14002 } 14003 } ConvertDiagnoser(Diagnoser.Suppress); 14004 14005 Converted = PerformContextualImplicitConversion(DiagLoc, E, 14006 ConvertDiagnoser); 14007 if (Converted.isInvalid()) 14008 return Converted; 14009 E = Converted.get(); 14010 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 14011 return ExprError(); 14012 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 14013 // An ICE must be of integral or unscoped enumeration type. 14014 if (!Diagnoser.Suppress) 14015 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14016 return ExprError(); 14017 } 14018 14019 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 14020 // in the non-ICE case. 14021 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 14022 if (Result) 14023 *Result = E->EvaluateKnownConstInt(Context); 14024 return E; 14025 } 14026 14027 Expr::EvalResult EvalResult; 14028 SmallVector<PartialDiagnosticAt, 8> Notes; 14029 EvalResult.Diag = &Notes; 14030 14031 // Try to evaluate the expression, and produce diagnostics explaining why it's 14032 // not a constant expression as a side-effect. 14033 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 14034 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 14035 14036 // In C++11, we can rely on diagnostics being produced for any expression 14037 // which is not a constant expression. If no diagnostics were produced, then 14038 // this is a constant expression. 14039 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 14040 if (Result) 14041 *Result = EvalResult.Val.getInt(); 14042 return E; 14043 } 14044 14045 // If our only note is the usual "invalid subexpression" note, just point 14046 // the caret at its location rather than producing an essentially 14047 // redundant note. 14048 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 14049 diag::note_invalid_subexpr_in_const_expr) { 14050 DiagLoc = Notes[0].first; 14051 Notes.clear(); 14052 } 14053 14054 if (!Folded || !AllowFold) { 14055 if (!Diagnoser.Suppress) { 14056 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14057 for (const PartialDiagnosticAt &Note : Notes) 14058 Diag(Note.first, Note.second); 14059 } 14060 14061 return ExprError(); 14062 } 14063 14064 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 14065 for (const PartialDiagnosticAt &Note : Notes) 14066 Diag(Note.first, Note.second); 14067 14068 if (Result) 14069 *Result = EvalResult.Val.getInt(); 14070 return E; 14071 } 14072 14073 namespace { 14074 // Handle the case where we conclude a expression which we speculatively 14075 // considered to be unevaluated is actually evaluated. 14076 class TransformToPE : public TreeTransform<TransformToPE> { 14077 typedef TreeTransform<TransformToPE> BaseTransform; 14078 14079 public: 14080 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 14081 14082 // Make sure we redo semantic analysis 14083 bool AlwaysRebuild() { return true; } 14084 14085 // Make sure we handle LabelStmts correctly. 14086 // FIXME: This does the right thing, but maybe we need a more general 14087 // fix to TreeTransform? 14088 StmtResult TransformLabelStmt(LabelStmt *S) { 14089 S->getDecl()->setStmt(nullptr); 14090 return BaseTransform::TransformLabelStmt(S); 14091 } 14092 14093 // We need to special-case DeclRefExprs referring to FieldDecls which 14094 // are not part of a member pointer formation; normal TreeTransforming 14095 // doesn't catch this case because of the way we represent them in the AST. 14096 // FIXME: This is a bit ugly; is it really the best way to handle this 14097 // case? 14098 // 14099 // Error on DeclRefExprs referring to FieldDecls. 14100 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 14101 if (isa<FieldDecl>(E->getDecl()) && 14102 !SemaRef.isUnevaluatedContext()) 14103 return SemaRef.Diag(E->getLocation(), 14104 diag::err_invalid_non_static_member_use) 14105 << E->getDecl() << E->getSourceRange(); 14106 14107 return BaseTransform::TransformDeclRefExpr(E); 14108 } 14109 14110 // Exception: filter out member pointer formation 14111 ExprResult TransformUnaryOperator(UnaryOperator *E) { 14112 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 14113 return E; 14114 14115 return BaseTransform::TransformUnaryOperator(E); 14116 } 14117 14118 ExprResult TransformLambdaExpr(LambdaExpr *E) { 14119 // Lambdas never need to be transformed. 14120 return E; 14121 } 14122 }; 14123 } 14124 14125 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 14126 assert(isUnevaluatedContext() && 14127 "Should only transform unevaluated expressions"); 14128 ExprEvalContexts.back().Context = 14129 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 14130 if (isUnevaluatedContext()) 14131 return E; 14132 return TransformToPE(*this).TransformExpr(E); 14133 } 14134 14135 void 14136 Sema::PushExpressionEvaluationContext( 14137 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 14138 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 14139 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 14140 LambdaContextDecl, ExprContext); 14141 Cleanup.reset(); 14142 if (!MaybeODRUseExprs.empty()) 14143 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 14144 } 14145 14146 void 14147 Sema::PushExpressionEvaluationContext( 14148 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 14149 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 14150 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 14151 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 14152 } 14153 14154 void Sema::PopExpressionEvaluationContext() { 14155 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 14156 unsigned NumTypos = Rec.NumTypos; 14157 14158 if (!Rec.Lambdas.empty()) { 14159 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 14160 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 14161 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 14162 unsigned D; 14163 if (Rec.isUnevaluated()) { 14164 // C++11 [expr.prim.lambda]p2: 14165 // A lambda-expression shall not appear in an unevaluated operand 14166 // (Clause 5). 14167 D = diag::err_lambda_unevaluated_operand; 14168 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 14169 // C++1y [expr.const]p2: 14170 // A conditional-expression e is a core constant expression unless the 14171 // evaluation of e, following the rules of the abstract machine, would 14172 // evaluate [...] a lambda-expression. 14173 D = diag::err_lambda_in_constant_expression; 14174 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 14175 // C++17 [expr.prim.lamda]p2: 14176 // A lambda-expression shall not appear [...] in a template-argument. 14177 D = diag::err_lambda_in_invalid_context; 14178 } else 14179 llvm_unreachable("Couldn't infer lambda error message."); 14180 14181 for (const auto *L : Rec.Lambdas) 14182 Diag(L->getBeginLoc(), D); 14183 } else { 14184 // Mark the capture expressions odr-used. This was deferred 14185 // during lambda expression creation. 14186 for (auto *Lambda : Rec.Lambdas) { 14187 for (auto *C : Lambda->capture_inits()) 14188 MarkDeclarationsReferencedInExpr(C); 14189 } 14190 } 14191 } 14192 14193 // When are coming out of an unevaluated context, clear out any 14194 // temporaries that we may have created as part of the evaluation of 14195 // the expression in that context: they aren't relevant because they 14196 // will never be constructed. 14197 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 14198 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 14199 ExprCleanupObjects.end()); 14200 Cleanup = Rec.ParentCleanup; 14201 CleanupVarDeclMarking(); 14202 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 14203 // Otherwise, merge the contexts together. 14204 } else { 14205 Cleanup.mergeFrom(Rec.ParentCleanup); 14206 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 14207 Rec.SavedMaybeODRUseExprs.end()); 14208 } 14209 14210 // Pop the current expression evaluation context off the stack. 14211 ExprEvalContexts.pop_back(); 14212 14213 if (!ExprEvalContexts.empty()) 14214 ExprEvalContexts.back().NumTypos += NumTypos; 14215 else 14216 assert(NumTypos == 0 && "There are outstanding typos after popping the " 14217 "last ExpressionEvaluationContextRecord"); 14218 } 14219 14220 void Sema::DiscardCleanupsInEvaluationContext() { 14221 ExprCleanupObjects.erase( 14222 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 14223 ExprCleanupObjects.end()); 14224 Cleanup.reset(); 14225 MaybeODRUseExprs.clear(); 14226 } 14227 14228 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 14229 if (!E->getType()->isVariablyModifiedType()) 14230 return E; 14231 return TransformToPotentiallyEvaluated(E); 14232 } 14233 14234 /// Are we within a context in which some evaluation could be performed (be it 14235 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 14236 /// captured by C++'s idea of an "unevaluated context". 14237 static bool isEvaluatableContext(Sema &SemaRef) { 14238 switch (SemaRef.ExprEvalContexts.back().Context) { 14239 case Sema::ExpressionEvaluationContext::Unevaluated: 14240 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14241 // Expressions in this context are never evaluated. 14242 return false; 14243 14244 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14245 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14246 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14247 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14248 // Expressions in this context could be evaluated. 14249 return true; 14250 14251 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14252 // Referenced declarations will only be used if the construct in the 14253 // containing expression is used, at which point we'll be given another 14254 // turn to mark them. 14255 return false; 14256 } 14257 llvm_unreachable("Invalid context"); 14258 } 14259 14260 /// Are we within a context in which references to resolved functions or to 14261 /// variables result in odr-use? 14262 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 14263 // An expression in a template is not really an expression until it's been 14264 // instantiated, so it doesn't trigger odr-use. 14265 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 14266 return false; 14267 14268 switch (SemaRef.ExprEvalContexts.back().Context) { 14269 case Sema::ExpressionEvaluationContext::Unevaluated: 14270 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14271 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14272 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14273 return false; 14274 14275 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14276 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14277 return true; 14278 14279 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14280 return false; 14281 } 14282 llvm_unreachable("Invalid context"); 14283 } 14284 14285 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 14286 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 14287 return Func->isConstexpr() && 14288 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 14289 } 14290 14291 /// Mark a function referenced, and check whether it is odr-used 14292 /// (C++ [basic.def.odr]p2, C99 6.9p3) 14293 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 14294 bool MightBeOdrUse) { 14295 assert(Func && "No function?"); 14296 14297 Func->setReferenced(); 14298 14299 // C++11 [basic.def.odr]p3: 14300 // A function whose name appears as a potentially-evaluated expression is 14301 // odr-used if it is the unique lookup result or the selected member of a 14302 // set of overloaded functions [...]. 14303 // 14304 // We (incorrectly) mark overload resolution as an unevaluated context, so we 14305 // can just check that here. 14306 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 14307 14308 // Determine whether we require a function definition to exist, per 14309 // C++11 [temp.inst]p3: 14310 // Unless a function template specialization has been explicitly 14311 // instantiated or explicitly specialized, the function template 14312 // specialization is implicitly instantiated when the specialization is 14313 // referenced in a context that requires a function definition to exist. 14314 // 14315 // That is either when this is an odr-use, or when a usage of a constexpr 14316 // function occurs within an evaluatable context. 14317 bool NeedDefinition = 14318 OdrUse || (isEvaluatableContext(*this) && 14319 isImplicitlyDefinableConstexprFunction(Func)); 14320 14321 // C++14 [temp.expl.spec]p6: 14322 // If a template [...] is explicitly specialized then that specialization 14323 // shall be declared before the first use of that specialization that would 14324 // cause an implicit instantiation to take place, in every translation unit 14325 // in which such a use occurs 14326 if (NeedDefinition && 14327 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 14328 Func->getMemberSpecializationInfo())) 14329 checkSpecializationVisibility(Loc, Func); 14330 14331 // C++14 [except.spec]p17: 14332 // An exception-specification is considered to be needed when: 14333 // - the function is odr-used or, if it appears in an unevaluated operand, 14334 // would be odr-used if the expression were potentially-evaluated; 14335 // 14336 // Note, we do this even if MightBeOdrUse is false. That indicates that the 14337 // function is a pure virtual function we're calling, and in that case the 14338 // function was selected by overload resolution and we need to resolve its 14339 // exception specification for a different reason. 14340 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 14341 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 14342 ResolveExceptionSpec(Loc, FPT); 14343 14344 // If we don't need to mark the function as used, and we don't need to 14345 // try to provide a definition, there's nothing more to do. 14346 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 14347 (!NeedDefinition || Func->getBody())) 14348 return; 14349 14350 // Note that this declaration has been used. 14351 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 14352 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 14353 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 14354 if (Constructor->isDefaultConstructor()) { 14355 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 14356 return; 14357 DefineImplicitDefaultConstructor(Loc, Constructor); 14358 } else if (Constructor->isCopyConstructor()) { 14359 DefineImplicitCopyConstructor(Loc, Constructor); 14360 } else if (Constructor->isMoveConstructor()) { 14361 DefineImplicitMoveConstructor(Loc, Constructor); 14362 } 14363 } else if (Constructor->getInheritedConstructor()) { 14364 DefineInheritingConstructor(Loc, Constructor); 14365 } 14366 } else if (CXXDestructorDecl *Destructor = 14367 dyn_cast<CXXDestructorDecl>(Func)) { 14368 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 14369 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 14370 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 14371 return; 14372 DefineImplicitDestructor(Loc, Destructor); 14373 } 14374 if (Destructor->isVirtual() && getLangOpts().AppleKext) 14375 MarkVTableUsed(Loc, Destructor->getParent()); 14376 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 14377 if (MethodDecl->isOverloadedOperator() && 14378 MethodDecl->getOverloadedOperator() == OO_Equal) { 14379 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 14380 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 14381 if (MethodDecl->isCopyAssignmentOperator()) 14382 DefineImplicitCopyAssignment(Loc, MethodDecl); 14383 else if (MethodDecl->isMoveAssignmentOperator()) 14384 DefineImplicitMoveAssignment(Loc, MethodDecl); 14385 } 14386 } else if (isa<CXXConversionDecl>(MethodDecl) && 14387 MethodDecl->getParent()->isLambda()) { 14388 CXXConversionDecl *Conversion = 14389 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 14390 if (Conversion->isLambdaToBlockPointerConversion()) 14391 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 14392 else 14393 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 14394 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 14395 MarkVTableUsed(Loc, MethodDecl->getParent()); 14396 } 14397 14398 // Recursive functions should be marked when used from another function. 14399 // FIXME: Is this really right? 14400 if (CurContext == Func) return; 14401 14402 // Implicit instantiation of function templates and member functions of 14403 // class templates. 14404 if (Func->isImplicitlyInstantiable()) { 14405 TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind(); 14406 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 14407 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 14408 if (FirstInstantiation) { 14409 PointOfInstantiation = Loc; 14410 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 14411 } else if (TSK != TSK_ImplicitInstantiation) { 14412 // Use the point of use as the point of instantiation, instead of the 14413 // point of explicit instantiation (which we track as the actual point of 14414 // instantiation). This gives better backtraces in diagnostics. 14415 PointOfInstantiation = Loc; 14416 } 14417 14418 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 14419 Func->isConstexpr()) { 14420 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 14421 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 14422 CodeSynthesisContexts.size()) 14423 PendingLocalImplicitInstantiations.push_back( 14424 std::make_pair(Func, PointOfInstantiation)); 14425 else if (Func->isConstexpr()) 14426 // Do not defer instantiations of constexpr functions, to avoid the 14427 // expression evaluator needing to call back into Sema if it sees a 14428 // call to such a function. 14429 InstantiateFunctionDefinition(PointOfInstantiation, Func); 14430 else { 14431 Func->setInstantiationIsPending(true); 14432 PendingInstantiations.push_back(std::make_pair(Func, 14433 PointOfInstantiation)); 14434 // Notify the consumer that a function was implicitly instantiated. 14435 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 14436 } 14437 } 14438 } else { 14439 // Walk redefinitions, as some of them may be instantiable. 14440 for (auto i : Func->redecls()) { 14441 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 14442 MarkFunctionReferenced(Loc, i, OdrUse); 14443 } 14444 } 14445 14446 if (!OdrUse) return; 14447 14448 // Keep track of used but undefined functions. 14449 if (!Func->isDefined()) { 14450 if (mightHaveNonExternalLinkage(Func)) 14451 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14452 else if (Func->getMostRecentDecl()->isInlined() && 14453 !LangOpts.GNUInline && 14454 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 14455 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14456 else if (isExternalWithNoLinkageType(Func)) 14457 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14458 } 14459 14460 Func->markUsed(Context); 14461 } 14462 14463 static void 14464 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 14465 ValueDecl *var, DeclContext *DC) { 14466 DeclContext *VarDC = var->getDeclContext(); 14467 14468 // If the parameter still belongs to the translation unit, then 14469 // we're actually just using one parameter in the declaration of 14470 // the next. 14471 if (isa<ParmVarDecl>(var) && 14472 isa<TranslationUnitDecl>(VarDC)) 14473 return; 14474 14475 // For C code, don't diagnose about capture if we're not actually in code 14476 // right now; it's impossible to write a non-constant expression outside of 14477 // function context, so we'll get other (more useful) diagnostics later. 14478 // 14479 // For C++, things get a bit more nasty... it would be nice to suppress this 14480 // diagnostic for certain cases like using a local variable in an array bound 14481 // for a member of a local class, but the correct predicate is not obvious. 14482 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 14483 return; 14484 14485 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 14486 unsigned ContextKind = 3; // unknown 14487 if (isa<CXXMethodDecl>(VarDC) && 14488 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 14489 ContextKind = 2; 14490 } else if (isa<FunctionDecl>(VarDC)) { 14491 ContextKind = 0; 14492 } else if (isa<BlockDecl>(VarDC)) { 14493 ContextKind = 1; 14494 } 14495 14496 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 14497 << var << ValueKind << ContextKind << VarDC; 14498 S.Diag(var->getLocation(), diag::note_entity_declared_at) 14499 << var; 14500 14501 // FIXME: Add additional diagnostic info about class etc. which prevents 14502 // capture. 14503 } 14504 14505 14506 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 14507 bool &SubCapturesAreNested, 14508 QualType &CaptureType, 14509 QualType &DeclRefType) { 14510 // Check whether we've already captured it. 14511 if (CSI->CaptureMap.count(Var)) { 14512 // If we found a capture, any subcaptures are nested. 14513 SubCapturesAreNested = true; 14514 14515 // Retrieve the capture type for this variable. 14516 CaptureType = CSI->getCapture(Var).getCaptureType(); 14517 14518 // Compute the type of an expression that refers to this variable. 14519 DeclRefType = CaptureType.getNonReferenceType(); 14520 14521 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 14522 // are mutable in the sense that user can change their value - they are 14523 // private instances of the captured declarations. 14524 const Capture &Cap = CSI->getCapture(Var); 14525 if (Cap.isCopyCapture() && 14526 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 14527 !(isa<CapturedRegionScopeInfo>(CSI) && 14528 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 14529 DeclRefType.addConst(); 14530 return true; 14531 } 14532 return false; 14533 } 14534 14535 // Only block literals, captured statements, and lambda expressions can 14536 // capture; other scopes don't work. 14537 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 14538 SourceLocation Loc, 14539 const bool Diagnose, Sema &S) { 14540 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 14541 return getLambdaAwareParentOfDeclContext(DC); 14542 else if (Var->hasLocalStorage()) { 14543 if (Diagnose) 14544 diagnoseUncapturableValueReference(S, Loc, Var, DC); 14545 } 14546 return nullptr; 14547 } 14548 14549 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14550 // certain types of variables (unnamed, variably modified types etc.) 14551 // so check for eligibility. 14552 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 14553 SourceLocation Loc, 14554 const bool Diagnose, Sema &S) { 14555 14556 bool IsBlock = isa<BlockScopeInfo>(CSI); 14557 bool IsLambda = isa<LambdaScopeInfo>(CSI); 14558 14559 // Lambdas are not allowed to capture unnamed variables 14560 // (e.g. anonymous unions). 14561 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 14562 // assuming that's the intent. 14563 if (IsLambda && !Var->getDeclName()) { 14564 if (Diagnose) { 14565 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 14566 S.Diag(Var->getLocation(), diag::note_declared_at); 14567 } 14568 return false; 14569 } 14570 14571 // Prohibit variably-modified types in blocks; they're difficult to deal with. 14572 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 14573 if (Diagnose) { 14574 S.Diag(Loc, diag::err_ref_vm_type); 14575 S.Diag(Var->getLocation(), diag::note_previous_decl) 14576 << Var->getDeclName(); 14577 } 14578 return false; 14579 } 14580 // Prohibit structs with flexible array members too. 14581 // We cannot capture what is in the tail end of the struct. 14582 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 14583 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 14584 if (Diagnose) { 14585 if (IsBlock) 14586 S.Diag(Loc, diag::err_ref_flexarray_type); 14587 else 14588 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 14589 << Var->getDeclName(); 14590 S.Diag(Var->getLocation(), diag::note_previous_decl) 14591 << Var->getDeclName(); 14592 } 14593 return false; 14594 } 14595 } 14596 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14597 // Lambdas and captured statements are not allowed to capture __block 14598 // variables; they don't support the expected semantics. 14599 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 14600 if (Diagnose) { 14601 S.Diag(Loc, diag::err_capture_block_variable) 14602 << Var->getDeclName() << !IsLambda; 14603 S.Diag(Var->getLocation(), diag::note_previous_decl) 14604 << Var->getDeclName(); 14605 } 14606 return false; 14607 } 14608 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 14609 if (S.getLangOpts().OpenCL && IsBlock && 14610 Var->getType()->isBlockPointerType()) { 14611 if (Diagnose) 14612 S.Diag(Loc, diag::err_opencl_block_ref_block); 14613 return false; 14614 } 14615 14616 return true; 14617 } 14618 14619 // Returns true if the capture by block was successful. 14620 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 14621 SourceLocation Loc, 14622 const bool BuildAndDiagnose, 14623 QualType &CaptureType, 14624 QualType &DeclRefType, 14625 const bool Nested, 14626 Sema &S) { 14627 Expr *CopyExpr = nullptr; 14628 bool ByRef = false; 14629 14630 // Blocks are not allowed to capture arrays. 14631 if (CaptureType->isArrayType()) { 14632 if (BuildAndDiagnose) { 14633 S.Diag(Loc, diag::err_ref_array_type); 14634 S.Diag(Var->getLocation(), diag::note_previous_decl) 14635 << Var->getDeclName(); 14636 } 14637 return false; 14638 } 14639 14640 // Forbid the block-capture of autoreleasing variables. 14641 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14642 if (BuildAndDiagnose) { 14643 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 14644 << /*block*/ 0; 14645 S.Diag(Var->getLocation(), diag::note_previous_decl) 14646 << Var->getDeclName(); 14647 } 14648 return false; 14649 } 14650 14651 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 14652 if (const auto *PT = CaptureType->getAs<PointerType>()) { 14653 // This function finds out whether there is an AttributedType of kind 14654 // attr::ObjCOwnership in Ty. The existence of AttributedType of kind 14655 // attr::ObjCOwnership implies __autoreleasing was explicitly specified 14656 // rather than being added implicitly by the compiler. 14657 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 14658 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 14659 if (AttrTy->getAttrKind() == attr::ObjCOwnership) 14660 return true; 14661 14662 // Peel off AttributedTypes that are not of kind ObjCOwnership. 14663 Ty = AttrTy->getModifiedType(); 14664 } 14665 14666 return false; 14667 }; 14668 14669 QualType PointeeTy = PT->getPointeeType(); 14670 14671 if (PointeeTy->getAs<ObjCObjectPointerType>() && 14672 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 14673 !IsObjCOwnershipAttributedType(PointeeTy)) { 14674 if (BuildAndDiagnose) { 14675 SourceLocation VarLoc = Var->getLocation(); 14676 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 14677 S.Diag(VarLoc, diag::note_declare_parameter_strong); 14678 } 14679 } 14680 } 14681 14682 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14683 if (HasBlocksAttr || CaptureType->isReferenceType() || 14684 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 14685 // Block capture by reference does not change the capture or 14686 // declaration reference types. 14687 ByRef = true; 14688 } else { 14689 // Block capture by copy introduces 'const'. 14690 CaptureType = CaptureType.getNonReferenceType().withConst(); 14691 DeclRefType = CaptureType; 14692 14693 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 14694 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 14695 // The capture logic needs the destructor, so make sure we mark it. 14696 // Usually this is unnecessary because most local variables have 14697 // their destructors marked at declaration time, but parameters are 14698 // an exception because it's technically only the call site that 14699 // actually requires the destructor. 14700 if (isa<ParmVarDecl>(Var)) 14701 S.FinalizeVarWithDestructor(Var, Record); 14702 14703 // Enter a new evaluation context to insulate the copy 14704 // full-expression. 14705 EnterExpressionEvaluationContext scope( 14706 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 14707 14708 // According to the blocks spec, the capture of a variable from 14709 // the stack requires a const copy constructor. This is not true 14710 // of the copy/move done to move a __block variable to the heap. 14711 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 14712 DeclRefType.withConst(), 14713 VK_LValue, Loc); 14714 14715 ExprResult Result 14716 = S.PerformCopyInitialization( 14717 InitializedEntity::InitializeBlock(Var->getLocation(), 14718 CaptureType, false), 14719 Loc, DeclRef); 14720 14721 // Build a full-expression copy expression if initialization 14722 // succeeded and used a non-trivial constructor. Recover from 14723 // errors by pretending that the copy isn't necessary. 14724 if (!Result.isInvalid() && 14725 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14726 ->isTrivial()) { 14727 Result = S.MaybeCreateExprWithCleanups(Result); 14728 CopyExpr = Result.get(); 14729 } 14730 } 14731 } 14732 } 14733 14734 // Actually capture the variable. 14735 if (BuildAndDiagnose) 14736 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 14737 SourceLocation(), CaptureType, CopyExpr); 14738 14739 return true; 14740 14741 } 14742 14743 14744 /// Capture the given variable in the captured region. 14745 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 14746 VarDecl *Var, 14747 SourceLocation Loc, 14748 const bool BuildAndDiagnose, 14749 QualType &CaptureType, 14750 QualType &DeclRefType, 14751 const bool RefersToCapturedVariable, 14752 Sema &S) { 14753 // By default, capture variables by reference. 14754 bool ByRef = true; 14755 // Using an LValue reference type is consistent with Lambdas (see below). 14756 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 14757 if (S.isOpenMPCapturedDecl(Var)) { 14758 bool HasConst = DeclRefType.isConstQualified(); 14759 DeclRefType = DeclRefType.getUnqualifiedType(); 14760 // Don't lose diagnostics about assignments to const. 14761 if (HasConst) 14762 DeclRefType.addConst(); 14763 } 14764 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 14765 } 14766 14767 if (ByRef) 14768 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14769 else 14770 CaptureType = DeclRefType; 14771 14772 Expr *CopyExpr = nullptr; 14773 if (BuildAndDiagnose) { 14774 // The current implementation assumes that all variables are captured 14775 // by references. Since there is no capture by copy, no expression 14776 // evaluation will be needed. 14777 RecordDecl *RD = RSI->TheRecordDecl; 14778 14779 FieldDecl *Field 14780 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 14781 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 14782 nullptr, false, ICIS_NoInit); 14783 Field->setImplicit(true); 14784 Field->setAccess(AS_private); 14785 RD->addDecl(Field); 14786 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) 14787 S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel); 14788 14789 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 14790 DeclRefType, VK_LValue, Loc); 14791 Var->setReferenced(true); 14792 Var->markUsed(S.Context); 14793 } 14794 14795 // Actually capture the variable. 14796 if (BuildAndDiagnose) 14797 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 14798 SourceLocation(), CaptureType, CopyExpr); 14799 14800 14801 return true; 14802 } 14803 14804 /// Create a field within the lambda class for the variable 14805 /// being captured. 14806 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 14807 QualType FieldType, QualType DeclRefType, 14808 SourceLocation Loc, 14809 bool RefersToCapturedVariable) { 14810 CXXRecordDecl *Lambda = LSI->Lambda; 14811 14812 // Build the non-static data member. 14813 FieldDecl *Field 14814 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 14815 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 14816 nullptr, false, ICIS_NoInit); 14817 Field->setImplicit(true); 14818 Field->setAccess(AS_private); 14819 Lambda->addDecl(Field); 14820 } 14821 14822 /// Capture the given variable in the lambda. 14823 static bool captureInLambda(LambdaScopeInfo *LSI, 14824 VarDecl *Var, 14825 SourceLocation Loc, 14826 const bool BuildAndDiagnose, 14827 QualType &CaptureType, 14828 QualType &DeclRefType, 14829 const bool RefersToCapturedVariable, 14830 const Sema::TryCaptureKind Kind, 14831 SourceLocation EllipsisLoc, 14832 const bool IsTopScope, 14833 Sema &S) { 14834 14835 // Determine whether we are capturing by reference or by value. 14836 bool ByRef = false; 14837 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 14838 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 14839 } else { 14840 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 14841 } 14842 14843 // Compute the type of the field that will capture this variable. 14844 if (ByRef) { 14845 // C++11 [expr.prim.lambda]p15: 14846 // An entity is captured by reference if it is implicitly or 14847 // explicitly captured but not captured by copy. It is 14848 // unspecified whether additional unnamed non-static data 14849 // members are declared in the closure type for entities 14850 // captured by reference. 14851 // 14852 // FIXME: It is not clear whether we want to build an lvalue reference 14853 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 14854 // to do the former, while EDG does the latter. Core issue 1249 will 14855 // clarify, but for now we follow GCC because it's a more permissive and 14856 // easily defensible position. 14857 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14858 } else { 14859 // C++11 [expr.prim.lambda]p14: 14860 // For each entity captured by copy, an unnamed non-static 14861 // data member is declared in the closure type. The 14862 // declaration order of these members is unspecified. The type 14863 // of such a data member is the type of the corresponding 14864 // captured entity if the entity is not a reference to an 14865 // object, or the referenced type otherwise. [Note: If the 14866 // captured entity is a reference to a function, the 14867 // corresponding data member is also a reference to a 14868 // function. - end note ] 14869 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 14870 if (!RefType->getPointeeType()->isFunctionType()) 14871 CaptureType = RefType->getPointeeType(); 14872 } 14873 14874 // Forbid the lambda copy-capture of autoreleasing variables. 14875 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14876 if (BuildAndDiagnose) { 14877 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 14878 S.Diag(Var->getLocation(), diag::note_previous_decl) 14879 << Var->getDeclName(); 14880 } 14881 return false; 14882 } 14883 14884 // Make sure that by-copy captures are of a complete and non-abstract type. 14885 if (BuildAndDiagnose) { 14886 if (!CaptureType->isDependentType() && 14887 S.RequireCompleteType(Loc, CaptureType, 14888 diag::err_capture_of_incomplete_type, 14889 Var->getDeclName())) 14890 return false; 14891 14892 if (S.RequireNonAbstractType(Loc, CaptureType, 14893 diag::err_capture_of_abstract_type)) 14894 return false; 14895 } 14896 } 14897 14898 // Capture this variable in the lambda. 14899 if (BuildAndDiagnose) 14900 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 14901 RefersToCapturedVariable); 14902 14903 // Compute the type of a reference to this captured variable. 14904 if (ByRef) 14905 DeclRefType = CaptureType.getNonReferenceType(); 14906 else { 14907 // C++ [expr.prim.lambda]p5: 14908 // The closure type for a lambda-expression has a public inline 14909 // function call operator [...]. This function call operator is 14910 // declared const (9.3.1) if and only if the lambda-expression's 14911 // parameter-declaration-clause is not followed by mutable. 14912 DeclRefType = CaptureType.getNonReferenceType(); 14913 if (!LSI->Mutable && !CaptureType->isReferenceType()) 14914 DeclRefType.addConst(); 14915 } 14916 14917 // Add the capture. 14918 if (BuildAndDiagnose) 14919 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 14920 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 14921 14922 return true; 14923 } 14924 14925 bool Sema::tryCaptureVariable( 14926 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 14927 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 14928 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 14929 // An init-capture is notionally from the context surrounding its 14930 // declaration, but its parent DC is the lambda class. 14931 DeclContext *VarDC = Var->getDeclContext(); 14932 if (Var->isInitCapture()) 14933 VarDC = VarDC->getParent(); 14934 14935 DeclContext *DC = CurContext; 14936 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 14937 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 14938 // We need to sync up the Declaration Context with the 14939 // FunctionScopeIndexToStopAt 14940 if (FunctionScopeIndexToStopAt) { 14941 unsigned FSIndex = FunctionScopes.size() - 1; 14942 while (FSIndex != MaxFunctionScopesIndex) { 14943 DC = getLambdaAwareParentOfDeclContext(DC); 14944 --FSIndex; 14945 } 14946 } 14947 14948 14949 // If the variable is declared in the current context, there is no need to 14950 // capture it. 14951 if (VarDC == DC) return true; 14952 14953 // Capture global variables if it is required to use private copy of this 14954 // variable. 14955 bool IsGlobal = !Var->hasLocalStorage(); 14956 if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var))) 14957 return true; 14958 Var = Var->getCanonicalDecl(); 14959 14960 // Walk up the stack to determine whether we can capture the variable, 14961 // performing the "simple" checks that don't depend on type. We stop when 14962 // we've either hit the declared scope of the variable or find an existing 14963 // capture of that variable. We start from the innermost capturing-entity 14964 // (the DC) and ensure that all intervening capturing-entities 14965 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 14966 // declcontext can either capture the variable or have already captured 14967 // the variable. 14968 CaptureType = Var->getType(); 14969 DeclRefType = CaptureType.getNonReferenceType(); 14970 bool Nested = false; 14971 bool Explicit = (Kind != TryCapture_Implicit); 14972 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 14973 do { 14974 // Only block literals, captured statements, and lambda expressions can 14975 // capture; other scopes don't work. 14976 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 14977 ExprLoc, 14978 BuildAndDiagnose, 14979 *this); 14980 // We need to check for the parent *first* because, if we *have* 14981 // private-captured a global variable, we need to recursively capture it in 14982 // intermediate blocks, lambdas, etc. 14983 if (!ParentDC) { 14984 if (IsGlobal) { 14985 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 14986 break; 14987 } 14988 return true; 14989 } 14990 14991 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 14992 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 14993 14994 14995 // Check whether we've already captured it. 14996 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 14997 DeclRefType)) { 14998 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 14999 break; 15000 } 15001 // If we are instantiating a generic lambda call operator body, 15002 // we do not want to capture new variables. What was captured 15003 // during either a lambdas transformation or initial parsing 15004 // should be used. 15005 if (isGenericLambdaCallOperatorSpecialization(DC)) { 15006 if (BuildAndDiagnose) { 15007 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15008 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 15009 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15010 Diag(Var->getLocation(), diag::note_previous_decl) 15011 << Var->getDeclName(); 15012 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 15013 } else 15014 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 15015 } 15016 return true; 15017 } 15018 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 15019 // certain types of variables (unnamed, variably modified types etc.) 15020 // so check for eligibility. 15021 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 15022 return true; 15023 15024 // Try to capture variable-length arrays types. 15025 if (Var->getType()->isVariablyModifiedType()) { 15026 // We're going to walk down into the type and look for VLA 15027 // expressions. 15028 QualType QTy = Var->getType(); 15029 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 15030 QTy = PVD->getOriginalType(); 15031 captureVariablyModifiedType(Context, QTy, CSI); 15032 } 15033 15034 if (getLangOpts().OpenMP) { 15035 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15036 // OpenMP private variables should not be captured in outer scope, so 15037 // just break here. Similarly, global variables that are captured in a 15038 // target region should not be captured outside the scope of the region. 15039 if (RSI->CapRegionKind == CR_OpenMP) { 15040 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 15041 auto IsTargetCap = !IsOpenMPPrivateDecl && 15042 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 15043 // When we detect target captures we are looking from inside the 15044 // target region, therefore we need to propagate the capture from the 15045 // enclosing region. Therefore, the capture is not initially nested. 15046 if (IsTargetCap) 15047 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 15048 15049 if (IsTargetCap || IsOpenMPPrivateDecl) { 15050 Nested = !IsTargetCap; 15051 DeclRefType = DeclRefType.getUnqualifiedType(); 15052 CaptureType = Context.getLValueReferenceType(DeclRefType); 15053 break; 15054 } 15055 } 15056 } 15057 } 15058 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 15059 // No capture-default, and this is not an explicit capture 15060 // so cannot capture this variable. 15061 if (BuildAndDiagnose) { 15062 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15063 Diag(Var->getLocation(), diag::note_previous_decl) 15064 << Var->getDeclName(); 15065 if (cast<LambdaScopeInfo>(CSI)->Lambda) 15066 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 15067 diag::note_lambda_decl); 15068 // FIXME: If we error out because an outer lambda can not implicitly 15069 // capture a variable that an inner lambda explicitly captures, we 15070 // should have the inner lambda do the explicit capture - because 15071 // it makes for cleaner diagnostics later. This would purely be done 15072 // so that the diagnostic does not misleadingly claim that a variable 15073 // can not be captured by a lambda implicitly even though it is captured 15074 // explicitly. Suggestion: 15075 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 15076 // at the function head 15077 // - cache the StartingDeclContext - this must be a lambda 15078 // - captureInLambda in the innermost lambda the variable. 15079 } 15080 return true; 15081 } 15082 15083 FunctionScopesIndex--; 15084 DC = ParentDC; 15085 Explicit = false; 15086 } while (!VarDC->Equals(DC)); 15087 15088 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 15089 // computing the type of the capture at each step, checking type-specific 15090 // requirements, and adding captures if requested. 15091 // If the variable had already been captured previously, we start capturing 15092 // at the lambda nested within that one. 15093 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 15094 ++I) { 15095 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 15096 15097 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 15098 if (!captureInBlock(BSI, Var, ExprLoc, 15099 BuildAndDiagnose, CaptureType, 15100 DeclRefType, Nested, *this)) 15101 return true; 15102 Nested = true; 15103 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15104 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 15105 BuildAndDiagnose, CaptureType, 15106 DeclRefType, Nested, *this)) 15107 return true; 15108 Nested = true; 15109 } else { 15110 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15111 if (!captureInLambda(LSI, Var, ExprLoc, 15112 BuildAndDiagnose, CaptureType, 15113 DeclRefType, Nested, Kind, EllipsisLoc, 15114 /*IsTopScope*/I == N - 1, *this)) 15115 return true; 15116 Nested = true; 15117 } 15118 } 15119 return false; 15120 } 15121 15122 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 15123 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 15124 QualType CaptureType; 15125 QualType DeclRefType; 15126 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 15127 /*BuildAndDiagnose=*/true, CaptureType, 15128 DeclRefType, nullptr); 15129 } 15130 15131 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 15132 QualType CaptureType; 15133 QualType DeclRefType; 15134 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15135 /*BuildAndDiagnose=*/false, CaptureType, 15136 DeclRefType, nullptr); 15137 } 15138 15139 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 15140 QualType CaptureType; 15141 QualType DeclRefType; 15142 15143 // Determine whether we can capture this variable. 15144 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15145 /*BuildAndDiagnose=*/false, CaptureType, 15146 DeclRefType, nullptr)) 15147 return QualType(); 15148 15149 return DeclRefType; 15150 } 15151 15152 15153 15154 // If either the type of the variable or the initializer is dependent, 15155 // return false. Otherwise, determine whether the variable is a constant 15156 // expression. Use this if you need to know if a variable that might or 15157 // might not be dependent is truly a constant expression. 15158 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 15159 ASTContext &Context) { 15160 15161 if (Var->getType()->isDependentType()) 15162 return false; 15163 const VarDecl *DefVD = nullptr; 15164 Var->getAnyInitializer(DefVD); 15165 if (!DefVD) 15166 return false; 15167 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 15168 Expr *Init = cast<Expr>(Eval->Value); 15169 if (Init->isValueDependent()) 15170 return false; 15171 return IsVariableAConstantExpression(Var, Context); 15172 } 15173 15174 15175 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 15176 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 15177 // an object that satisfies the requirements for appearing in a 15178 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 15179 // is immediately applied." This function handles the lvalue-to-rvalue 15180 // conversion part. 15181 MaybeODRUseExprs.erase(E->IgnoreParens()); 15182 15183 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 15184 // to a variable that is a constant expression, and if so, identify it as 15185 // a reference to a variable that does not involve an odr-use of that 15186 // variable. 15187 if (LambdaScopeInfo *LSI = getCurLambda()) { 15188 Expr *SansParensExpr = E->IgnoreParens(); 15189 VarDecl *Var = nullptr; 15190 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 15191 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 15192 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 15193 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 15194 15195 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 15196 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 15197 } 15198 } 15199 15200 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 15201 Res = CorrectDelayedTyposInExpr(Res); 15202 15203 if (!Res.isUsable()) 15204 return Res; 15205 15206 // If a constant-expression is a reference to a variable where we delay 15207 // deciding whether it is an odr-use, just assume we will apply the 15208 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 15209 // (a non-type template argument), we have special handling anyway. 15210 UpdateMarkingForLValueToRValue(Res.get()); 15211 return Res; 15212 } 15213 15214 void Sema::CleanupVarDeclMarking() { 15215 for (Expr *E : MaybeODRUseExprs) { 15216 VarDecl *Var; 15217 SourceLocation Loc; 15218 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15219 Var = cast<VarDecl>(DRE->getDecl()); 15220 Loc = DRE->getLocation(); 15221 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 15222 Var = cast<VarDecl>(ME->getMemberDecl()); 15223 Loc = ME->getMemberLoc(); 15224 } else { 15225 llvm_unreachable("Unexpected expression"); 15226 } 15227 15228 MarkVarDeclODRUsed(Var, Loc, *this, 15229 /*MaxFunctionScopeIndex Pointer*/ nullptr); 15230 } 15231 15232 MaybeODRUseExprs.clear(); 15233 } 15234 15235 15236 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 15237 VarDecl *Var, Expr *E) { 15238 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 15239 "Invalid Expr argument to DoMarkVarDeclReferenced"); 15240 Var->setReferenced(); 15241 15242 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 15243 15244 bool OdrUseContext = isOdrUseContext(SemaRef); 15245 bool UsableInConstantExpr = 15246 Var->isUsableInConstantExpressions(SemaRef.Context); 15247 bool NeedDefinition = 15248 OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr); 15249 15250 VarTemplateSpecializationDecl *VarSpec = 15251 dyn_cast<VarTemplateSpecializationDecl>(Var); 15252 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 15253 "Can't instantiate a partial template specialization."); 15254 15255 // If this might be a member specialization of a static data member, check 15256 // the specialization is visible. We already did the checks for variable 15257 // template specializations when we created them. 15258 if (NeedDefinition && TSK != TSK_Undeclared && 15259 !isa<VarTemplateSpecializationDecl>(Var)) 15260 SemaRef.checkSpecializationVisibility(Loc, Var); 15261 15262 // Perform implicit instantiation of static data members, static data member 15263 // templates of class templates, and variable template specializations. Delay 15264 // instantiations of variable templates, except for those that could be used 15265 // in a constant expression. 15266 if (NeedDefinition && isTemplateInstantiation(TSK)) { 15267 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 15268 // instantiation declaration if a variable is usable in a constant 15269 // expression (among other cases). 15270 bool TryInstantiating = 15271 TSK == TSK_ImplicitInstantiation || 15272 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 15273 15274 if (TryInstantiating) { 15275 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 15276 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 15277 if (FirstInstantiation) { 15278 PointOfInstantiation = Loc; 15279 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 15280 } 15281 15282 bool InstantiationDependent = false; 15283 bool IsNonDependent = 15284 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 15285 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 15286 : true; 15287 15288 // Do not instantiate specializations that are still type-dependent. 15289 if (IsNonDependent) { 15290 if (UsableInConstantExpr) { 15291 // Do not defer instantiations of variables that could be used in a 15292 // constant expression. 15293 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 15294 } else if (FirstInstantiation || 15295 isa<VarTemplateSpecializationDecl>(Var)) { 15296 // FIXME: For a specialization of a variable template, we don't 15297 // distinguish between "declaration and type implicitly instantiated" 15298 // and "implicit instantiation of definition requested", so we have 15299 // no direct way to avoid enqueueing the pending instantiation 15300 // multiple times. 15301 SemaRef.PendingInstantiations 15302 .push_back(std::make_pair(Var, PointOfInstantiation)); 15303 } 15304 } 15305 } 15306 } 15307 15308 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 15309 // the requirements for appearing in a constant expression (5.19) and, if 15310 // it is an object, the lvalue-to-rvalue conversion (4.1) 15311 // is immediately applied." We check the first part here, and 15312 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 15313 // Note that we use the C++11 definition everywhere because nothing in 15314 // C++03 depends on whether we get the C++03 version correct. The second 15315 // part does not apply to references, since they are not objects. 15316 if (OdrUseContext && E && 15317 IsVariableAConstantExpression(Var, SemaRef.Context)) { 15318 // A reference initialized by a constant expression can never be 15319 // odr-used, so simply ignore it. 15320 if (!Var->getType()->isReferenceType() || 15321 (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var))) 15322 SemaRef.MaybeODRUseExprs.insert(E); 15323 } else if (OdrUseContext) { 15324 MarkVarDeclODRUsed(Var, Loc, SemaRef, 15325 /*MaxFunctionScopeIndex ptr*/ nullptr); 15326 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 15327 // If this is a dependent context, we don't need to mark variables as 15328 // odr-used, but we may still need to track them for lambda capture. 15329 // FIXME: Do we also need to do this inside dependent typeid expressions 15330 // (which are modeled as unevaluated at this point)? 15331 const bool RefersToEnclosingScope = 15332 (SemaRef.CurContext != Var->getDeclContext() && 15333 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 15334 if (RefersToEnclosingScope) { 15335 LambdaScopeInfo *const LSI = 15336 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 15337 if (LSI && (!LSI->CallOperator || 15338 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 15339 // If a variable could potentially be odr-used, defer marking it so 15340 // until we finish analyzing the full expression for any 15341 // lvalue-to-rvalue 15342 // or discarded value conversions that would obviate odr-use. 15343 // Add it to the list of potential captures that will be analyzed 15344 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 15345 // unless the variable is a reference that was initialized by a constant 15346 // expression (this will never need to be captured or odr-used). 15347 assert(E && "Capture variable should be used in an expression."); 15348 if (!Var->getType()->isReferenceType() || 15349 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 15350 LSI->addPotentialCapture(E->IgnoreParens()); 15351 } 15352 } 15353 } 15354 } 15355 15356 /// Mark a variable referenced, and check whether it is odr-used 15357 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 15358 /// used directly for normal expressions referring to VarDecl. 15359 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 15360 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 15361 } 15362 15363 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 15364 Decl *D, Expr *E, bool MightBeOdrUse) { 15365 if (SemaRef.isInOpenMPDeclareTargetContext()) 15366 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 15367 15368 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 15369 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 15370 return; 15371 } 15372 15373 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 15374 15375 // If this is a call to a method via a cast, also mark the method in the 15376 // derived class used in case codegen can devirtualize the call. 15377 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 15378 if (!ME) 15379 return; 15380 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 15381 if (!MD) 15382 return; 15383 // Only attempt to devirtualize if this is truly a virtual call. 15384 bool IsVirtualCall = MD->isVirtual() && 15385 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 15386 if (!IsVirtualCall) 15387 return; 15388 15389 // If it's possible to devirtualize the call, mark the called function 15390 // referenced. 15391 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 15392 ME->getBase(), SemaRef.getLangOpts().AppleKext); 15393 if (DM) 15394 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 15395 } 15396 15397 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 15398 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 15399 // TODO: update this with DR# once a defect report is filed. 15400 // C++11 defect. The address of a pure member should not be an ODR use, even 15401 // if it's a qualified reference. 15402 bool OdrUse = true; 15403 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 15404 if (Method->isVirtual() && 15405 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 15406 OdrUse = false; 15407 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 15408 } 15409 15410 /// Perform reference-marking and odr-use handling for a MemberExpr. 15411 void Sema::MarkMemberReferenced(MemberExpr *E) { 15412 // C++11 [basic.def.odr]p2: 15413 // A non-overloaded function whose name appears as a potentially-evaluated 15414 // expression or a member of a set of candidate functions, if selected by 15415 // overload resolution when referred to from a potentially-evaluated 15416 // expression, is odr-used, unless it is a pure virtual function and its 15417 // name is not explicitly qualified. 15418 bool MightBeOdrUse = true; 15419 if (E->performsVirtualDispatch(getLangOpts())) { 15420 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 15421 if (Method->isPure()) 15422 MightBeOdrUse = false; 15423 } 15424 SourceLocation Loc = 15425 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 15426 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 15427 } 15428 15429 /// Perform marking for a reference to an arbitrary declaration. It 15430 /// marks the declaration referenced, and performs odr-use checking for 15431 /// functions and variables. This method should not be used when building a 15432 /// normal expression which refers to a variable. 15433 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 15434 bool MightBeOdrUse) { 15435 if (MightBeOdrUse) { 15436 if (auto *VD = dyn_cast<VarDecl>(D)) { 15437 MarkVariableReferenced(Loc, VD); 15438 return; 15439 } 15440 } 15441 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 15442 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 15443 return; 15444 } 15445 D->setReferenced(); 15446 } 15447 15448 namespace { 15449 // Mark all of the declarations used by a type as referenced. 15450 // FIXME: Not fully implemented yet! We need to have a better understanding 15451 // of when we're entering a context we should not recurse into. 15452 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 15453 // TreeTransforms rebuilding the type in a new context. Rather than 15454 // duplicating the TreeTransform logic, we should consider reusing it here. 15455 // Currently that causes problems when rebuilding LambdaExprs. 15456 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 15457 Sema &S; 15458 SourceLocation Loc; 15459 15460 public: 15461 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 15462 15463 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 15464 15465 bool TraverseTemplateArgument(const TemplateArgument &Arg); 15466 }; 15467 } 15468 15469 bool MarkReferencedDecls::TraverseTemplateArgument( 15470 const TemplateArgument &Arg) { 15471 { 15472 // A non-type template argument is a constant-evaluated context. 15473 EnterExpressionEvaluationContext Evaluated( 15474 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 15475 if (Arg.getKind() == TemplateArgument::Declaration) { 15476 if (Decl *D = Arg.getAsDecl()) 15477 S.MarkAnyDeclReferenced(Loc, D, true); 15478 } else if (Arg.getKind() == TemplateArgument::Expression) { 15479 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 15480 } 15481 } 15482 15483 return Inherited::TraverseTemplateArgument(Arg); 15484 } 15485 15486 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 15487 MarkReferencedDecls Marker(*this, Loc); 15488 Marker.TraverseType(T); 15489 } 15490 15491 namespace { 15492 /// Helper class that marks all of the declarations referenced by 15493 /// potentially-evaluated subexpressions as "referenced". 15494 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 15495 Sema &S; 15496 bool SkipLocalVariables; 15497 15498 public: 15499 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 15500 15501 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 15502 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 15503 15504 void VisitDeclRefExpr(DeclRefExpr *E) { 15505 // If we were asked not to visit local variables, don't. 15506 if (SkipLocalVariables) { 15507 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 15508 if (VD->hasLocalStorage()) 15509 return; 15510 } 15511 15512 S.MarkDeclRefReferenced(E); 15513 } 15514 15515 void VisitMemberExpr(MemberExpr *E) { 15516 S.MarkMemberReferenced(E); 15517 Inherited::VisitMemberExpr(E); 15518 } 15519 15520 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 15521 S.MarkFunctionReferenced( 15522 E->getBeginLoc(), 15523 const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor())); 15524 Visit(E->getSubExpr()); 15525 } 15526 15527 void VisitCXXNewExpr(CXXNewExpr *E) { 15528 if (E->getOperatorNew()) 15529 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew()); 15530 if (E->getOperatorDelete()) 15531 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 15532 Inherited::VisitCXXNewExpr(E); 15533 } 15534 15535 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 15536 if (E->getOperatorDelete()) 15537 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 15538 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 15539 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 15540 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 15541 S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record)); 15542 } 15543 15544 Inherited::VisitCXXDeleteExpr(E); 15545 } 15546 15547 void VisitCXXConstructExpr(CXXConstructExpr *E) { 15548 S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor()); 15549 Inherited::VisitCXXConstructExpr(E); 15550 } 15551 15552 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 15553 Visit(E->getExpr()); 15554 } 15555 15556 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 15557 Inherited::VisitImplicitCastExpr(E); 15558 15559 if (E->getCastKind() == CK_LValueToRValue) 15560 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 15561 } 15562 }; 15563 } 15564 15565 /// Mark any declarations that appear within this expression or any 15566 /// potentially-evaluated subexpressions as "referenced". 15567 /// 15568 /// \param SkipLocalVariables If true, don't mark local variables as 15569 /// 'referenced'. 15570 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 15571 bool SkipLocalVariables) { 15572 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 15573 } 15574 15575 /// Emit a diagnostic that describes an effect on the run-time behavior 15576 /// of the program being compiled. 15577 /// 15578 /// This routine emits the given diagnostic when the code currently being 15579 /// type-checked is "potentially evaluated", meaning that there is a 15580 /// possibility that the code will actually be executable. Code in sizeof() 15581 /// expressions, code used only during overload resolution, etc., are not 15582 /// potentially evaluated. This routine will suppress such diagnostics or, 15583 /// in the absolutely nutty case of potentially potentially evaluated 15584 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 15585 /// later. 15586 /// 15587 /// This routine should be used for all diagnostics that describe the run-time 15588 /// behavior of a program, such as passing a non-POD value through an ellipsis. 15589 /// Failure to do so will likely result in spurious diagnostics or failures 15590 /// during overload resolution or within sizeof/alignof/typeof/typeid. 15591 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 15592 const PartialDiagnostic &PD) { 15593 switch (ExprEvalContexts.back().Context) { 15594 case ExpressionEvaluationContext::Unevaluated: 15595 case ExpressionEvaluationContext::UnevaluatedList: 15596 case ExpressionEvaluationContext::UnevaluatedAbstract: 15597 case ExpressionEvaluationContext::DiscardedStatement: 15598 // The argument will never be evaluated, so don't complain. 15599 break; 15600 15601 case ExpressionEvaluationContext::ConstantEvaluated: 15602 // Relevant diagnostics should be produced by constant evaluation. 15603 break; 15604 15605 case ExpressionEvaluationContext::PotentiallyEvaluated: 15606 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15607 if (Statement && getCurFunctionOrMethodDecl()) { 15608 FunctionScopes.back()->PossiblyUnreachableDiags. 15609 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 15610 return true; 15611 } 15612 15613 // The initializer of a constexpr variable or of the first declaration of a 15614 // static data member is not syntactically a constant evaluated constant, 15615 // but nonetheless is always required to be a constant expression, so we 15616 // can skip diagnosing. 15617 // FIXME: Using the mangling context here is a hack. 15618 if (auto *VD = dyn_cast_or_null<VarDecl>( 15619 ExprEvalContexts.back().ManglingContextDecl)) { 15620 if (VD->isConstexpr() || 15621 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 15622 break; 15623 // FIXME: For any other kind of variable, we should build a CFG for its 15624 // initializer and check whether the context in question is reachable. 15625 } 15626 15627 Diag(Loc, PD); 15628 return true; 15629 } 15630 15631 return false; 15632 } 15633 15634 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 15635 CallExpr *CE, FunctionDecl *FD) { 15636 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 15637 return false; 15638 15639 // If we're inside a decltype's expression, don't check for a valid return 15640 // type or construct temporaries until we know whether this is the last call. 15641 if (ExprEvalContexts.back().ExprContext == 15642 ExpressionEvaluationContextRecord::EK_Decltype) { 15643 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 15644 return false; 15645 } 15646 15647 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 15648 FunctionDecl *FD; 15649 CallExpr *CE; 15650 15651 public: 15652 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 15653 : FD(FD), CE(CE) { } 15654 15655 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15656 if (!FD) { 15657 S.Diag(Loc, diag::err_call_incomplete_return) 15658 << T << CE->getSourceRange(); 15659 return; 15660 } 15661 15662 S.Diag(Loc, diag::err_call_function_incomplete_return) 15663 << CE->getSourceRange() << FD->getDeclName() << T; 15664 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 15665 << FD->getDeclName(); 15666 } 15667 } Diagnoser(FD, CE); 15668 15669 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 15670 return true; 15671 15672 return false; 15673 } 15674 15675 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 15676 // will prevent this condition from triggering, which is what we want. 15677 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 15678 SourceLocation Loc; 15679 15680 unsigned diagnostic = diag::warn_condition_is_assignment; 15681 bool IsOrAssign = false; 15682 15683 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 15684 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 15685 return; 15686 15687 IsOrAssign = Op->getOpcode() == BO_OrAssign; 15688 15689 // Greylist some idioms by putting them into a warning subcategory. 15690 if (ObjCMessageExpr *ME 15691 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 15692 Selector Sel = ME->getSelector(); 15693 15694 // self = [<foo> init...] 15695 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 15696 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15697 15698 // <foo> = [<bar> nextObject] 15699 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 15700 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15701 } 15702 15703 Loc = Op->getOperatorLoc(); 15704 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 15705 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 15706 return; 15707 15708 IsOrAssign = Op->getOperator() == OO_PipeEqual; 15709 Loc = Op->getOperatorLoc(); 15710 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 15711 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 15712 else { 15713 // Not an assignment. 15714 return; 15715 } 15716 15717 Diag(Loc, diagnostic) << E->getSourceRange(); 15718 15719 SourceLocation Open = E->getBeginLoc(); 15720 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 15721 Diag(Loc, diag::note_condition_assign_silence) 15722 << FixItHint::CreateInsertion(Open, "(") 15723 << FixItHint::CreateInsertion(Close, ")"); 15724 15725 if (IsOrAssign) 15726 Diag(Loc, diag::note_condition_or_assign_to_comparison) 15727 << FixItHint::CreateReplacement(Loc, "!="); 15728 else 15729 Diag(Loc, diag::note_condition_assign_to_comparison) 15730 << FixItHint::CreateReplacement(Loc, "=="); 15731 } 15732 15733 /// Redundant parentheses over an equality comparison can indicate 15734 /// that the user intended an assignment used as condition. 15735 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 15736 // Don't warn if the parens came from a macro. 15737 SourceLocation parenLoc = ParenE->getBeginLoc(); 15738 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 15739 return; 15740 // Don't warn for dependent expressions. 15741 if (ParenE->isTypeDependent()) 15742 return; 15743 15744 Expr *E = ParenE->IgnoreParens(); 15745 15746 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 15747 if (opE->getOpcode() == BO_EQ && 15748 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 15749 == Expr::MLV_Valid) { 15750 SourceLocation Loc = opE->getOperatorLoc(); 15751 15752 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 15753 SourceRange ParenERange = ParenE->getSourceRange(); 15754 Diag(Loc, diag::note_equality_comparison_silence) 15755 << FixItHint::CreateRemoval(ParenERange.getBegin()) 15756 << FixItHint::CreateRemoval(ParenERange.getEnd()); 15757 Diag(Loc, diag::note_equality_comparison_to_assign) 15758 << FixItHint::CreateReplacement(Loc, "="); 15759 } 15760 } 15761 15762 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 15763 bool IsConstexpr) { 15764 DiagnoseAssignmentAsCondition(E); 15765 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 15766 DiagnoseEqualityWithExtraParens(parenE); 15767 15768 ExprResult result = CheckPlaceholderExpr(E); 15769 if (result.isInvalid()) return ExprError(); 15770 E = result.get(); 15771 15772 if (!E->isTypeDependent()) { 15773 if (getLangOpts().CPlusPlus) 15774 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 15775 15776 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 15777 if (ERes.isInvalid()) 15778 return ExprError(); 15779 E = ERes.get(); 15780 15781 QualType T = E->getType(); 15782 if (!T->isScalarType()) { // C99 6.8.4.1p1 15783 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 15784 << T << E->getSourceRange(); 15785 return ExprError(); 15786 } 15787 CheckBoolLikeConversion(E, Loc); 15788 } 15789 15790 return E; 15791 } 15792 15793 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 15794 Expr *SubExpr, ConditionKind CK) { 15795 // Empty conditions are valid in for-statements. 15796 if (!SubExpr) 15797 return ConditionResult(); 15798 15799 ExprResult Cond; 15800 switch (CK) { 15801 case ConditionKind::Boolean: 15802 Cond = CheckBooleanCondition(Loc, SubExpr); 15803 break; 15804 15805 case ConditionKind::ConstexprIf: 15806 Cond = CheckBooleanCondition(Loc, SubExpr, true); 15807 break; 15808 15809 case ConditionKind::Switch: 15810 Cond = CheckSwitchCondition(Loc, SubExpr); 15811 break; 15812 } 15813 if (Cond.isInvalid()) 15814 return ConditionError(); 15815 15816 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 15817 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 15818 if (!FullExpr.get()) 15819 return ConditionError(); 15820 15821 return ConditionResult(*this, nullptr, FullExpr, 15822 CK == ConditionKind::ConstexprIf); 15823 } 15824 15825 namespace { 15826 /// A visitor for rebuilding a call to an __unknown_any expression 15827 /// to have an appropriate type. 15828 struct RebuildUnknownAnyFunction 15829 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 15830 15831 Sema &S; 15832 15833 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 15834 15835 ExprResult VisitStmt(Stmt *S) { 15836 llvm_unreachable("unexpected statement!"); 15837 } 15838 15839 ExprResult VisitExpr(Expr *E) { 15840 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 15841 << E->getSourceRange(); 15842 return ExprError(); 15843 } 15844 15845 /// Rebuild an expression which simply semantically wraps another 15846 /// expression which it shares the type and value kind of. 15847 template <class T> ExprResult rebuildSugarExpr(T *E) { 15848 ExprResult SubResult = Visit(E->getSubExpr()); 15849 if (SubResult.isInvalid()) return ExprError(); 15850 15851 Expr *SubExpr = SubResult.get(); 15852 E->setSubExpr(SubExpr); 15853 E->setType(SubExpr->getType()); 15854 E->setValueKind(SubExpr->getValueKind()); 15855 assert(E->getObjectKind() == OK_Ordinary); 15856 return E; 15857 } 15858 15859 ExprResult VisitParenExpr(ParenExpr *E) { 15860 return rebuildSugarExpr(E); 15861 } 15862 15863 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15864 return rebuildSugarExpr(E); 15865 } 15866 15867 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15868 ExprResult SubResult = Visit(E->getSubExpr()); 15869 if (SubResult.isInvalid()) return ExprError(); 15870 15871 Expr *SubExpr = SubResult.get(); 15872 E->setSubExpr(SubExpr); 15873 E->setType(S.Context.getPointerType(SubExpr->getType())); 15874 assert(E->getValueKind() == VK_RValue); 15875 assert(E->getObjectKind() == OK_Ordinary); 15876 return E; 15877 } 15878 15879 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 15880 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 15881 15882 E->setType(VD->getType()); 15883 15884 assert(E->getValueKind() == VK_RValue); 15885 if (S.getLangOpts().CPlusPlus && 15886 !(isa<CXXMethodDecl>(VD) && 15887 cast<CXXMethodDecl>(VD)->isInstance())) 15888 E->setValueKind(VK_LValue); 15889 15890 return E; 15891 } 15892 15893 ExprResult VisitMemberExpr(MemberExpr *E) { 15894 return resolveDecl(E, E->getMemberDecl()); 15895 } 15896 15897 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15898 return resolveDecl(E, E->getDecl()); 15899 } 15900 }; 15901 } 15902 15903 /// Given a function expression of unknown-any type, try to rebuild it 15904 /// to have a function type. 15905 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 15906 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 15907 if (Result.isInvalid()) return ExprError(); 15908 return S.DefaultFunctionArrayConversion(Result.get()); 15909 } 15910 15911 namespace { 15912 /// A visitor for rebuilding an expression of type __unknown_anytype 15913 /// into one which resolves the type directly on the referring 15914 /// expression. Strict preservation of the original source 15915 /// structure is not a goal. 15916 struct RebuildUnknownAnyExpr 15917 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 15918 15919 Sema &S; 15920 15921 /// The current destination type. 15922 QualType DestType; 15923 15924 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 15925 : S(S), DestType(CastType) {} 15926 15927 ExprResult VisitStmt(Stmt *S) { 15928 llvm_unreachable("unexpected statement!"); 15929 } 15930 15931 ExprResult VisitExpr(Expr *E) { 15932 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 15933 << E->getSourceRange(); 15934 return ExprError(); 15935 } 15936 15937 ExprResult VisitCallExpr(CallExpr *E); 15938 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 15939 15940 /// Rebuild an expression which simply semantically wraps another 15941 /// expression which it shares the type and value kind of. 15942 template <class T> ExprResult rebuildSugarExpr(T *E) { 15943 ExprResult SubResult = Visit(E->getSubExpr()); 15944 if (SubResult.isInvalid()) return ExprError(); 15945 Expr *SubExpr = SubResult.get(); 15946 E->setSubExpr(SubExpr); 15947 E->setType(SubExpr->getType()); 15948 E->setValueKind(SubExpr->getValueKind()); 15949 assert(E->getObjectKind() == OK_Ordinary); 15950 return E; 15951 } 15952 15953 ExprResult VisitParenExpr(ParenExpr *E) { 15954 return rebuildSugarExpr(E); 15955 } 15956 15957 ExprResult VisitUnaryExtension(UnaryOperator *E) { 15958 return rebuildSugarExpr(E); 15959 } 15960 15961 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 15962 const PointerType *Ptr = DestType->getAs<PointerType>(); 15963 if (!Ptr) { 15964 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 15965 << E->getSourceRange(); 15966 return ExprError(); 15967 } 15968 15969 if (isa<CallExpr>(E->getSubExpr())) { 15970 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 15971 << E->getSourceRange(); 15972 return ExprError(); 15973 } 15974 15975 assert(E->getValueKind() == VK_RValue); 15976 assert(E->getObjectKind() == OK_Ordinary); 15977 E->setType(DestType); 15978 15979 // Build the sub-expression as if it were an object of the pointee type. 15980 DestType = Ptr->getPointeeType(); 15981 ExprResult SubResult = Visit(E->getSubExpr()); 15982 if (SubResult.isInvalid()) return ExprError(); 15983 E->setSubExpr(SubResult.get()); 15984 return E; 15985 } 15986 15987 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 15988 15989 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 15990 15991 ExprResult VisitMemberExpr(MemberExpr *E) { 15992 return resolveDecl(E, E->getMemberDecl()); 15993 } 15994 15995 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 15996 return resolveDecl(E, E->getDecl()); 15997 } 15998 }; 15999 } 16000 16001 /// Rebuilds a call expression which yielded __unknown_anytype. 16002 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 16003 Expr *CalleeExpr = E->getCallee(); 16004 16005 enum FnKind { 16006 FK_MemberFunction, 16007 FK_FunctionPointer, 16008 FK_BlockPointer 16009 }; 16010 16011 FnKind Kind; 16012 QualType CalleeType = CalleeExpr->getType(); 16013 if (CalleeType == S.Context.BoundMemberTy) { 16014 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 16015 Kind = FK_MemberFunction; 16016 CalleeType = Expr::findBoundMemberType(CalleeExpr); 16017 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 16018 CalleeType = Ptr->getPointeeType(); 16019 Kind = FK_FunctionPointer; 16020 } else { 16021 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 16022 Kind = FK_BlockPointer; 16023 } 16024 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 16025 16026 // Verify that this is a legal result type of a function. 16027 if (DestType->isArrayType() || DestType->isFunctionType()) { 16028 unsigned diagID = diag::err_func_returning_array_function; 16029 if (Kind == FK_BlockPointer) 16030 diagID = diag::err_block_returning_array_function; 16031 16032 S.Diag(E->getExprLoc(), diagID) 16033 << DestType->isFunctionType() << DestType; 16034 return ExprError(); 16035 } 16036 16037 // Otherwise, go ahead and set DestType as the call's result. 16038 E->setType(DestType.getNonLValueExprType(S.Context)); 16039 E->setValueKind(Expr::getValueKindForType(DestType)); 16040 assert(E->getObjectKind() == OK_Ordinary); 16041 16042 // Rebuild the function type, replacing the result type with DestType. 16043 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 16044 if (Proto) { 16045 // __unknown_anytype(...) is a special case used by the debugger when 16046 // it has no idea what a function's signature is. 16047 // 16048 // We want to build this call essentially under the K&R 16049 // unprototyped rules, but making a FunctionNoProtoType in C++ 16050 // would foul up all sorts of assumptions. However, we cannot 16051 // simply pass all arguments as variadic arguments, nor can we 16052 // portably just call the function under a non-variadic type; see 16053 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 16054 // However, it turns out that in practice it is generally safe to 16055 // call a function declared as "A foo(B,C,D);" under the prototype 16056 // "A foo(B,C,D,...);". The only known exception is with the 16057 // Windows ABI, where any variadic function is implicitly cdecl 16058 // regardless of its normal CC. Therefore we change the parameter 16059 // types to match the types of the arguments. 16060 // 16061 // This is a hack, but it is far superior to moving the 16062 // corresponding target-specific code from IR-gen to Sema/AST. 16063 16064 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 16065 SmallVector<QualType, 8> ArgTypes; 16066 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 16067 ArgTypes.reserve(E->getNumArgs()); 16068 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 16069 Expr *Arg = E->getArg(i); 16070 QualType ArgType = Arg->getType(); 16071 if (E->isLValue()) { 16072 ArgType = S.Context.getLValueReferenceType(ArgType); 16073 } else if (E->isXValue()) { 16074 ArgType = S.Context.getRValueReferenceType(ArgType); 16075 } 16076 ArgTypes.push_back(ArgType); 16077 } 16078 ParamTypes = ArgTypes; 16079 } 16080 DestType = S.Context.getFunctionType(DestType, ParamTypes, 16081 Proto->getExtProtoInfo()); 16082 } else { 16083 DestType = S.Context.getFunctionNoProtoType(DestType, 16084 FnType->getExtInfo()); 16085 } 16086 16087 // Rebuild the appropriate pointer-to-function type. 16088 switch (Kind) { 16089 case FK_MemberFunction: 16090 // Nothing to do. 16091 break; 16092 16093 case FK_FunctionPointer: 16094 DestType = S.Context.getPointerType(DestType); 16095 break; 16096 16097 case FK_BlockPointer: 16098 DestType = S.Context.getBlockPointerType(DestType); 16099 break; 16100 } 16101 16102 // Finally, we can recurse. 16103 ExprResult CalleeResult = Visit(CalleeExpr); 16104 if (!CalleeResult.isUsable()) return ExprError(); 16105 E->setCallee(CalleeResult.get()); 16106 16107 // Bind a temporary if necessary. 16108 return S.MaybeBindToTemporary(E); 16109 } 16110 16111 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 16112 // Verify that this is a legal result type of a call. 16113 if (DestType->isArrayType() || DestType->isFunctionType()) { 16114 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 16115 << DestType->isFunctionType() << DestType; 16116 return ExprError(); 16117 } 16118 16119 // Rewrite the method result type if available. 16120 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 16121 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 16122 Method->setReturnType(DestType); 16123 } 16124 16125 // Change the type of the message. 16126 E->setType(DestType.getNonReferenceType()); 16127 E->setValueKind(Expr::getValueKindForType(DestType)); 16128 16129 return S.MaybeBindToTemporary(E); 16130 } 16131 16132 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 16133 // The only case we should ever see here is a function-to-pointer decay. 16134 if (E->getCastKind() == CK_FunctionToPointerDecay) { 16135 assert(E->getValueKind() == VK_RValue); 16136 assert(E->getObjectKind() == OK_Ordinary); 16137 16138 E->setType(DestType); 16139 16140 // Rebuild the sub-expression as the pointee (function) type. 16141 DestType = DestType->castAs<PointerType>()->getPointeeType(); 16142 16143 ExprResult Result = Visit(E->getSubExpr()); 16144 if (!Result.isUsable()) return ExprError(); 16145 16146 E->setSubExpr(Result.get()); 16147 return E; 16148 } else if (E->getCastKind() == CK_LValueToRValue) { 16149 assert(E->getValueKind() == VK_RValue); 16150 assert(E->getObjectKind() == OK_Ordinary); 16151 16152 assert(isa<BlockPointerType>(E->getType())); 16153 16154 E->setType(DestType); 16155 16156 // The sub-expression has to be a lvalue reference, so rebuild it as such. 16157 DestType = S.Context.getLValueReferenceType(DestType); 16158 16159 ExprResult Result = Visit(E->getSubExpr()); 16160 if (!Result.isUsable()) return ExprError(); 16161 16162 E->setSubExpr(Result.get()); 16163 return E; 16164 } else { 16165 llvm_unreachable("Unhandled cast type!"); 16166 } 16167 } 16168 16169 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 16170 ExprValueKind ValueKind = VK_LValue; 16171 QualType Type = DestType; 16172 16173 // We know how to make this work for certain kinds of decls: 16174 16175 // - functions 16176 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 16177 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 16178 DestType = Ptr->getPointeeType(); 16179 ExprResult Result = resolveDecl(E, VD); 16180 if (Result.isInvalid()) return ExprError(); 16181 return S.ImpCastExprToType(Result.get(), Type, 16182 CK_FunctionToPointerDecay, VK_RValue); 16183 } 16184 16185 if (!Type->isFunctionType()) { 16186 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 16187 << VD << E->getSourceRange(); 16188 return ExprError(); 16189 } 16190 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 16191 // We must match the FunctionDecl's type to the hack introduced in 16192 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 16193 // type. See the lengthy commentary in that routine. 16194 QualType FDT = FD->getType(); 16195 const FunctionType *FnType = FDT->castAs<FunctionType>(); 16196 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 16197 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 16198 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 16199 SourceLocation Loc = FD->getLocation(); 16200 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 16201 FD->getDeclContext(), 16202 Loc, Loc, FD->getNameInfo().getName(), 16203 DestType, FD->getTypeSourceInfo(), 16204 SC_None, false/*isInlineSpecified*/, 16205 FD->hasPrototype(), 16206 false/*isConstexprSpecified*/); 16207 16208 if (FD->getQualifier()) 16209 NewFD->setQualifierInfo(FD->getQualifierLoc()); 16210 16211 SmallVector<ParmVarDecl*, 16> Params; 16212 for (const auto &AI : FT->param_types()) { 16213 ParmVarDecl *Param = 16214 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 16215 Param->setScopeInfo(0, Params.size()); 16216 Params.push_back(Param); 16217 } 16218 NewFD->setParams(Params); 16219 DRE->setDecl(NewFD); 16220 VD = DRE->getDecl(); 16221 } 16222 } 16223 16224 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 16225 if (MD->isInstance()) { 16226 ValueKind = VK_RValue; 16227 Type = S.Context.BoundMemberTy; 16228 } 16229 16230 // Function references aren't l-values in C. 16231 if (!S.getLangOpts().CPlusPlus) 16232 ValueKind = VK_RValue; 16233 16234 // - variables 16235 } else if (isa<VarDecl>(VD)) { 16236 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 16237 Type = RefTy->getPointeeType(); 16238 } else if (Type->isFunctionType()) { 16239 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 16240 << VD << E->getSourceRange(); 16241 return ExprError(); 16242 } 16243 16244 // - nothing else 16245 } else { 16246 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 16247 << VD << E->getSourceRange(); 16248 return ExprError(); 16249 } 16250 16251 // Modifying the declaration like this is friendly to IR-gen but 16252 // also really dangerous. 16253 VD->setType(DestType); 16254 E->setType(Type); 16255 E->setValueKind(ValueKind); 16256 return E; 16257 } 16258 16259 /// Check a cast of an unknown-any type. We intentionally only 16260 /// trigger this for C-style casts. 16261 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 16262 Expr *CastExpr, CastKind &CastKind, 16263 ExprValueKind &VK, CXXCastPath &Path) { 16264 // The type we're casting to must be either void or complete. 16265 if (!CastType->isVoidType() && 16266 RequireCompleteType(TypeRange.getBegin(), CastType, 16267 diag::err_typecheck_cast_to_incomplete)) 16268 return ExprError(); 16269 16270 // Rewrite the casted expression from scratch. 16271 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 16272 if (!result.isUsable()) return ExprError(); 16273 16274 CastExpr = result.get(); 16275 VK = CastExpr->getValueKind(); 16276 CastKind = CK_NoOp; 16277 16278 return CastExpr; 16279 } 16280 16281 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 16282 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 16283 } 16284 16285 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 16286 Expr *arg, QualType ¶mType) { 16287 // If the syntactic form of the argument is not an explicit cast of 16288 // any sort, just do default argument promotion. 16289 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 16290 if (!castArg) { 16291 ExprResult result = DefaultArgumentPromotion(arg); 16292 if (result.isInvalid()) return ExprError(); 16293 paramType = result.get()->getType(); 16294 return result; 16295 } 16296 16297 // Otherwise, use the type that was written in the explicit cast. 16298 assert(!arg->hasPlaceholderType()); 16299 paramType = castArg->getTypeAsWritten(); 16300 16301 // Copy-initialize a parameter of that type. 16302 InitializedEntity entity = 16303 InitializedEntity::InitializeParameter(Context, paramType, 16304 /*consumed*/ false); 16305 return PerformCopyInitialization(entity, callLoc, arg); 16306 } 16307 16308 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 16309 Expr *orig = E; 16310 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 16311 while (true) { 16312 E = E->IgnoreParenImpCasts(); 16313 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 16314 E = call->getCallee(); 16315 diagID = diag::err_uncasted_call_of_unknown_any; 16316 } else { 16317 break; 16318 } 16319 } 16320 16321 SourceLocation loc; 16322 NamedDecl *d; 16323 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 16324 loc = ref->getLocation(); 16325 d = ref->getDecl(); 16326 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 16327 loc = mem->getMemberLoc(); 16328 d = mem->getMemberDecl(); 16329 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 16330 diagID = diag::err_uncasted_call_of_unknown_any; 16331 loc = msg->getSelectorStartLoc(); 16332 d = msg->getMethodDecl(); 16333 if (!d) { 16334 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 16335 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 16336 << orig->getSourceRange(); 16337 return ExprError(); 16338 } 16339 } else { 16340 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 16341 << E->getSourceRange(); 16342 return ExprError(); 16343 } 16344 16345 S.Diag(loc, diagID) << d << orig->getSourceRange(); 16346 16347 // Never recoverable. 16348 return ExprError(); 16349 } 16350 16351 /// Check for operands with placeholder types and complain if found. 16352 /// Returns ExprError() if there was an error and no recovery was possible. 16353 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 16354 if (!getLangOpts().CPlusPlus) { 16355 // C cannot handle TypoExpr nodes on either side of a binop because it 16356 // doesn't handle dependent types properly, so make sure any TypoExprs have 16357 // been dealt with before checking the operands. 16358 ExprResult Result = CorrectDelayedTyposInExpr(E); 16359 if (!Result.isUsable()) return ExprError(); 16360 E = Result.get(); 16361 } 16362 16363 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 16364 if (!placeholderType) return E; 16365 16366 switch (placeholderType->getKind()) { 16367 16368 // Overloaded expressions. 16369 case BuiltinType::Overload: { 16370 // Try to resolve a single function template specialization. 16371 // This is obligatory. 16372 ExprResult Result = E; 16373 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 16374 return Result; 16375 16376 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 16377 // leaves Result unchanged on failure. 16378 Result = E; 16379 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 16380 return Result; 16381 16382 // If that failed, try to recover with a call. 16383 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 16384 /*complain*/ true); 16385 return Result; 16386 } 16387 16388 // Bound member functions. 16389 case BuiltinType::BoundMember: { 16390 ExprResult result = E; 16391 const Expr *BME = E->IgnoreParens(); 16392 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 16393 // Try to give a nicer diagnostic if it is a bound member that we recognize. 16394 if (isa<CXXPseudoDestructorExpr>(BME)) { 16395 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 16396 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 16397 if (ME->getMemberNameInfo().getName().getNameKind() == 16398 DeclarationName::CXXDestructorName) 16399 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 16400 } 16401 tryToRecoverWithCall(result, PD, 16402 /*complain*/ true); 16403 return result; 16404 } 16405 16406 // ARC unbridged casts. 16407 case BuiltinType::ARCUnbridgedCast: { 16408 Expr *realCast = stripARCUnbridgedCast(E); 16409 diagnoseARCUnbridgedCast(realCast); 16410 return realCast; 16411 } 16412 16413 // Expressions of unknown type. 16414 case BuiltinType::UnknownAny: 16415 return diagnoseUnknownAnyExpr(*this, E); 16416 16417 // Pseudo-objects. 16418 case BuiltinType::PseudoObject: 16419 return checkPseudoObjectRValue(E); 16420 16421 case BuiltinType::BuiltinFn: { 16422 // Accept __noop without parens by implicitly converting it to a call expr. 16423 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 16424 if (DRE) { 16425 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 16426 if (FD->getBuiltinID() == Builtin::BI__noop) { 16427 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 16428 CK_BuiltinFnToFnPtr).get(); 16429 return new (Context) CallExpr(Context, E, None, Context.IntTy, 16430 VK_RValue, SourceLocation()); 16431 } 16432 } 16433 16434 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 16435 return ExprError(); 16436 } 16437 16438 // Expressions of unknown type. 16439 case BuiltinType::OMPArraySection: 16440 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 16441 return ExprError(); 16442 16443 // Everything else should be impossible. 16444 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 16445 case BuiltinType::Id: 16446 #include "clang/Basic/OpenCLImageTypes.def" 16447 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 16448 #define PLACEHOLDER_TYPE(Id, SingletonId) 16449 #include "clang/AST/BuiltinTypes.def" 16450 break; 16451 } 16452 16453 llvm_unreachable("invalid placeholder type!"); 16454 } 16455 16456 bool Sema::CheckCaseExpression(Expr *E) { 16457 if (E->isTypeDependent()) 16458 return true; 16459 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 16460 return E->getType()->isIntegralOrEnumerationType(); 16461 return false; 16462 } 16463 16464 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 16465 ExprResult 16466 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 16467 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 16468 "Unknown Objective-C Boolean value!"); 16469 QualType BoolT = Context.ObjCBuiltinBoolTy; 16470 if (!Context.getBOOLDecl()) { 16471 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 16472 Sema::LookupOrdinaryName); 16473 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 16474 NamedDecl *ND = Result.getFoundDecl(); 16475 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 16476 Context.setBOOLDecl(TD); 16477 } 16478 } 16479 if (Context.getBOOLDecl()) 16480 BoolT = Context.getBOOLType(); 16481 return new (Context) 16482 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 16483 } 16484 16485 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 16486 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 16487 SourceLocation RParen) { 16488 16489 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 16490 16491 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 16492 [&](const AvailabilitySpec &Spec) { 16493 return Spec.getPlatform() == Platform; 16494 }); 16495 16496 VersionTuple Version; 16497 if (Spec != AvailSpecs.end()) 16498 Version = Spec->getVersion(); 16499 16500 // The use of `@available` in the enclosing function should be analyzed to 16501 // warn when it's used inappropriately (i.e. not if(@available)). 16502 if (getCurFunctionOrMethodDecl()) 16503 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 16504 else if (getCurBlock() || getCurLambda()) 16505 getCurFunction()->HasPotentialAvailabilityViolations = true; 16506 16507 return new (Context) 16508 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 16509 } 16510