1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for expressions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TreeTransform.h" 14 #include "UsedDeclVisitor.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/OperationKinds.h" 28 #include "clang/AST/ParentMapContext.h" 29 #include "clang/AST/RecursiveASTVisitor.h" 30 #include "clang/AST/Type.h" 31 #include "clang/AST/TypeLoc.h" 32 #include "clang/Basic/Builtins.h" 33 #include "clang/Basic/DiagnosticSema.h" 34 #include "clang/Basic/PartialDiagnostic.h" 35 #include "clang/Basic/SourceManager.h" 36 #include "clang/Basic/Specifiers.h" 37 #include "clang/Basic/TargetInfo.h" 38 #include "clang/Lex/LiteralSupport.h" 39 #include "clang/Lex/Preprocessor.h" 40 #include "clang/Sema/AnalysisBasedWarnings.h" 41 #include "clang/Sema/DeclSpec.h" 42 #include "clang/Sema/DelayedDiagnostic.h" 43 #include "clang/Sema/Designator.h" 44 #include "clang/Sema/Initialization.h" 45 #include "clang/Sema/Lookup.h" 46 #include "clang/Sema/Overload.h" 47 #include "clang/Sema/ParsedTemplate.h" 48 #include "clang/Sema/Scope.h" 49 #include "clang/Sema/ScopeInfo.h" 50 #include "clang/Sema/SemaFixItUtils.h" 51 #include "clang/Sema/SemaInternal.h" 52 #include "clang/Sema/Template.h" 53 #include "llvm/ADT/STLExtras.h" 54 #include "llvm/ADT/StringExtras.h" 55 #include "llvm/Support/Casting.h" 56 #include "llvm/Support/ConvertUTF.h" 57 #include "llvm/Support/SaveAndRestore.h" 58 #include "llvm/Support/TypeSize.h" 59 #include <optional> 60 61 using namespace clang; 62 using namespace sema; 63 64 /// Determine whether the use of this declaration is valid, without 65 /// emitting diagnostics. 66 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 67 // See if this is an auto-typed variable whose initializer we are parsing. 68 if (ParsingInitForAutoVars.count(D)) 69 return false; 70 71 // See if this is a deleted function. 72 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 73 if (FD->isDeleted()) 74 return false; 75 76 // If the function has a deduced return type, and we can't deduce it, 77 // then we can't use it either. 78 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 79 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 80 return false; 81 82 // See if this is an aligned allocation/deallocation function that is 83 // unavailable. 84 if (TreatUnavailableAsInvalid && 85 isUnavailableAlignedAllocationFunction(*FD)) 86 return false; 87 } 88 89 // See if this function is unavailable. 90 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 91 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 92 return false; 93 94 if (isa<UnresolvedUsingIfExistsDecl>(D)) 95 return false; 96 97 return true; 98 } 99 100 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 101 // Warn if this is used but marked unused. 102 if (const auto *A = D->getAttr<UnusedAttr>()) { 103 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 104 // should diagnose them. 105 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 106 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 107 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 108 if (DC && !DC->hasAttr<UnusedAttr>()) 109 S.Diag(Loc, diag::warn_used_but_marked_unused) << D; 110 } 111 } 112 } 113 114 /// Emit a note explaining that this function is deleted. 115 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 116 assert(Decl && Decl->isDeleted()); 117 118 if (Decl->isDefaulted()) { 119 // If the method was explicitly defaulted, point at that declaration. 120 if (!Decl->isImplicit()) 121 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 122 123 // Try to diagnose why this special member function was implicitly 124 // deleted. This might fail, if that reason no longer applies. 125 DiagnoseDeletedDefaultedFunction(Decl); 126 return; 127 } 128 129 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 130 if (Ctor && Ctor->isInheritingConstructor()) 131 return NoteDeletedInheritingConstructor(Ctor); 132 133 Diag(Decl->getLocation(), diag::note_availability_specified_here) 134 << Decl << 1; 135 } 136 137 /// Determine whether a FunctionDecl was ever declared with an 138 /// explicit storage class. 139 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 140 for (auto *I : D->redecls()) { 141 if (I->getStorageClass() != SC_None) 142 return true; 143 } 144 return false; 145 } 146 147 /// Check whether we're in an extern inline function and referring to a 148 /// variable or function with internal linkage (C11 6.7.4p3). 149 /// 150 /// This is only a warning because we used to silently accept this code, but 151 /// in many cases it will not behave correctly. This is not enabled in C++ mode 152 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 153 /// and so while there may still be user mistakes, most of the time we can't 154 /// prove that there are errors. 155 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 156 const NamedDecl *D, 157 SourceLocation Loc) { 158 // This is disabled under C++; there are too many ways for this to fire in 159 // contexts where the warning is a false positive, or where it is technically 160 // correct but benign. 161 if (S.getLangOpts().CPlusPlus) 162 return; 163 164 // Check if this is an inlined function or method. 165 FunctionDecl *Current = S.getCurFunctionDecl(); 166 if (!Current) 167 return; 168 if (!Current->isInlined()) 169 return; 170 if (!Current->isExternallyVisible()) 171 return; 172 173 // Check if the decl has internal linkage. 174 if (D->getFormalLinkage() != InternalLinkage) 175 return; 176 177 // Downgrade from ExtWarn to Extension if 178 // (1) the supposedly external inline function is in the main file, 179 // and probably won't be included anywhere else. 180 // (2) the thing we're referencing is a pure function. 181 // (3) the thing we're referencing is another inline function. 182 // This last can give us false negatives, but it's better than warning on 183 // wrappers for simple C library functions. 184 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 185 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 186 if (!DowngradeWarning && UsedFn) 187 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 188 189 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 190 : diag::ext_internal_in_extern_inline) 191 << /*IsVar=*/!UsedFn << D; 192 193 S.MaybeSuggestAddingStaticToDecl(Current); 194 195 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 196 << D; 197 } 198 199 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 200 const FunctionDecl *First = Cur->getFirstDecl(); 201 202 // Suggest "static" on the function, if possible. 203 if (!hasAnyExplicitStorageClass(First)) { 204 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 205 Diag(DeclBegin, diag::note_convert_inline_to_static) 206 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 207 } 208 } 209 210 /// Determine whether the use of this declaration is valid, and 211 /// emit any corresponding diagnostics. 212 /// 213 /// This routine diagnoses various problems with referencing 214 /// declarations that can occur when using a declaration. For example, 215 /// it might warn if a deprecated or unavailable declaration is being 216 /// used, or produce an error (and return true) if a C++0x deleted 217 /// function is being used. 218 /// 219 /// \returns true if there was an error (this declaration cannot be 220 /// referenced), false otherwise. 221 /// 222 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 223 const ObjCInterfaceDecl *UnknownObjCClass, 224 bool ObjCPropertyAccess, 225 bool AvoidPartialAvailabilityChecks, 226 ObjCInterfaceDecl *ClassReceiver, 227 bool SkipTrailingRequiresClause) { 228 SourceLocation Loc = Locs.front(); 229 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 230 // If there were any diagnostics suppressed by template argument deduction, 231 // emit them now. 232 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 233 if (Pos != SuppressedDiagnostics.end()) { 234 for (const PartialDiagnosticAt &Suppressed : Pos->second) 235 Diag(Suppressed.first, Suppressed.second); 236 237 // Clear out the list of suppressed diagnostics, so that we don't emit 238 // them again for this specialization. However, we don't obsolete this 239 // entry from the table, because we want to avoid ever emitting these 240 // diagnostics again. 241 Pos->second.clear(); 242 } 243 244 // C++ [basic.start.main]p3: 245 // The function 'main' shall not be used within a program. 246 if (cast<FunctionDecl>(D)->isMain()) 247 Diag(Loc, diag::ext_main_used); 248 249 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc); 250 } 251 252 // See if this is an auto-typed variable whose initializer we are parsing. 253 if (ParsingInitForAutoVars.count(D)) { 254 if (isa<BindingDecl>(D)) { 255 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 256 << D->getDeclName(); 257 } else { 258 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 259 << D->getDeclName() << cast<VarDecl>(D)->getType(); 260 } 261 return true; 262 } 263 264 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 265 // See if this is a deleted function. 266 if (FD->isDeleted()) { 267 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 268 if (Ctor && Ctor->isInheritingConstructor()) 269 Diag(Loc, diag::err_deleted_inherited_ctor_use) 270 << Ctor->getParent() 271 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 272 else 273 Diag(Loc, diag::err_deleted_function_use); 274 NoteDeletedFunction(FD); 275 return true; 276 } 277 278 // [expr.prim.id]p4 279 // A program that refers explicitly or implicitly to a function with a 280 // trailing requires-clause whose constraint-expression is not satisfied, 281 // other than to declare it, is ill-formed. [...] 282 // 283 // See if this is a function with constraints that need to be satisfied. 284 // Check this before deducing the return type, as it might instantiate the 285 // definition. 286 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) { 287 ConstraintSatisfaction Satisfaction; 288 if (CheckFunctionConstraints(FD, Satisfaction, Loc, 289 /*ForOverloadResolution*/ true)) 290 // A diagnostic will have already been generated (non-constant 291 // constraint expression, for example) 292 return true; 293 if (!Satisfaction.IsSatisfied) { 294 Diag(Loc, 295 diag::err_reference_to_function_with_unsatisfied_constraints) 296 << D; 297 DiagnoseUnsatisfiedConstraint(Satisfaction); 298 return true; 299 } 300 } 301 302 // If the function has a deduced return type, and we can't deduce it, 303 // then we can't use it either. 304 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 305 DeduceReturnType(FD, Loc)) 306 return true; 307 308 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 309 return true; 310 311 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD)) 312 return true; 313 } 314 315 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 316 // Lambdas are only default-constructible or assignable in C++2a onwards. 317 if (MD->getParent()->isLambda() && 318 ((isa<CXXConstructorDecl>(MD) && 319 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 320 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 321 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 322 << !isa<CXXConstructorDecl>(MD); 323 } 324 } 325 326 auto getReferencedObjCProp = [](const NamedDecl *D) -> 327 const ObjCPropertyDecl * { 328 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 329 return MD->findPropertyDecl(); 330 return nullptr; 331 }; 332 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 333 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 334 return true; 335 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 336 return true; 337 } 338 339 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 340 // Only the variables omp_in and omp_out are allowed in the combiner. 341 // Only the variables omp_priv and omp_orig are allowed in the 342 // initializer-clause. 343 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 344 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 345 isa<VarDecl>(D)) { 346 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 347 << getCurFunction()->HasOMPDeclareReductionCombiner; 348 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 349 return true; 350 } 351 352 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions 353 // List-items in map clauses on this construct may only refer to the declared 354 // variable var and entities that could be referenced by a procedure defined 355 // at the same location. 356 // [OpenMP 5.2] Also allow iterator declared variables. 357 if (LangOpts.OpenMP && isa<VarDecl>(D) && 358 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) { 359 Diag(Loc, diag::err_omp_declare_mapper_wrong_var) 360 << getOpenMPDeclareMapperVarName(); 361 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 362 return true; 363 } 364 365 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) { 366 Diag(Loc, diag::err_use_of_empty_using_if_exists); 367 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here); 368 return true; 369 } 370 371 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 372 AvoidPartialAvailabilityChecks, ClassReceiver); 373 374 DiagnoseUnusedOfDecl(*this, D, Loc); 375 376 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 377 378 if (auto *VD = dyn_cast<ValueDecl>(D)) 379 checkTypeSupport(VD->getType(), Loc, VD); 380 381 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) { 382 if (!Context.getTargetInfo().isTLSSupported()) 383 if (const auto *VD = dyn_cast<VarDecl>(D)) 384 if (VD->getTLSKind() != VarDecl::TLS_None) 385 targetDiag(*Locs.begin(), diag::err_thread_unsupported); 386 } 387 388 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) && 389 !isUnevaluatedContext()) { 390 // C++ [expr.prim.req.nested] p3 391 // A local parameter shall only appear as an unevaluated operand 392 // (Clause 8) within the constraint-expression. 393 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context) 394 << D; 395 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 396 return true; 397 } 398 399 return false; 400 } 401 402 /// DiagnoseSentinelCalls - This routine checks whether a call or 403 /// message-send is to a declaration with the sentinel attribute, and 404 /// if so, it checks that the requirements of the sentinel are 405 /// satisfied. 406 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 407 ArrayRef<Expr *> Args) { 408 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 409 if (!attr) 410 return; 411 412 // The number of formal parameters of the declaration. 413 unsigned numFormalParams; 414 415 // The kind of declaration. This is also an index into a %select in 416 // the diagnostic. 417 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 418 419 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 420 numFormalParams = MD->param_size(); 421 calleeType = CT_Method; 422 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 423 numFormalParams = FD->param_size(); 424 calleeType = CT_Function; 425 } else if (isa<VarDecl>(D)) { 426 QualType type = cast<ValueDecl>(D)->getType(); 427 const FunctionType *fn = nullptr; 428 if (const PointerType *ptr = type->getAs<PointerType>()) { 429 fn = ptr->getPointeeType()->getAs<FunctionType>(); 430 if (!fn) return; 431 calleeType = CT_Function; 432 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 433 fn = ptr->getPointeeType()->castAs<FunctionType>(); 434 calleeType = CT_Block; 435 } else { 436 return; 437 } 438 439 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 440 numFormalParams = proto->getNumParams(); 441 } else { 442 numFormalParams = 0; 443 } 444 } else { 445 return; 446 } 447 448 // "nullPos" is the number of formal parameters at the end which 449 // effectively count as part of the variadic arguments. This is 450 // useful if you would prefer to not have *any* formal parameters, 451 // but the language forces you to have at least one. 452 unsigned nullPos = attr->getNullPos(); 453 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 454 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 455 456 // The number of arguments which should follow the sentinel. 457 unsigned numArgsAfterSentinel = attr->getSentinel(); 458 459 // If there aren't enough arguments for all the formal parameters, 460 // the sentinel, and the args after the sentinel, complain. 461 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 462 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 463 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 464 return; 465 } 466 467 // Otherwise, find the sentinel expression. 468 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 469 if (!sentinelExpr) return; 470 if (sentinelExpr->isValueDependent()) return; 471 if (Context.isSentinelNullExpr(sentinelExpr)) return; 472 473 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 474 // or 'NULL' if those are actually defined in the context. Only use 475 // 'nil' for ObjC methods, where it's much more likely that the 476 // variadic arguments form a list of object pointers. 477 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 478 std::string NullValue; 479 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 480 NullValue = "nil"; 481 else if (getLangOpts().CPlusPlus11) 482 NullValue = "nullptr"; 483 else if (PP.isMacroDefined("NULL")) 484 NullValue = "NULL"; 485 else 486 NullValue = "(void*) 0"; 487 488 if (MissingNilLoc.isInvalid()) 489 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 490 else 491 Diag(MissingNilLoc, diag::warn_missing_sentinel) 492 << int(calleeType) 493 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 494 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 495 } 496 497 SourceRange Sema::getExprRange(Expr *E) const { 498 return E ? E->getSourceRange() : SourceRange(); 499 } 500 501 //===----------------------------------------------------------------------===// 502 // Standard Promotions and Conversions 503 //===----------------------------------------------------------------------===// 504 505 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 506 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 507 // Handle any placeholder expressions which made it here. 508 if (E->hasPlaceholderType()) { 509 ExprResult result = CheckPlaceholderExpr(E); 510 if (result.isInvalid()) return ExprError(); 511 E = result.get(); 512 } 513 514 QualType Ty = E->getType(); 515 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 516 517 if (Ty->isFunctionType()) { 518 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 519 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 520 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 521 return ExprError(); 522 523 E = ImpCastExprToType(E, Context.getPointerType(Ty), 524 CK_FunctionToPointerDecay).get(); 525 } else if (Ty->isArrayType()) { 526 // In C90 mode, arrays only promote to pointers if the array expression is 527 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 528 // type 'array of type' is converted to an expression that has type 'pointer 529 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 530 // that has type 'array of type' ...". The relevant change is "an lvalue" 531 // (C90) to "an expression" (C99). 532 // 533 // C++ 4.2p1: 534 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 535 // T" can be converted to an rvalue of type "pointer to T". 536 // 537 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) { 538 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 539 CK_ArrayToPointerDecay); 540 if (Res.isInvalid()) 541 return ExprError(); 542 E = Res.get(); 543 } 544 } 545 return E; 546 } 547 548 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 549 // Check to see if we are dereferencing a null pointer. If so, 550 // and if not volatile-qualified, this is undefined behavior that the 551 // optimizer will delete, so warn about it. People sometimes try to use this 552 // to get a deterministic trap and are surprised by clang's behavior. This 553 // only handles the pattern "*null", which is a very syntactic check. 554 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()); 555 if (UO && UO->getOpcode() == UO_Deref && 556 UO->getSubExpr()->getType()->isPointerType()) { 557 const LangAS AS = 558 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace(); 559 if ((!isTargetAddressSpace(AS) || 560 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) && 561 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant( 562 S.Context, Expr::NPC_ValueDependentIsNotNull) && 563 !UO->getType().isVolatileQualified()) { 564 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 565 S.PDiag(diag::warn_indirection_through_null) 566 << UO->getSubExpr()->getSourceRange()); 567 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 568 S.PDiag(diag::note_indirection_through_null)); 569 } 570 } 571 } 572 573 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 574 SourceLocation AssignLoc, 575 const Expr* RHS) { 576 const ObjCIvarDecl *IV = OIRE->getDecl(); 577 if (!IV) 578 return; 579 580 DeclarationName MemberName = IV->getDeclName(); 581 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 582 if (!Member || !Member->isStr("isa")) 583 return; 584 585 const Expr *Base = OIRE->getBase(); 586 QualType BaseType = Base->getType(); 587 if (OIRE->isArrow()) 588 BaseType = BaseType->getPointeeType(); 589 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 590 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 591 ObjCInterfaceDecl *ClassDeclared = nullptr; 592 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 593 if (!ClassDeclared->getSuperClass() 594 && (*ClassDeclared->ivar_begin()) == IV) { 595 if (RHS) { 596 NamedDecl *ObjectSetClass = 597 S.LookupSingleName(S.TUScope, 598 &S.Context.Idents.get("object_setClass"), 599 SourceLocation(), S.LookupOrdinaryName); 600 if (ObjectSetClass) { 601 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 602 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 603 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 604 "object_setClass(") 605 << FixItHint::CreateReplacement( 606 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 607 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 608 } 609 else 610 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 611 } else { 612 NamedDecl *ObjectGetClass = 613 S.LookupSingleName(S.TUScope, 614 &S.Context.Idents.get("object_getClass"), 615 SourceLocation(), S.LookupOrdinaryName); 616 if (ObjectGetClass) 617 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 618 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 619 "object_getClass(") 620 << FixItHint::CreateReplacement( 621 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 622 else 623 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 624 } 625 S.Diag(IV->getLocation(), diag::note_ivar_decl); 626 } 627 } 628 } 629 630 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 631 // Handle any placeholder expressions which made it here. 632 if (E->hasPlaceholderType()) { 633 ExprResult result = CheckPlaceholderExpr(E); 634 if (result.isInvalid()) return ExprError(); 635 E = result.get(); 636 } 637 638 // C++ [conv.lval]p1: 639 // A glvalue of a non-function, non-array type T can be 640 // converted to a prvalue. 641 if (!E->isGLValue()) return E; 642 643 QualType T = E->getType(); 644 assert(!T.isNull() && "r-value conversion on typeless expression?"); 645 646 // lvalue-to-rvalue conversion cannot be applied to function or array types. 647 if (T->isFunctionType() || T->isArrayType()) 648 return E; 649 650 // We don't want to throw lvalue-to-rvalue casts on top of 651 // expressions of certain types in C++. 652 if (getLangOpts().CPlusPlus && 653 (E->getType() == Context.OverloadTy || 654 T->isDependentType() || 655 T->isRecordType())) 656 return E; 657 658 // The C standard is actually really unclear on this point, and 659 // DR106 tells us what the result should be but not why. It's 660 // generally best to say that void types just doesn't undergo 661 // lvalue-to-rvalue at all. Note that expressions of unqualified 662 // 'void' type are never l-values, but qualified void can be. 663 if (T->isVoidType()) 664 return E; 665 666 // OpenCL usually rejects direct accesses to values of 'half' type. 667 if (getLangOpts().OpenCL && 668 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 669 T->isHalfType()) { 670 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 671 << 0 << T; 672 return ExprError(); 673 } 674 675 CheckForNullPointerDereference(*this, E); 676 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 677 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 678 &Context.Idents.get("object_getClass"), 679 SourceLocation(), LookupOrdinaryName); 680 if (ObjectGetClass) 681 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 682 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 683 << FixItHint::CreateReplacement( 684 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 685 else 686 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 687 } 688 else if (const ObjCIvarRefExpr *OIRE = 689 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 690 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 691 692 // C++ [conv.lval]p1: 693 // [...] If T is a non-class type, the type of the prvalue is the 694 // cv-unqualified version of T. Otherwise, the type of the 695 // rvalue is T. 696 // 697 // C99 6.3.2.1p2: 698 // If the lvalue has qualified type, the value has the unqualified 699 // version of the type of the lvalue; otherwise, the value has the 700 // type of the lvalue. 701 if (T.hasQualifiers()) 702 T = T.getUnqualifiedType(); 703 704 // Under the MS ABI, lock down the inheritance model now. 705 if (T->isMemberPointerType() && 706 Context.getTargetInfo().getCXXABI().isMicrosoft()) 707 (void)isCompleteType(E->getExprLoc(), T); 708 709 ExprResult Res = CheckLValueToRValueConversionOperand(E); 710 if (Res.isInvalid()) 711 return Res; 712 E = Res.get(); 713 714 // Loading a __weak object implicitly retains the value, so we need a cleanup to 715 // balance that. 716 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 717 Cleanup.setExprNeedsCleanups(true); 718 719 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 720 Cleanup.setExprNeedsCleanups(true); 721 722 // C++ [conv.lval]p3: 723 // If T is cv std::nullptr_t, the result is a null pointer constant. 724 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue; 725 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue, 726 CurFPFeatureOverrides()); 727 728 // C11 6.3.2.1p2: 729 // ... if the lvalue has atomic type, the value has the non-atomic version 730 // of the type of the lvalue ... 731 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 732 T = Atomic->getValueType().getUnqualifiedType(); 733 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 734 nullptr, VK_PRValue, FPOptionsOverride()); 735 } 736 737 return Res; 738 } 739 740 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 741 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 742 if (Res.isInvalid()) 743 return ExprError(); 744 Res = DefaultLvalueConversion(Res.get()); 745 if (Res.isInvalid()) 746 return ExprError(); 747 return Res; 748 } 749 750 /// CallExprUnaryConversions - a special case of an unary conversion 751 /// performed on a function designator of a call expression. 752 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 753 QualType Ty = E->getType(); 754 ExprResult Res = E; 755 // Only do implicit cast for a function type, but not for a pointer 756 // to function type. 757 if (Ty->isFunctionType()) { 758 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 759 CK_FunctionToPointerDecay); 760 if (Res.isInvalid()) 761 return ExprError(); 762 } 763 Res = DefaultLvalueConversion(Res.get()); 764 if (Res.isInvalid()) 765 return ExprError(); 766 return Res.get(); 767 } 768 769 /// UsualUnaryConversions - Performs various conversions that are common to most 770 /// operators (C99 6.3). The conversions of array and function types are 771 /// sometimes suppressed. For example, the array->pointer conversion doesn't 772 /// apply if the array is an argument to the sizeof or address (&) operators. 773 /// In these instances, this routine should *not* be called. 774 ExprResult Sema::UsualUnaryConversions(Expr *E) { 775 // First, convert to an r-value. 776 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 777 if (Res.isInvalid()) 778 return ExprError(); 779 E = Res.get(); 780 781 QualType Ty = E->getType(); 782 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 783 784 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod(); 785 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() && 786 (getLangOpts().getFPEvalMethod() != 787 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine || 788 PP.getLastFPEvalPragmaLocation().isValid())) { 789 switch (EvalMethod) { 790 default: 791 llvm_unreachable("Unrecognized float evaluation method"); 792 break; 793 case LangOptions::FEM_UnsetOnCommandLine: 794 llvm_unreachable("Float evaluation method should be set by now"); 795 break; 796 case LangOptions::FEM_Double: 797 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0) 798 // Widen the expression to double. 799 return Ty->isComplexType() 800 ? ImpCastExprToType(E, 801 Context.getComplexType(Context.DoubleTy), 802 CK_FloatingComplexCast) 803 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast); 804 break; 805 case LangOptions::FEM_Extended: 806 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0) 807 // Widen the expression to long double. 808 return Ty->isComplexType() 809 ? ImpCastExprToType( 810 E, Context.getComplexType(Context.LongDoubleTy), 811 CK_FloatingComplexCast) 812 : ImpCastExprToType(E, Context.LongDoubleTy, 813 CK_FloatingCast); 814 break; 815 } 816 } 817 818 // Half FP have to be promoted to float unless it is natively supported 819 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 820 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 821 822 // Try to perform integral promotions if the object has a theoretically 823 // promotable type. 824 if (Ty->isIntegralOrUnscopedEnumerationType()) { 825 // C99 6.3.1.1p2: 826 // 827 // The following may be used in an expression wherever an int or 828 // unsigned int may be used: 829 // - an object or expression with an integer type whose integer 830 // conversion rank is less than or equal to the rank of int 831 // and unsigned int. 832 // - A bit-field of type _Bool, int, signed int, or unsigned int. 833 // 834 // If an int can represent all values of the original type, the 835 // value is converted to an int; otherwise, it is converted to an 836 // unsigned int. These are called the integer promotions. All 837 // other types are unchanged by the integer promotions. 838 839 QualType PTy = Context.isPromotableBitField(E); 840 if (!PTy.isNull()) { 841 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 842 return E; 843 } 844 if (Context.isPromotableIntegerType(Ty)) { 845 QualType PT = Context.getPromotedIntegerType(Ty); 846 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 847 return E; 848 } 849 } 850 return E; 851 } 852 853 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 854 /// do not have a prototype. Arguments that have type float or __fp16 855 /// are promoted to double. All other argument types are converted by 856 /// UsualUnaryConversions(). 857 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 858 QualType Ty = E->getType(); 859 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 860 861 ExprResult Res = UsualUnaryConversions(E); 862 if (Res.isInvalid()) 863 return ExprError(); 864 E = Res.get(); 865 866 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 867 // promote to double. 868 // Note that default argument promotion applies only to float (and 869 // half/fp16); it does not apply to _Float16. 870 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 871 if (BTy && (BTy->getKind() == BuiltinType::Half || 872 BTy->getKind() == BuiltinType::Float)) { 873 if (getLangOpts().OpenCL && 874 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) { 875 if (BTy->getKind() == BuiltinType::Half) { 876 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get(); 877 } 878 } else { 879 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 880 } 881 } 882 if (BTy && 883 getLangOpts().getExtendIntArgs() == 884 LangOptions::ExtendArgsKind::ExtendTo64 && 885 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() && 886 Context.getTypeSizeInChars(BTy) < 887 Context.getTypeSizeInChars(Context.LongLongTy)) { 888 E = (Ty->isUnsignedIntegerType()) 889 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast) 890 .get() 891 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get(); 892 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() && 893 "Unexpected typesize for LongLongTy"); 894 } 895 896 // C++ performs lvalue-to-rvalue conversion as a default argument 897 // promotion, even on class types, but note: 898 // C++11 [conv.lval]p2: 899 // When an lvalue-to-rvalue conversion occurs in an unevaluated 900 // operand or a subexpression thereof the value contained in the 901 // referenced object is not accessed. Otherwise, if the glvalue 902 // has a class type, the conversion copy-initializes a temporary 903 // of type T from the glvalue and the result of the conversion 904 // is a prvalue for the temporary. 905 // FIXME: add some way to gate this entire thing for correctness in 906 // potentially potentially evaluated contexts. 907 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 908 ExprResult Temp = PerformCopyInitialization( 909 InitializedEntity::InitializeTemporary(E->getType()), 910 E->getExprLoc(), E); 911 if (Temp.isInvalid()) 912 return ExprError(); 913 E = Temp.get(); 914 } 915 916 return E; 917 } 918 919 /// Determine the degree of POD-ness for an expression. 920 /// Incomplete types are considered POD, since this check can be performed 921 /// when we're in an unevaluated context. 922 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 923 if (Ty->isIncompleteType()) { 924 // C++11 [expr.call]p7: 925 // After these conversions, if the argument does not have arithmetic, 926 // enumeration, pointer, pointer to member, or class type, the program 927 // is ill-formed. 928 // 929 // Since we've already performed array-to-pointer and function-to-pointer 930 // decay, the only such type in C++ is cv void. This also handles 931 // initializer lists as variadic arguments. 932 if (Ty->isVoidType()) 933 return VAK_Invalid; 934 935 if (Ty->isObjCObjectType()) 936 return VAK_Invalid; 937 return VAK_Valid; 938 } 939 940 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 941 return VAK_Invalid; 942 943 if (Ty.isCXX98PODType(Context)) 944 return VAK_Valid; 945 946 // C++11 [expr.call]p7: 947 // Passing a potentially-evaluated argument of class type (Clause 9) 948 // having a non-trivial copy constructor, a non-trivial move constructor, 949 // or a non-trivial destructor, with no corresponding parameter, 950 // is conditionally-supported with implementation-defined semantics. 951 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 952 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 953 if (!Record->hasNonTrivialCopyConstructor() && 954 !Record->hasNonTrivialMoveConstructor() && 955 !Record->hasNonTrivialDestructor()) 956 return VAK_ValidInCXX11; 957 958 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 959 return VAK_Valid; 960 961 if (Ty->isObjCObjectType()) 962 return VAK_Invalid; 963 964 if (getLangOpts().MSVCCompat) 965 return VAK_MSVCUndefined; 966 967 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 968 // permitted to reject them. We should consider doing so. 969 return VAK_Undefined; 970 } 971 972 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 973 // Don't allow one to pass an Objective-C interface to a vararg. 974 const QualType &Ty = E->getType(); 975 VarArgKind VAK = isValidVarArgType(Ty); 976 977 // Complain about passing non-POD types through varargs. 978 switch (VAK) { 979 case VAK_ValidInCXX11: 980 DiagRuntimeBehavior( 981 E->getBeginLoc(), nullptr, 982 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 983 [[fallthrough]]; 984 case VAK_Valid: 985 if (Ty->isRecordType()) { 986 // This is unlikely to be what the user intended. If the class has a 987 // 'c_str' member function, the user probably meant to call that. 988 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 989 PDiag(diag::warn_pass_class_arg_to_vararg) 990 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 991 } 992 break; 993 994 case VAK_Undefined: 995 case VAK_MSVCUndefined: 996 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 997 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 998 << getLangOpts().CPlusPlus11 << Ty << CT); 999 break; 1000 1001 case VAK_Invalid: 1002 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 1003 Diag(E->getBeginLoc(), 1004 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 1005 << Ty << CT; 1006 else if (Ty->isObjCObjectType()) 1007 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 1008 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 1009 << Ty << CT); 1010 else 1011 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 1012 << isa<InitListExpr>(E) << Ty << CT; 1013 break; 1014 } 1015 } 1016 1017 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 1018 /// will create a trap if the resulting type is not a POD type. 1019 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 1020 FunctionDecl *FDecl) { 1021 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 1022 // Strip the unbridged-cast placeholder expression off, if applicable. 1023 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 1024 (CT == VariadicMethod || 1025 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 1026 E = stripARCUnbridgedCast(E); 1027 1028 // Otherwise, do normal placeholder checking. 1029 } else { 1030 ExprResult ExprRes = CheckPlaceholderExpr(E); 1031 if (ExprRes.isInvalid()) 1032 return ExprError(); 1033 E = ExprRes.get(); 1034 } 1035 } 1036 1037 ExprResult ExprRes = DefaultArgumentPromotion(E); 1038 if (ExprRes.isInvalid()) 1039 return ExprError(); 1040 1041 // Copy blocks to the heap. 1042 if (ExprRes.get()->getType()->isBlockPointerType()) 1043 maybeExtendBlockObject(ExprRes); 1044 1045 E = ExprRes.get(); 1046 1047 // Diagnostics regarding non-POD argument types are 1048 // emitted along with format string checking in Sema::CheckFunctionCall(). 1049 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 1050 // Turn this into a trap. 1051 CXXScopeSpec SS; 1052 SourceLocation TemplateKWLoc; 1053 UnqualifiedId Name; 1054 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 1055 E->getBeginLoc()); 1056 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name, 1057 /*HasTrailingLParen=*/true, 1058 /*IsAddressOfOperand=*/false); 1059 if (TrapFn.isInvalid()) 1060 return ExprError(); 1061 1062 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 1063 std::nullopt, E->getEndLoc()); 1064 if (Call.isInvalid()) 1065 return ExprError(); 1066 1067 ExprResult Comma = 1068 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 1069 if (Comma.isInvalid()) 1070 return ExprError(); 1071 return Comma.get(); 1072 } 1073 1074 if (!getLangOpts().CPlusPlus && 1075 RequireCompleteType(E->getExprLoc(), E->getType(), 1076 diag::err_call_incomplete_argument)) 1077 return ExprError(); 1078 1079 return E; 1080 } 1081 1082 /// Converts an integer to complex float type. Helper function of 1083 /// UsualArithmeticConversions() 1084 /// 1085 /// \return false if the integer expression is an integer type and is 1086 /// successfully converted to the complex type. 1087 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 1088 ExprResult &ComplexExpr, 1089 QualType IntTy, 1090 QualType ComplexTy, 1091 bool SkipCast) { 1092 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1093 if (SkipCast) return false; 1094 if (IntTy->isIntegerType()) { 1095 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType(); 1096 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1097 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1098 CK_FloatingRealToComplex); 1099 } else { 1100 assert(IntTy->isComplexIntegerType()); 1101 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1102 CK_IntegralComplexToFloatingComplex); 1103 } 1104 return false; 1105 } 1106 1107 // This handles complex/complex, complex/float, or float/complex. 1108 // When both operands are complex, the shorter operand is converted to the 1109 // type of the longer, and that is the type of the result. This corresponds 1110 // to what is done when combining two real floating-point operands. 1111 // The fun begins when size promotion occur across type domains. 1112 // From H&S 6.3.4: When one operand is complex and the other is a real 1113 // floating-point type, the less precise type is converted, within it's 1114 // real or complex domain, to the precision of the other type. For example, 1115 // when combining a "long double" with a "double _Complex", the 1116 // "double _Complex" is promoted to "long double _Complex". 1117 static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter, 1118 QualType ShorterType, 1119 QualType LongerType, 1120 bool PromotePrecision) { 1121 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType()); 1122 QualType Result = 1123 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType); 1124 1125 if (PromotePrecision) { 1126 if (isa<ComplexType>(ShorterType.getCanonicalType())) { 1127 Shorter = 1128 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast); 1129 } else { 1130 if (LongerIsComplex) 1131 LongerType = LongerType->castAs<ComplexType>()->getElementType(); 1132 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast); 1133 } 1134 } 1135 return Result; 1136 } 1137 1138 /// Handle arithmetic conversion with complex types. Helper function of 1139 /// UsualArithmeticConversions() 1140 static QualType handleComplexConversion(Sema &S, ExprResult &LHS, 1141 ExprResult &RHS, QualType LHSType, 1142 QualType RHSType, bool IsCompAssign) { 1143 // if we have an integer operand, the result is the complex type. 1144 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1145 /*SkipCast=*/false)) 1146 return LHSType; 1147 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1148 /*SkipCast=*/IsCompAssign)) 1149 return RHSType; 1150 1151 // Compute the rank of the two types, regardless of whether they are complex. 1152 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1153 if (Order < 0) 1154 // Promote the precision of the LHS if not an assignment. 1155 return handleComplexFloatConversion(S, LHS, LHSType, RHSType, 1156 /*PromotePrecision=*/!IsCompAssign); 1157 // Promote the precision of the RHS unless it is already the same as the LHS. 1158 return handleComplexFloatConversion(S, RHS, RHSType, LHSType, 1159 /*PromotePrecision=*/Order > 0); 1160 } 1161 1162 /// Handle arithmetic conversion from integer to float. Helper function 1163 /// of UsualArithmeticConversions() 1164 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1165 ExprResult &IntExpr, 1166 QualType FloatTy, QualType IntTy, 1167 bool ConvertFloat, bool ConvertInt) { 1168 if (IntTy->isIntegerType()) { 1169 if (ConvertInt) 1170 // Convert intExpr to the lhs floating point type. 1171 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1172 CK_IntegralToFloating); 1173 return FloatTy; 1174 } 1175 1176 // Convert both sides to the appropriate complex float. 1177 assert(IntTy->isComplexIntegerType()); 1178 QualType result = S.Context.getComplexType(FloatTy); 1179 1180 // _Complex int -> _Complex float 1181 if (ConvertInt) 1182 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1183 CK_IntegralComplexToFloatingComplex); 1184 1185 // float -> _Complex float 1186 if (ConvertFloat) 1187 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1188 CK_FloatingRealToComplex); 1189 1190 return result; 1191 } 1192 1193 /// Handle arithmethic conversion with floating point types. Helper 1194 /// function of UsualArithmeticConversions() 1195 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1196 ExprResult &RHS, QualType LHSType, 1197 QualType RHSType, bool IsCompAssign) { 1198 bool LHSFloat = LHSType->isRealFloatingType(); 1199 bool RHSFloat = RHSType->isRealFloatingType(); 1200 1201 // N1169 4.1.4: If one of the operands has a floating type and the other 1202 // operand has a fixed-point type, the fixed-point operand 1203 // is converted to the floating type [...] 1204 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) { 1205 if (LHSFloat) 1206 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating); 1207 else if (!IsCompAssign) 1208 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating); 1209 return LHSFloat ? LHSType : RHSType; 1210 } 1211 1212 // If we have two real floating types, convert the smaller operand 1213 // to the bigger result. 1214 if (LHSFloat && RHSFloat) { 1215 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1216 if (order > 0) { 1217 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1218 return LHSType; 1219 } 1220 1221 assert(order < 0 && "illegal float comparison"); 1222 if (!IsCompAssign) 1223 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1224 return RHSType; 1225 } 1226 1227 if (LHSFloat) { 1228 // Half FP has to be promoted to float unless it is natively supported 1229 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1230 LHSType = S.Context.FloatTy; 1231 1232 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1233 /*ConvertFloat=*/!IsCompAssign, 1234 /*ConvertInt=*/ true); 1235 } 1236 assert(RHSFloat); 1237 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1238 /*ConvertFloat=*/ true, 1239 /*ConvertInt=*/!IsCompAssign); 1240 } 1241 1242 /// Diagnose attempts to convert between __float128, __ibm128 and 1243 /// long double if there is no support for such conversion. 1244 /// Helper function of UsualArithmeticConversions(). 1245 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1246 QualType RHSType) { 1247 // No issue if either is not a floating point type. 1248 if (!LHSType->isFloatingType() || !RHSType->isFloatingType()) 1249 return false; 1250 1251 // No issue if both have the same 128-bit float semantics. 1252 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1253 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1254 1255 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType; 1256 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType; 1257 1258 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem); 1259 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem); 1260 1261 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() || 1262 &RHSSem != &llvm::APFloat::IEEEquad()) && 1263 (&LHSSem != &llvm::APFloat::IEEEquad() || 1264 &RHSSem != &llvm::APFloat::PPCDoubleDouble())) 1265 return false; 1266 1267 return true; 1268 } 1269 1270 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1271 1272 namespace { 1273 /// These helper callbacks are placed in an anonymous namespace to 1274 /// permit their use as function template parameters. 1275 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1276 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1277 } 1278 1279 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1280 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1281 CK_IntegralComplexCast); 1282 } 1283 } 1284 1285 /// Handle integer arithmetic conversions. Helper function of 1286 /// UsualArithmeticConversions() 1287 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1288 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1289 ExprResult &RHS, QualType LHSType, 1290 QualType RHSType, bool IsCompAssign) { 1291 // The rules for this case are in C99 6.3.1.8 1292 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1293 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1294 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1295 if (LHSSigned == RHSSigned) { 1296 // Same signedness; use the higher-ranked type 1297 if (order >= 0) { 1298 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1299 return LHSType; 1300 } else if (!IsCompAssign) 1301 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1302 return RHSType; 1303 } else if (order != (LHSSigned ? 1 : -1)) { 1304 // The unsigned type has greater than or equal rank to the 1305 // signed type, so use the unsigned type 1306 if (RHSSigned) { 1307 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1308 return LHSType; 1309 } else if (!IsCompAssign) 1310 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1311 return RHSType; 1312 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1313 // The two types are different widths; if we are here, that 1314 // means the signed type is larger than the unsigned type, so 1315 // use the signed type. 1316 if (LHSSigned) { 1317 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1318 return LHSType; 1319 } else if (!IsCompAssign) 1320 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1321 return RHSType; 1322 } else { 1323 // The signed type is higher-ranked than the unsigned type, 1324 // but isn't actually any bigger (like unsigned int and long 1325 // on most 32-bit systems). Use the unsigned type corresponding 1326 // to the signed type. 1327 QualType result = 1328 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1329 RHS = (*doRHSCast)(S, RHS.get(), result); 1330 if (!IsCompAssign) 1331 LHS = (*doLHSCast)(S, LHS.get(), result); 1332 return result; 1333 } 1334 } 1335 1336 /// Handle conversions with GCC complex int extension. Helper function 1337 /// of UsualArithmeticConversions() 1338 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1339 ExprResult &RHS, QualType LHSType, 1340 QualType RHSType, 1341 bool IsCompAssign) { 1342 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1343 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1344 1345 if (LHSComplexInt && RHSComplexInt) { 1346 QualType LHSEltType = LHSComplexInt->getElementType(); 1347 QualType RHSEltType = RHSComplexInt->getElementType(); 1348 QualType ScalarType = 1349 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1350 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1351 1352 return S.Context.getComplexType(ScalarType); 1353 } 1354 1355 if (LHSComplexInt) { 1356 QualType LHSEltType = LHSComplexInt->getElementType(); 1357 QualType ScalarType = 1358 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1359 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1360 QualType ComplexType = S.Context.getComplexType(ScalarType); 1361 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1362 CK_IntegralRealToComplex); 1363 1364 return ComplexType; 1365 } 1366 1367 assert(RHSComplexInt); 1368 1369 QualType RHSEltType = RHSComplexInt->getElementType(); 1370 QualType ScalarType = 1371 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1372 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1373 QualType ComplexType = S.Context.getComplexType(ScalarType); 1374 1375 if (!IsCompAssign) 1376 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1377 CK_IntegralRealToComplex); 1378 return ComplexType; 1379 } 1380 1381 /// Return the rank of a given fixed point or integer type. The value itself 1382 /// doesn't matter, but the values must be increasing with proper increasing 1383 /// rank as described in N1169 4.1.1. 1384 static unsigned GetFixedPointRank(QualType Ty) { 1385 const auto *BTy = Ty->getAs<BuiltinType>(); 1386 assert(BTy && "Expected a builtin type."); 1387 1388 switch (BTy->getKind()) { 1389 case BuiltinType::ShortFract: 1390 case BuiltinType::UShortFract: 1391 case BuiltinType::SatShortFract: 1392 case BuiltinType::SatUShortFract: 1393 return 1; 1394 case BuiltinType::Fract: 1395 case BuiltinType::UFract: 1396 case BuiltinType::SatFract: 1397 case BuiltinType::SatUFract: 1398 return 2; 1399 case BuiltinType::LongFract: 1400 case BuiltinType::ULongFract: 1401 case BuiltinType::SatLongFract: 1402 case BuiltinType::SatULongFract: 1403 return 3; 1404 case BuiltinType::ShortAccum: 1405 case BuiltinType::UShortAccum: 1406 case BuiltinType::SatShortAccum: 1407 case BuiltinType::SatUShortAccum: 1408 return 4; 1409 case BuiltinType::Accum: 1410 case BuiltinType::UAccum: 1411 case BuiltinType::SatAccum: 1412 case BuiltinType::SatUAccum: 1413 return 5; 1414 case BuiltinType::LongAccum: 1415 case BuiltinType::ULongAccum: 1416 case BuiltinType::SatLongAccum: 1417 case BuiltinType::SatULongAccum: 1418 return 6; 1419 default: 1420 if (BTy->isInteger()) 1421 return 0; 1422 llvm_unreachable("Unexpected fixed point or integer type"); 1423 } 1424 } 1425 1426 /// handleFixedPointConversion - Fixed point operations between fixed 1427 /// point types and integers or other fixed point types do not fall under 1428 /// usual arithmetic conversion since these conversions could result in loss 1429 /// of precsision (N1169 4.1.4). These operations should be calculated with 1430 /// the full precision of their result type (N1169 4.1.6.2.1). 1431 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, 1432 QualType RHSTy) { 1433 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && 1434 "Expected at least one of the operands to be a fixed point type"); 1435 assert((LHSTy->isFixedPointOrIntegerType() || 1436 RHSTy->isFixedPointOrIntegerType()) && 1437 "Special fixed point arithmetic operation conversions are only " 1438 "applied to ints or other fixed point types"); 1439 1440 // If one operand has signed fixed-point type and the other operand has 1441 // unsigned fixed-point type, then the unsigned fixed-point operand is 1442 // converted to its corresponding signed fixed-point type and the resulting 1443 // type is the type of the converted operand. 1444 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType()) 1445 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy); 1446 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType()) 1447 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy); 1448 1449 // The result type is the type with the highest rank, whereby a fixed-point 1450 // conversion rank is always greater than an integer conversion rank; if the 1451 // type of either of the operands is a saturating fixedpoint type, the result 1452 // type shall be the saturating fixed-point type corresponding to the type 1453 // with the highest rank; the resulting value is converted (taking into 1454 // account rounding and overflow) to the precision of the resulting type. 1455 // Same ranks between signed and unsigned types are resolved earlier, so both 1456 // types are either signed or both unsigned at this point. 1457 unsigned LHSTyRank = GetFixedPointRank(LHSTy); 1458 unsigned RHSTyRank = GetFixedPointRank(RHSTy); 1459 1460 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy; 1461 1462 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType()) 1463 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy); 1464 1465 return ResultTy; 1466 } 1467 1468 /// Check that the usual arithmetic conversions can be performed on this pair of 1469 /// expressions that might be of enumeration type. 1470 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, 1471 SourceLocation Loc, 1472 Sema::ArithConvKind ACK) { 1473 // C++2a [expr.arith.conv]p1: 1474 // If one operand is of enumeration type and the other operand is of a 1475 // different enumeration type or a floating-point type, this behavior is 1476 // deprecated ([depr.arith.conv.enum]). 1477 // 1478 // Warn on this in all language modes. Produce a deprecation warning in C++20. 1479 // Eventually we will presumably reject these cases (in C++23 onwards?). 1480 QualType L = LHS->getType(), R = RHS->getType(); 1481 bool LEnum = L->isUnscopedEnumerationType(), 1482 REnum = R->isUnscopedEnumerationType(); 1483 bool IsCompAssign = ACK == Sema::ACK_CompAssign; 1484 if ((!IsCompAssign && LEnum && R->isFloatingType()) || 1485 (REnum && L->isFloatingType())) { 1486 S.Diag(Loc, S.getLangOpts().CPlusPlus20 1487 ? diag::warn_arith_conv_enum_float_cxx20 1488 : diag::warn_arith_conv_enum_float) 1489 << LHS->getSourceRange() << RHS->getSourceRange() 1490 << (int)ACK << LEnum << L << R; 1491 } else if (!IsCompAssign && LEnum && REnum && 1492 !S.Context.hasSameUnqualifiedType(L, R)) { 1493 unsigned DiagID; 1494 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() || 1495 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) { 1496 // If either enumeration type is unnamed, it's less likely that the 1497 // user cares about this, but this situation is still deprecated in 1498 // C++2a. Use a different warning group. 1499 DiagID = S.getLangOpts().CPlusPlus20 1500 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20 1501 : diag::warn_arith_conv_mixed_anon_enum_types; 1502 } else if (ACK == Sema::ACK_Conditional) { 1503 // Conditional expressions are separated out because they have 1504 // historically had a different warning flag. 1505 DiagID = S.getLangOpts().CPlusPlus20 1506 ? diag::warn_conditional_mixed_enum_types_cxx20 1507 : diag::warn_conditional_mixed_enum_types; 1508 } else if (ACK == Sema::ACK_Comparison) { 1509 // Comparison expressions are separated out because they have 1510 // historically had a different warning flag. 1511 DiagID = S.getLangOpts().CPlusPlus20 1512 ? diag::warn_comparison_mixed_enum_types_cxx20 1513 : diag::warn_comparison_mixed_enum_types; 1514 } else { 1515 DiagID = S.getLangOpts().CPlusPlus20 1516 ? diag::warn_arith_conv_mixed_enum_types_cxx20 1517 : diag::warn_arith_conv_mixed_enum_types; 1518 } 1519 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange() 1520 << (int)ACK << L << R; 1521 } 1522 } 1523 1524 /// UsualArithmeticConversions - Performs various conversions that are common to 1525 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1526 /// routine returns the first non-arithmetic type found. The client is 1527 /// responsible for emitting appropriate error diagnostics. 1528 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1529 SourceLocation Loc, 1530 ArithConvKind ACK) { 1531 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK); 1532 1533 if (ACK != ACK_CompAssign) { 1534 LHS = UsualUnaryConversions(LHS.get()); 1535 if (LHS.isInvalid()) 1536 return QualType(); 1537 } 1538 1539 RHS = UsualUnaryConversions(RHS.get()); 1540 if (RHS.isInvalid()) 1541 return QualType(); 1542 1543 // For conversion purposes, we ignore any qualifiers. 1544 // For example, "const float" and "float" are equivalent. 1545 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 1546 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 1547 1548 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1549 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1550 LHSType = AtomicLHS->getValueType(); 1551 1552 // If both types are identical, no conversion is needed. 1553 if (Context.hasSameType(LHSType, RHSType)) 1554 return Context.getCommonSugaredType(LHSType, RHSType); 1555 1556 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1557 // The caller can deal with this (e.g. pointer + int). 1558 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1559 return QualType(); 1560 1561 // Apply unary and bitfield promotions to the LHS's type. 1562 QualType LHSUnpromotedType = LHSType; 1563 if (Context.isPromotableIntegerType(LHSType)) 1564 LHSType = Context.getPromotedIntegerType(LHSType); 1565 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1566 if (!LHSBitfieldPromoteTy.isNull()) 1567 LHSType = LHSBitfieldPromoteTy; 1568 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign) 1569 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1570 1571 // If both types are identical, no conversion is needed. 1572 if (Context.hasSameType(LHSType, RHSType)) 1573 return Context.getCommonSugaredType(LHSType, RHSType); 1574 1575 // At this point, we have two different arithmetic types. 1576 1577 // Diagnose attempts to convert between __ibm128, __float128 and long double 1578 // where such conversions currently can't be handled. 1579 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1580 return QualType(); 1581 1582 // Handle complex types first (C99 6.3.1.8p1). 1583 if (LHSType->isComplexType() || RHSType->isComplexType()) 1584 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType, 1585 ACK == ACK_CompAssign); 1586 1587 // Now handle "real" floating types (i.e. float, double, long double). 1588 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1589 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1590 ACK == ACK_CompAssign); 1591 1592 // Handle GCC complex int extension. 1593 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1594 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1595 ACK == ACK_CompAssign); 1596 1597 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) 1598 return handleFixedPointConversion(*this, LHSType, RHSType); 1599 1600 // Finally, we have two differing integer types. 1601 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1602 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign); 1603 } 1604 1605 //===----------------------------------------------------------------------===// 1606 // Semantic Analysis for various Expression Types 1607 //===----------------------------------------------------------------------===// 1608 1609 1610 ExprResult 1611 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1612 SourceLocation DefaultLoc, 1613 SourceLocation RParenLoc, 1614 Expr *ControllingExpr, 1615 ArrayRef<ParsedType> ArgTypes, 1616 ArrayRef<Expr *> ArgExprs) { 1617 unsigned NumAssocs = ArgTypes.size(); 1618 assert(NumAssocs == ArgExprs.size()); 1619 1620 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1621 for (unsigned i = 0; i < NumAssocs; ++i) { 1622 if (ArgTypes[i]) 1623 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1624 else 1625 Types[i] = nullptr; 1626 } 1627 1628 ExprResult ER = 1629 CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, ControllingExpr, 1630 llvm::ArrayRef(Types, NumAssocs), ArgExprs); 1631 delete [] Types; 1632 return ER; 1633 } 1634 1635 ExprResult 1636 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1637 SourceLocation DefaultLoc, 1638 SourceLocation RParenLoc, 1639 Expr *ControllingExpr, 1640 ArrayRef<TypeSourceInfo *> Types, 1641 ArrayRef<Expr *> Exprs) { 1642 unsigned NumAssocs = Types.size(); 1643 assert(NumAssocs == Exprs.size()); 1644 1645 // Decay and strip qualifiers for the controlling expression type, and handle 1646 // placeholder type replacement. See committee discussion from WG14 DR423. 1647 { 1648 EnterExpressionEvaluationContext Unevaluated( 1649 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1650 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1651 if (R.isInvalid()) 1652 return ExprError(); 1653 ControllingExpr = R.get(); 1654 } 1655 1656 bool TypeErrorFound = false, 1657 IsResultDependent = ControllingExpr->isTypeDependent(), 1658 ContainsUnexpandedParameterPack 1659 = ControllingExpr->containsUnexpandedParameterPack(); 1660 1661 // The controlling expression is an unevaluated operand, so side effects are 1662 // likely unintended. 1663 if (!inTemplateInstantiation() && !IsResultDependent && 1664 ControllingExpr->HasSideEffects(Context, false)) 1665 Diag(ControllingExpr->getExprLoc(), 1666 diag::warn_side_effects_unevaluated_context); 1667 1668 for (unsigned i = 0; i < NumAssocs; ++i) { 1669 if (Exprs[i]->containsUnexpandedParameterPack()) 1670 ContainsUnexpandedParameterPack = true; 1671 1672 if (Types[i]) { 1673 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1674 ContainsUnexpandedParameterPack = true; 1675 1676 if (Types[i]->getType()->isDependentType()) { 1677 IsResultDependent = true; 1678 } else { 1679 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1680 // complete object type other than a variably modified type." 1681 unsigned D = 0; 1682 if (Types[i]->getType()->isIncompleteType()) 1683 D = diag::err_assoc_type_incomplete; 1684 else if (!Types[i]->getType()->isObjectType()) 1685 D = diag::err_assoc_type_nonobject; 1686 else if (Types[i]->getType()->isVariablyModifiedType()) 1687 D = diag::err_assoc_type_variably_modified; 1688 else { 1689 // Because the controlling expression undergoes lvalue conversion, 1690 // array conversion, and function conversion, an association which is 1691 // of array type, function type, or is qualified can never be 1692 // reached. We will warn about this so users are less surprised by 1693 // the unreachable association. However, we don't have to handle 1694 // function types; that's not an object type, so it's handled above. 1695 // 1696 // The logic is somewhat different for C++ because C++ has different 1697 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says, 1698 // If T is a non-class type, the type of the prvalue is the cv- 1699 // unqualified version of T. Otherwise, the type of the prvalue is T. 1700 // The result of these rules is that all qualified types in an 1701 // association in C are unreachable, and in C++, only qualified non- 1702 // class types are unreachable. 1703 unsigned Reason = 0; 1704 QualType QT = Types[i]->getType(); 1705 if (QT->isArrayType()) 1706 Reason = 1; 1707 else if (QT.hasQualifiers() && 1708 (!LangOpts.CPlusPlus || !QT->isRecordType())) 1709 Reason = 2; 1710 1711 if (Reason) 1712 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1713 diag::warn_unreachable_association) 1714 << QT << (Reason - 1); 1715 } 1716 1717 if (D != 0) { 1718 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1719 << Types[i]->getTypeLoc().getSourceRange() 1720 << Types[i]->getType(); 1721 TypeErrorFound = true; 1722 } 1723 1724 // C11 6.5.1.1p2 "No two generic associations in the same generic 1725 // selection shall specify compatible types." 1726 for (unsigned j = i+1; j < NumAssocs; ++j) 1727 if (Types[j] && !Types[j]->getType()->isDependentType() && 1728 Context.typesAreCompatible(Types[i]->getType(), 1729 Types[j]->getType())) { 1730 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1731 diag::err_assoc_compatible_types) 1732 << Types[j]->getTypeLoc().getSourceRange() 1733 << Types[j]->getType() 1734 << Types[i]->getType(); 1735 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1736 diag::note_compat_assoc) 1737 << Types[i]->getTypeLoc().getSourceRange() 1738 << Types[i]->getType(); 1739 TypeErrorFound = true; 1740 } 1741 } 1742 } 1743 } 1744 if (TypeErrorFound) 1745 return ExprError(); 1746 1747 // If we determined that the generic selection is result-dependent, don't 1748 // try to compute the result expression. 1749 if (IsResultDependent) 1750 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types, 1751 Exprs, DefaultLoc, RParenLoc, 1752 ContainsUnexpandedParameterPack); 1753 1754 SmallVector<unsigned, 1> CompatIndices; 1755 unsigned DefaultIndex = -1U; 1756 // Look at the canonical type of the controlling expression in case it was a 1757 // deduced type like __auto_type. However, when issuing diagnostics, use the 1758 // type the user wrote in source rather than the canonical one. 1759 for (unsigned i = 0; i < NumAssocs; ++i) { 1760 if (!Types[i]) 1761 DefaultIndex = i; 1762 else if (Context.typesAreCompatible( 1763 ControllingExpr->getType().getCanonicalType(), 1764 Types[i]->getType())) 1765 CompatIndices.push_back(i); 1766 } 1767 1768 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1769 // type compatible with at most one of the types named in its generic 1770 // association list." 1771 if (CompatIndices.size() > 1) { 1772 // We strip parens here because the controlling expression is typically 1773 // parenthesized in macro definitions. 1774 ControllingExpr = ControllingExpr->IgnoreParens(); 1775 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1776 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1777 << (unsigned)CompatIndices.size(); 1778 for (unsigned I : CompatIndices) { 1779 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1780 diag::note_compat_assoc) 1781 << Types[I]->getTypeLoc().getSourceRange() 1782 << Types[I]->getType(); 1783 } 1784 return ExprError(); 1785 } 1786 1787 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1788 // its controlling expression shall have type compatible with exactly one of 1789 // the types named in its generic association list." 1790 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1791 // We strip parens here because the controlling expression is typically 1792 // parenthesized in macro definitions. 1793 ControllingExpr = ControllingExpr->IgnoreParens(); 1794 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1795 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1796 return ExprError(); 1797 } 1798 1799 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1800 // type name that is compatible with the type of the controlling expression, 1801 // then the result expression of the generic selection is the expression 1802 // in that generic association. Otherwise, the result expression of the 1803 // generic selection is the expression in the default generic association." 1804 unsigned ResultIndex = 1805 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1806 1807 return GenericSelectionExpr::Create( 1808 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1809 ContainsUnexpandedParameterPack, ResultIndex); 1810 } 1811 1812 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1813 /// location of the token and the offset of the ud-suffix within it. 1814 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1815 unsigned Offset) { 1816 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1817 S.getLangOpts()); 1818 } 1819 1820 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1821 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1822 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1823 IdentifierInfo *UDSuffix, 1824 SourceLocation UDSuffixLoc, 1825 ArrayRef<Expr*> Args, 1826 SourceLocation LitEndLoc) { 1827 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1828 1829 QualType ArgTy[2]; 1830 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1831 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1832 if (ArgTy[ArgIdx]->isArrayType()) 1833 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1834 } 1835 1836 DeclarationName OpName = 1837 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1838 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1839 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1840 1841 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1842 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()), 1843 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1844 /*AllowStringTemplatePack*/ false, 1845 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1846 return ExprError(); 1847 1848 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1849 } 1850 1851 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1852 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1853 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1854 /// multiple tokens. However, the common case is that StringToks points to one 1855 /// string. 1856 /// 1857 ExprResult 1858 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1859 assert(!StringToks.empty() && "Must have at least one string!"); 1860 1861 StringLiteralParser Literal(StringToks, PP); 1862 if (Literal.hadError) 1863 return ExprError(); 1864 1865 SmallVector<SourceLocation, 4> StringTokLocs; 1866 for (const Token &Tok : StringToks) 1867 StringTokLocs.push_back(Tok.getLocation()); 1868 1869 QualType CharTy = Context.CharTy; 1870 StringLiteral::StringKind Kind = StringLiteral::Ordinary; 1871 if (Literal.isWide()) { 1872 CharTy = Context.getWideCharType(); 1873 Kind = StringLiteral::Wide; 1874 } else if (Literal.isUTF8()) { 1875 if (getLangOpts().Char8) 1876 CharTy = Context.Char8Ty; 1877 Kind = StringLiteral::UTF8; 1878 } else if (Literal.isUTF16()) { 1879 CharTy = Context.Char16Ty; 1880 Kind = StringLiteral::UTF16; 1881 } else if (Literal.isUTF32()) { 1882 CharTy = Context.Char32Ty; 1883 Kind = StringLiteral::UTF32; 1884 } else if (Literal.isPascal()) { 1885 CharTy = Context.UnsignedCharTy; 1886 } 1887 1888 // Warn on initializing an array of char from a u8 string literal; this 1889 // becomes ill-formed in C++2a. 1890 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 && 1891 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1892 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string); 1893 1894 // Create removals for all 'u8' prefixes in the string literal(s). This 1895 // ensures C++2a compatibility (but may change the program behavior when 1896 // built by non-Clang compilers for which the execution character set is 1897 // not always UTF-8). 1898 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8); 1899 SourceLocation RemovalDiagLoc; 1900 for (const Token &Tok : StringToks) { 1901 if (Tok.getKind() == tok::utf8_string_literal) { 1902 if (RemovalDiagLoc.isInvalid()) 1903 RemovalDiagLoc = Tok.getLocation(); 1904 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1905 Tok.getLocation(), 1906 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1907 getSourceManager(), getLangOpts()))); 1908 } 1909 } 1910 Diag(RemovalDiagLoc, RemovalDiag); 1911 } 1912 1913 QualType StrTy = 1914 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars()); 1915 1916 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1917 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1918 Kind, Literal.Pascal, StrTy, 1919 &StringTokLocs[0], 1920 StringTokLocs.size()); 1921 if (Literal.getUDSuffix().empty()) 1922 return Lit; 1923 1924 // We're building a user-defined literal. 1925 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1926 SourceLocation UDSuffixLoc = 1927 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1928 Literal.getUDSuffixOffset()); 1929 1930 // Make sure we're allowed user-defined literals here. 1931 if (!UDLScope) 1932 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1933 1934 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1935 // operator "" X (str, len) 1936 QualType SizeType = Context.getSizeType(); 1937 1938 DeclarationName OpName = 1939 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1940 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1941 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1942 1943 QualType ArgTy[] = { 1944 Context.getArrayDecayedType(StrTy), SizeType 1945 }; 1946 1947 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1948 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1949 /*AllowRaw*/ false, /*AllowTemplate*/ true, 1950 /*AllowStringTemplatePack*/ true, 1951 /*DiagnoseMissing*/ true, Lit)) { 1952 1953 case LOLR_Cooked: { 1954 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1955 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1956 StringTokLocs[0]); 1957 Expr *Args[] = { Lit, LenArg }; 1958 1959 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1960 } 1961 1962 case LOLR_Template: { 1963 TemplateArgumentListInfo ExplicitArgs; 1964 TemplateArgument Arg(Lit); 1965 TemplateArgumentLocInfo ArgInfo(Lit); 1966 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1967 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, 1968 StringTokLocs.back(), &ExplicitArgs); 1969 } 1970 1971 case LOLR_StringTemplatePack: { 1972 TemplateArgumentListInfo ExplicitArgs; 1973 1974 unsigned CharBits = Context.getIntWidth(CharTy); 1975 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1976 llvm::APSInt Value(CharBits, CharIsUnsigned); 1977 1978 TemplateArgument TypeArg(CharTy); 1979 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1980 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1981 1982 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1983 Value = Lit->getCodeUnit(I); 1984 TemplateArgument Arg(Context, Value, CharTy); 1985 TemplateArgumentLocInfo ArgInfo; 1986 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1987 } 1988 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, 1989 StringTokLocs.back(), &ExplicitArgs); 1990 } 1991 case LOLR_Raw: 1992 case LOLR_ErrorNoDiagnostic: 1993 llvm_unreachable("unexpected literal operator lookup result"); 1994 case LOLR_Error: 1995 return ExprError(); 1996 } 1997 llvm_unreachable("unexpected literal operator lookup result"); 1998 } 1999 2000 DeclRefExpr * 2001 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2002 SourceLocation Loc, 2003 const CXXScopeSpec *SS) { 2004 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 2005 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 2006 } 2007 2008 DeclRefExpr * 2009 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2010 const DeclarationNameInfo &NameInfo, 2011 const CXXScopeSpec *SS, NamedDecl *FoundD, 2012 SourceLocation TemplateKWLoc, 2013 const TemplateArgumentListInfo *TemplateArgs) { 2014 NestedNameSpecifierLoc NNS = 2015 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(); 2016 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc, 2017 TemplateArgs); 2018 } 2019 2020 // CUDA/HIP: Check whether a captured reference variable is referencing a 2021 // host variable in a device or host device lambda. 2022 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, 2023 VarDecl *VD) { 2024 if (!S.getLangOpts().CUDA || !VD->hasInit()) 2025 return false; 2026 assert(VD->getType()->isReferenceType()); 2027 2028 // Check whether the reference variable is referencing a host variable. 2029 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit()); 2030 if (!DRE) 2031 return false; 2032 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl()); 2033 if (!Referee || !Referee->hasGlobalStorage() || 2034 Referee->hasAttr<CUDADeviceAttr>()) 2035 return false; 2036 2037 // Check whether the current function is a device or host device lambda. 2038 // Check whether the reference variable is a capture by getDeclContext() 2039 // since refersToEnclosingVariableOrCapture() is not ready at this point. 2040 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext); 2041 if (MD && MD->getParent()->isLambda() && 2042 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() && 2043 VD->getDeclContext() != MD) 2044 return true; 2045 2046 return false; 2047 } 2048 2049 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) { 2050 // A declaration named in an unevaluated operand never constitutes an odr-use. 2051 if (isUnevaluatedContext()) 2052 return NOUR_Unevaluated; 2053 2054 // C++2a [basic.def.odr]p4: 2055 // A variable x whose name appears as a potentially-evaluated expression e 2056 // is odr-used by e unless [...] x is a reference that is usable in 2057 // constant expressions. 2058 // CUDA/HIP: 2059 // If a reference variable referencing a host variable is captured in a 2060 // device or host device lambda, the value of the referee must be copied 2061 // to the capture and the reference variable must be treated as odr-use 2062 // since the value of the referee is not known at compile time and must 2063 // be loaded from the captured. 2064 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2065 if (VD->getType()->isReferenceType() && 2066 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) && 2067 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) && 2068 VD->isUsableInConstantExpressions(Context)) 2069 return NOUR_Constant; 2070 } 2071 2072 // All remaining non-variable cases constitute an odr-use. For variables, we 2073 // need to wait and see how the expression is used. 2074 return NOUR_None; 2075 } 2076 2077 /// BuildDeclRefExpr - Build an expression that references a 2078 /// declaration that does not require a closure capture. 2079 DeclRefExpr * 2080 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 2081 const DeclarationNameInfo &NameInfo, 2082 NestedNameSpecifierLoc NNS, NamedDecl *FoundD, 2083 SourceLocation TemplateKWLoc, 2084 const TemplateArgumentListInfo *TemplateArgs) { 2085 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) && 2086 NeedToCaptureVariable(D, NameInfo.getLoc()); 2087 2088 DeclRefExpr *E = DeclRefExpr::Create( 2089 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty, 2090 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D)); 2091 MarkDeclRefReferenced(E); 2092 2093 // C++ [except.spec]p17: 2094 // An exception-specification is considered to be needed when: 2095 // - in an expression, the function is the unique lookup result or 2096 // the selected member of a set of overloaded functions. 2097 // 2098 // We delay doing this until after we've built the function reference and 2099 // marked it as used so that: 2100 // a) if the function is defaulted, we get errors from defining it before / 2101 // instead of errors from computing its exception specification, and 2102 // b) if the function is a defaulted comparison, we can use the body we 2103 // build when defining it as input to the exception specification 2104 // computation rather than computing a new body. 2105 if (auto *FPT = Ty->getAs<FunctionProtoType>()) { 2106 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) { 2107 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT)) 2108 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers())); 2109 } 2110 } 2111 2112 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 2113 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 2114 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 2115 getCurFunction()->recordUseOfWeak(E); 2116 2117 FieldDecl *FD = dyn_cast<FieldDecl>(D); 2118 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 2119 FD = IFD->getAnonField(); 2120 if (FD) { 2121 UnusedPrivateFields.remove(FD); 2122 // Just in case we're building an illegal pointer-to-member. 2123 if (FD->isBitField()) 2124 E->setObjectKind(OK_BitField); 2125 } 2126 2127 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 2128 // designates a bit-field. 2129 if (auto *BD = dyn_cast<BindingDecl>(D)) 2130 if (auto *BE = BD->getBinding()) 2131 E->setObjectKind(BE->getObjectKind()); 2132 2133 return E; 2134 } 2135 2136 /// Decomposes the given name into a DeclarationNameInfo, its location, and 2137 /// possibly a list of template arguments. 2138 /// 2139 /// If this produces template arguments, it is permitted to call 2140 /// DecomposeTemplateName. 2141 /// 2142 /// This actually loses a lot of source location information for 2143 /// non-standard name kinds; we should consider preserving that in 2144 /// some way. 2145 void 2146 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 2147 TemplateArgumentListInfo &Buffer, 2148 DeclarationNameInfo &NameInfo, 2149 const TemplateArgumentListInfo *&TemplateArgs) { 2150 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 2151 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 2152 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 2153 2154 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 2155 Id.TemplateId->NumArgs); 2156 translateTemplateArguments(TemplateArgsPtr, Buffer); 2157 2158 TemplateName TName = Id.TemplateId->Template.get(); 2159 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 2160 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 2161 TemplateArgs = &Buffer; 2162 } else { 2163 NameInfo = GetNameFromUnqualifiedId(Id); 2164 TemplateArgs = nullptr; 2165 } 2166 } 2167 2168 static void emitEmptyLookupTypoDiagnostic( 2169 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 2170 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 2171 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 2172 DeclContext *Ctx = 2173 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 2174 if (!TC) { 2175 // Emit a special diagnostic for failed member lookups. 2176 // FIXME: computing the declaration context might fail here (?) 2177 if (Ctx) 2178 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 2179 << SS.getRange(); 2180 else 2181 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 2182 return; 2183 } 2184 2185 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 2186 bool DroppedSpecifier = 2187 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 2188 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 2189 ? diag::note_implicit_param_decl 2190 : diag::note_previous_decl; 2191 if (!Ctx) 2192 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 2193 SemaRef.PDiag(NoteID)); 2194 else 2195 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 2196 << Typo << Ctx << DroppedSpecifier 2197 << SS.getRange(), 2198 SemaRef.PDiag(NoteID)); 2199 } 2200 2201 /// Diagnose a lookup that found results in an enclosing class during error 2202 /// recovery. This usually indicates that the results were found in a dependent 2203 /// base class that could not be searched as part of a template definition. 2204 /// Always issues a diagnostic (though this may be only a warning in MS 2205 /// compatibility mode). 2206 /// 2207 /// Return \c true if the error is unrecoverable, or \c false if the caller 2208 /// should attempt to recover using these lookup results. 2209 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) { 2210 // During a default argument instantiation the CurContext points 2211 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 2212 // function parameter list, hence add an explicit check. 2213 bool isDefaultArgument = 2214 !CodeSynthesisContexts.empty() && 2215 CodeSynthesisContexts.back().Kind == 2216 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 2217 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 2218 bool isInstance = CurMethod && CurMethod->isInstance() && 2219 R.getNamingClass() == CurMethod->getParent() && 2220 !isDefaultArgument; 2221 2222 // There are two ways we can find a class-scope declaration during template 2223 // instantiation that we did not find in the template definition: if it is a 2224 // member of a dependent base class, or if it is declared after the point of 2225 // use in the same class. Distinguish these by comparing the class in which 2226 // the member was found to the naming class of the lookup. 2227 unsigned DiagID = diag::err_found_in_dependent_base; 2228 unsigned NoteID = diag::note_member_declared_at; 2229 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) { 2230 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class 2231 : diag::err_found_later_in_class; 2232 } else if (getLangOpts().MSVCCompat) { 2233 DiagID = diag::ext_found_in_dependent_base; 2234 NoteID = diag::note_dependent_member_use; 2235 } 2236 2237 if (isInstance) { 2238 // Give a code modification hint to insert 'this->'. 2239 Diag(R.getNameLoc(), DiagID) 2240 << R.getLookupName() 2241 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 2242 CheckCXXThisCapture(R.getNameLoc()); 2243 } else { 2244 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming 2245 // they're not shadowed). 2246 Diag(R.getNameLoc(), DiagID) << R.getLookupName(); 2247 } 2248 2249 for (NamedDecl *D : R) 2250 Diag(D->getLocation(), NoteID); 2251 2252 // Return true if we are inside a default argument instantiation 2253 // and the found name refers to an instance member function, otherwise 2254 // the caller will try to create an implicit member call and this is wrong 2255 // for default arguments. 2256 // 2257 // FIXME: Is this special case necessary? We could allow the caller to 2258 // diagnose this. 2259 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 2260 Diag(R.getNameLoc(), diag::err_member_call_without_object); 2261 return true; 2262 } 2263 2264 // Tell the callee to try to recover. 2265 return false; 2266 } 2267 2268 /// Diagnose an empty lookup. 2269 /// 2270 /// \return false if new lookup candidates were found 2271 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2272 CorrectionCandidateCallback &CCC, 2273 TemplateArgumentListInfo *ExplicitTemplateArgs, 2274 ArrayRef<Expr *> Args, TypoExpr **Out) { 2275 DeclarationName Name = R.getLookupName(); 2276 2277 unsigned diagnostic = diag::err_undeclared_var_use; 2278 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 2279 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 2280 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 2281 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2282 diagnostic = diag::err_undeclared_use; 2283 diagnostic_suggest = diag::err_undeclared_use_suggest; 2284 } 2285 2286 // If the original lookup was an unqualified lookup, fake an 2287 // unqualified lookup. This is useful when (for example) the 2288 // original lookup would not have found something because it was a 2289 // dependent name. 2290 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 2291 while (DC) { 2292 if (isa<CXXRecordDecl>(DC)) { 2293 LookupQualifiedName(R, DC); 2294 2295 if (!R.empty()) { 2296 // Don't give errors about ambiguities in this lookup. 2297 R.suppressDiagnostics(); 2298 2299 // If there's a best viable function among the results, only mention 2300 // that one in the notes. 2301 OverloadCandidateSet Candidates(R.getNameLoc(), 2302 OverloadCandidateSet::CSK_Normal); 2303 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates); 2304 OverloadCandidateSet::iterator Best; 2305 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) == 2306 OR_Success) { 2307 R.clear(); 2308 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess()); 2309 R.resolveKind(); 2310 } 2311 2312 return DiagnoseDependentMemberLookup(R); 2313 } 2314 2315 R.clear(); 2316 } 2317 2318 DC = DC->getLookupParent(); 2319 } 2320 2321 // We didn't find anything, so try to correct for a typo. 2322 TypoCorrection Corrected; 2323 if (S && Out) { 2324 SourceLocation TypoLoc = R.getNameLoc(); 2325 assert(!ExplicitTemplateArgs && 2326 "Diagnosing an empty lookup with explicit template args!"); 2327 *Out = CorrectTypoDelayed( 2328 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 2329 [=](const TypoCorrection &TC) { 2330 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 2331 diagnostic, diagnostic_suggest); 2332 }, 2333 nullptr, CTK_ErrorRecovery); 2334 if (*Out) 2335 return true; 2336 } else if (S && 2337 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 2338 S, &SS, CCC, CTK_ErrorRecovery))) { 2339 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 2340 bool DroppedSpecifier = 2341 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 2342 R.setLookupName(Corrected.getCorrection()); 2343 2344 bool AcceptableWithRecovery = false; 2345 bool AcceptableWithoutRecovery = false; 2346 NamedDecl *ND = Corrected.getFoundDecl(); 2347 if (ND) { 2348 if (Corrected.isOverloaded()) { 2349 OverloadCandidateSet OCS(R.getNameLoc(), 2350 OverloadCandidateSet::CSK_Normal); 2351 OverloadCandidateSet::iterator Best; 2352 for (NamedDecl *CD : Corrected) { 2353 if (FunctionTemplateDecl *FTD = 2354 dyn_cast<FunctionTemplateDecl>(CD)) 2355 AddTemplateOverloadCandidate( 2356 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 2357 Args, OCS); 2358 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 2359 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 2360 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 2361 Args, OCS); 2362 } 2363 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 2364 case OR_Success: 2365 ND = Best->FoundDecl; 2366 Corrected.setCorrectionDecl(ND); 2367 break; 2368 default: 2369 // FIXME: Arbitrarily pick the first declaration for the note. 2370 Corrected.setCorrectionDecl(ND); 2371 break; 2372 } 2373 } 2374 R.addDecl(ND); 2375 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 2376 CXXRecordDecl *Record = nullptr; 2377 if (Corrected.getCorrectionSpecifier()) { 2378 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 2379 Record = Ty->getAsCXXRecordDecl(); 2380 } 2381 if (!Record) 2382 Record = cast<CXXRecordDecl>( 2383 ND->getDeclContext()->getRedeclContext()); 2384 R.setNamingClass(Record); 2385 } 2386 2387 auto *UnderlyingND = ND->getUnderlyingDecl(); 2388 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 2389 isa<FunctionTemplateDecl>(UnderlyingND); 2390 // FIXME: If we ended up with a typo for a type name or 2391 // Objective-C class name, we're in trouble because the parser 2392 // is in the wrong place to recover. Suggest the typo 2393 // correction, but don't make it a fix-it since we're not going 2394 // to recover well anyway. 2395 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) || 2396 getAsTypeTemplateDecl(UnderlyingND) || 2397 isa<ObjCInterfaceDecl>(UnderlyingND); 2398 } else { 2399 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 2400 // because we aren't able to recover. 2401 AcceptableWithoutRecovery = true; 2402 } 2403 2404 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 2405 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 2406 ? diag::note_implicit_param_decl 2407 : diag::note_previous_decl; 2408 if (SS.isEmpty()) 2409 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 2410 PDiag(NoteID), AcceptableWithRecovery); 2411 else 2412 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2413 << Name << computeDeclContext(SS, false) 2414 << DroppedSpecifier << SS.getRange(), 2415 PDiag(NoteID), AcceptableWithRecovery); 2416 2417 // Tell the callee whether to try to recover. 2418 return !AcceptableWithRecovery; 2419 } 2420 } 2421 R.clear(); 2422 2423 // Emit a special diagnostic for failed member lookups. 2424 // FIXME: computing the declaration context might fail here (?) 2425 if (!SS.isEmpty()) { 2426 Diag(R.getNameLoc(), diag::err_no_member) 2427 << Name << computeDeclContext(SS, false) 2428 << SS.getRange(); 2429 return true; 2430 } 2431 2432 // Give up, we can't recover. 2433 Diag(R.getNameLoc(), diagnostic) << Name; 2434 return true; 2435 } 2436 2437 /// In Microsoft mode, if we are inside a template class whose parent class has 2438 /// dependent base classes, and we can't resolve an unqualified identifier, then 2439 /// assume the identifier is a member of a dependent base class. We can only 2440 /// recover successfully in static methods, instance methods, and other contexts 2441 /// where 'this' is available. This doesn't precisely match MSVC's 2442 /// instantiation model, but it's close enough. 2443 static Expr * 2444 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2445 DeclarationNameInfo &NameInfo, 2446 SourceLocation TemplateKWLoc, 2447 const TemplateArgumentListInfo *TemplateArgs) { 2448 // Only try to recover from lookup into dependent bases in static methods or 2449 // contexts where 'this' is available. 2450 QualType ThisType = S.getCurrentThisType(); 2451 const CXXRecordDecl *RD = nullptr; 2452 if (!ThisType.isNull()) 2453 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2454 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2455 RD = MD->getParent(); 2456 if (!RD || !RD->hasAnyDependentBases()) 2457 return nullptr; 2458 2459 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2460 // is available, suggest inserting 'this->' as a fixit. 2461 SourceLocation Loc = NameInfo.getLoc(); 2462 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2463 DB << NameInfo.getName() << RD; 2464 2465 if (!ThisType.isNull()) { 2466 DB << FixItHint::CreateInsertion(Loc, "this->"); 2467 return CXXDependentScopeMemberExpr::Create( 2468 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2469 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2470 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs); 2471 } 2472 2473 // Synthesize a fake NNS that points to the derived class. This will 2474 // perform name lookup during template instantiation. 2475 CXXScopeSpec SS; 2476 auto *NNS = 2477 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2478 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2479 return DependentScopeDeclRefExpr::Create( 2480 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2481 TemplateArgs); 2482 } 2483 2484 ExprResult 2485 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2486 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2487 bool HasTrailingLParen, bool IsAddressOfOperand, 2488 CorrectionCandidateCallback *CCC, 2489 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2490 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2491 "cannot be direct & operand and have a trailing lparen"); 2492 if (SS.isInvalid()) 2493 return ExprError(); 2494 2495 TemplateArgumentListInfo TemplateArgsBuffer; 2496 2497 // Decompose the UnqualifiedId into the following data. 2498 DeclarationNameInfo NameInfo; 2499 const TemplateArgumentListInfo *TemplateArgs; 2500 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2501 2502 DeclarationName Name = NameInfo.getName(); 2503 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2504 SourceLocation NameLoc = NameInfo.getLoc(); 2505 2506 if (II && II->isEditorPlaceholder()) { 2507 // FIXME: When typed placeholders are supported we can create a typed 2508 // placeholder expression node. 2509 return ExprError(); 2510 } 2511 2512 // C++ [temp.dep.expr]p3: 2513 // An id-expression is type-dependent if it contains: 2514 // -- an identifier that was declared with a dependent type, 2515 // (note: handled after lookup) 2516 // -- a template-id that is dependent, 2517 // (note: handled in BuildTemplateIdExpr) 2518 // -- a conversion-function-id that specifies a dependent type, 2519 // -- a nested-name-specifier that contains a class-name that 2520 // names a dependent type. 2521 // Determine whether this is a member of an unknown specialization; 2522 // we need to handle these differently. 2523 bool DependentID = false; 2524 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2525 Name.getCXXNameType()->isDependentType()) { 2526 DependentID = true; 2527 } else if (SS.isSet()) { 2528 if (DeclContext *DC = computeDeclContext(SS, false)) { 2529 if (RequireCompleteDeclContext(SS, DC)) 2530 return ExprError(); 2531 } else { 2532 DependentID = true; 2533 } 2534 } 2535 2536 if (DependentID) 2537 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2538 IsAddressOfOperand, TemplateArgs); 2539 2540 // Perform the required lookup. 2541 LookupResult R(*this, NameInfo, 2542 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2543 ? LookupObjCImplicitSelfParam 2544 : LookupOrdinaryName); 2545 if (TemplateKWLoc.isValid() || TemplateArgs) { 2546 // Lookup the template name again to correctly establish the context in 2547 // which it was found. This is really unfortunate as we already did the 2548 // lookup to determine that it was a template name in the first place. If 2549 // this becomes a performance hit, we can work harder to preserve those 2550 // results until we get here but it's likely not worth it. 2551 bool MemberOfUnknownSpecialization; 2552 AssumedTemplateKind AssumedTemplate; 2553 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2554 MemberOfUnknownSpecialization, TemplateKWLoc, 2555 &AssumedTemplate)) 2556 return ExprError(); 2557 2558 if (MemberOfUnknownSpecialization || 2559 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2560 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2561 IsAddressOfOperand, TemplateArgs); 2562 } else { 2563 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2564 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2565 2566 // If the result might be in a dependent base class, this is a dependent 2567 // id-expression. 2568 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2569 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2570 IsAddressOfOperand, TemplateArgs); 2571 2572 // If this reference is in an Objective-C method, then we need to do 2573 // some special Objective-C lookup, too. 2574 if (IvarLookupFollowUp) { 2575 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2576 if (E.isInvalid()) 2577 return ExprError(); 2578 2579 if (Expr *Ex = E.getAs<Expr>()) 2580 return Ex; 2581 } 2582 } 2583 2584 if (R.isAmbiguous()) 2585 return ExprError(); 2586 2587 // This could be an implicitly declared function reference if the language 2588 // mode allows it as a feature. 2589 if (R.empty() && HasTrailingLParen && II && 2590 getLangOpts().implicitFunctionsAllowed()) { 2591 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2592 if (D) R.addDecl(D); 2593 } 2594 2595 // Determine whether this name might be a candidate for 2596 // argument-dependent lookup. 2597 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2598 2599 if (R.empty() && !ADL) { 2600 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2601 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2602 TemplateKWLoc, TemplateArgs)) 2603 return E; 2604 } 2605 2606 // Don't diagnose an empty lookup for inline assembly. 2607 if (IsInlineAsmIdentifier) 2608 return ExprError(); 2609 2610 // If this name wasn't predeclared and if this is not a function 2611 // call, diagnose the problem. 2612 TypoExpr *TE = nullptr; 2613 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep() 2614 : nullptr); 2615 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2616 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2617 "Typo correction callback misconfigured"); 2618 if (CCC) { 2619 // Make sure the callback knows what the typo being diagnosed is. 2620 CCC->setTypoName(II); 2621 if (SS.isValid()) 2622 CCC->setTypoNNS(SS.getScopeRep()); 2623 } 2624 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2625 // a template name, but we happen to have always already looked up the name 2626 // before we get here if it must be a template name. 2627 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr, 2628 std::nullopt, &TE)) { 2629 if (TE && KeywordReplacement) { 2630 auto &State = getTypoExprState(TE); 2631 auto BestTC = State.Consumer->getNextCorrection(); 2632 if (BestTC.isKeyword()) { 2633 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2634 if (State.DiagHandler) 2635 State.DiagHandler(BestTC); 2636 KeywordReplacement->startToken(); 2637 KeywordReplacement->setKind(II->getTokenID()); 2638 KeywordReplacement->setIdentifierInfo(II); 2639 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2640 // Clean up the state associated with the TypoExpr, since it has 2641 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2642 clearDelayedTypo(TE); 2643 // Signal that a correction to a keyword was performed by returning a 2644 // valid-but-null ExprResult. 2645 return (Expr*)nullptr; 2646 } 2647 State.Consumer->resetCorrectionStream(); 2648 } 2649 return TE ? TE : ExprError(); 2650 } 2651 2652 assert(!R.empty() && 2653 "DiagnoseEmptyLookup returned false but added no results"); 2654 2655 // If we found an Objective-C instance variable, let 2656 // LookupInObjCMethod build the appropriate expression to 2657 // reference the ivar. 2658 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2659 R.clear(); 2660 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2661 // In a hopelessly buggy code, Objective-C instance variable 2662 // lookup fails and no expression will be built to reference it. 2663 if (!E.isInvalid() && !E.get()) 2664 return ExprError(); 2665 return E; 2666 } 2667 } 2668 2669 // This is guaranteed from this point on. 2670 assert(!R.empty() || ADL); 2671 2672 // Check whether this might be a C++ implicit instance member access. 2673 // C++ [class.mfct.non-static]p3: 2674 // When an id-expression that is not part of a class member access 2675 // syntax and not used to form a pointer to member is used in the 2676 // body of a non-static member function of class X, if name lookup 2677 // resolves the name in the id-expression to a non-static non-type 2678 // member of some class C, the id-expression is transformed into a 2679 // class member access expression using (*this) as the 2680 // postfix-expression to the left of the . operator. 2681 // 2682 // But we don't actually need to do this for '&' operands if R 2683 // resolved to a function or overloaded function set, because the 2684 // expression is ill-formed if it actually works out to be a 2685 // non-static member function: 2686 // 2687 // C++ [expr.ref]p4: 2688 // Otherwise, if E1.E2 refers to a non-static member function. . . 2689 // [t]he expression can be used only as the left-hand operand of a 2690 // member function call. 2691 // 2692 // There are other safeguards against such uses, but it's important 2693 // to get this right here so that we don't end up making a 2694 // spuriously dependent expression if we're inside a dependent 2695 // instance method. 2696 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2697 bool MightBeImplicitMember; 2698 if (!IsAddressOfOperand) 2699 MightBeImplicitMember = true; 2700 else if (!SS.isEmpty()) 2701 MightBeImplicitMember = false; 2702 else if (R.isOverloadedResult()) 2703 MightBeImplicitMember = false; 2704 else if (R.isUnresolvableResult()) 2705 MightBeImplicitMember = true; 2706 else 2707 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2708 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2709 isa<MSPropertyDecl>(R.getFoundDecl()); 2710 2711 if (MightBeImplicitMember) 2712 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2713 R, TemplateArgs, S); 2714 } 2715 2716 if (TemplateArgs || TemplateKWLoc.isValid()) { 2717 2718 // In C++1y, if this is a variable template id, then check it 2719 // in BuildTemplateIdExpr(). 2720 // The single lookup result must be a variable template declaration. 2721 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2722 Id.TemplateId->Kind == TNK_Var_template) { 2723 assert(R.getAsSingle<VarTemplateDecl>() && 2724 "There should only be one declaration found."); 2725 } 2726 2727 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2728 } 2729 2730 return BuildDeclarationNameExpr(SS, R, ADL); 2731 } 2732 2733 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2734 /// declaration name, generally during template instantiation. 2735 /// There's a large number of things which don't need to be done along 2736 /// this path. 2737 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2738 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2739 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2740 if (NameInfo.getName().isDependentName()) 2741 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2742 NameInfo, /*TemplateArgs=*/nullptr); 2743 2744 DeclContext *DC = computeDeclContext(SS, false); 2745 if (!DC) 2746 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2747 NameInfo, /*TemplateArgs=*/nullptr); 2748 2749 if (RequireCompleteDeclContext(SS, DC)) 2750 return ExprError(); 2751 2752 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2753 LookupQualifiedName(R, DC); 2754 2755 if (R.isAmbiguous()) 2756 return ExprError(); 2757 2758 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2759 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2760 NameInfo, /*TemplateArgs=*/nullptr); 2761 2762 if (R.empty()) { 2763 // Don't diagnose problems with invalid record decl, the secondary no_member 2764 // diagnostic during template instantiation is likely bogus, e.g. if a class 2765 // is invalid because it's derived from an invalid base class, then missing 2766 // members were likely supposed to be inherited. 2767 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC)) 2768 if (CD->isInvalidDecl()) 2769 return ExprError(); 2770 Diag(NameInfo.getLoc(), diag::err_no_member) 2771 << NameInfo.getName() << DC << SS.getRange(); 2772 return ExprError(); 2773 } 2774 2775 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2776 // Diagnose a missing typename if this resolved unambiguously to a type in 2777 // a dependent context. If we can recover with a type, downgrade this to 2778 // a warning in Microsoft compatibility mode. 2779 unsigned DiagID = diag::err_typename_missing; 2780 if (RecoveryTSI && getLangOpts().MSVCCompat) 2781 DiagID = diag::ext_typename_missing; 2782 SourceLocation Loc = SS.getBeginLoc(); 2783 auto D = Diag(Loc, DiagID); 2784 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2785 << SourceRange(Loc, NameInfo.getEndLoc()); 2786 2787 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2788 // context. 2789 if (!RecoveryTSI) 2790 return ExprError(); 2791 2792 // Only issue the fixit if we're prepared to recover. 2793 D << FixItHint::CreateInsertion(Loc, "typename "); 2794 2795 // Recover by pretending this was an elaborated type. 2796 QualType Ty = Context.getTypeDeclType(TD); 2797 TypeLocBuilder TLB; 2798 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2799 2800 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2801 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2802 QTL.setElaboratedKeywordLoc(SourceLocation()); 2803 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2804 2805 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2806 2807 return ExprEmpty(); 2808 } 2809 2810 // Defend against this resolving to an implicit member access. We usually 2811 // won't get here if this might be a legitimate a class member (we end up in 2812 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2813 // a pointer-to-member or in an unevaluated context in C++11. 2814 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2815 return BuildPossibleImplicitMemberExpr(SS, 2816 /*TemplateKWLoc=*/SourceLocation(), 2817 R, /*TemplateArgs=*/nullptr, S); 2818 2819 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2820 } 2821 2822 /// The parser has read a name in, and Sema has detected that we're currently 2823 /// inside an ObjC method. Perform some additional checks and determine if we 2824 /// should form a reference to an ivar. 2825 /// 2826 /// Ideally, most of this would be done by lookup, but there's 2827 /// actually quite a lot of extra work involved. 2828 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 2829 IdentifierInfo *II) { 2830 SourceLocation Loc = Lookup.getNameLoc(); 2831 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2832 2833 // Check for error condition which is already reported. 2834 if (!CurMethod) 2835 return DeclResult(true); 2836 2837 // There are two cases to handle here. 1) scoped lookup could have failed, 2838 // in which case we should look for an ivar. 2) scoped lookup could have 2839 // found a decl, but that decl is outside the current instance method (i.e. 2840 // a global variable). In these two cases, we do a lookup for an ivar with 2841 // this name, if the lookup sucedes, we replace it our current decl. 2842 2843 // If we're in a class method, we don't normally want to look for 2844 // ivars. But if we don't find anything else, and there's an 2845 // ivar, that's an error. 2846 bool IsClassMethod = CurMethod->isClassMethod(); 2847 2848 bool LookForIvars; 2849 if (Lookup.empty()) 2850 LookForIvars = true; 2851 else if (IsClassMethod) 2852 LookForIvars = false; 2853 else 2854 LookForIvars = (Lookup.isSingleResult() && 2855 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2856 ObjCInterfaceDecl *IFace = nullptr; 2857 if (LookForIvars) { 2858 IFace = CurMethod->getClassInterface(); 2859 ObjCInterfaceDecl *ClassDeclared; 2860 ObjCIvarDecl *IV = nullptr; 2861 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2862 // Diagnose using an ivar in a class method. 2863 if (IsClassMethod) { 2864 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2865 return DeclResult(true); 2866 } 2867 2868 // Diagnose the use of an ivar outside of the declaring class. 2869 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2870 !declaresSameEntity(ClassDeclared, IFace) && 2871 !getLangOpts().DebuggerSupport) 2872 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2873 2874 // Success. 2875 return IV; 2876 } 2877 } else if (CurMethod->isInstanceMethod()) { 2878 // We should warn if a local variable hides an ivar. 2879 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2880 ObjCInterfaceDecl *ClassDeclared; 2881 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2882 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2883 declaresSameEntity(IFace, ClassDeclared)) 2884 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2885 } 2886 } 2887 } else if (Lookup.isSingleResult() && 2888 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2889 // If accessing a stand-alone ivar in a class method, this is an error. 2890 if (const ObjCIvarDecl *IV = 2891 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) { 2892 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName(); 2893 return DeclResult(true); 2894 } 2895 } 2896 2897 // Didn't encounter an error, didn't find an ivar. 2898 return DeclResult(false); 2899 } 2900 2901 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc, 2902 ObjCIvarDecl *IV) { 2903 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2904 assert(CurMethod && CurMethod->isInstanceMethod() && 2905 "should not reference ivar from this context"); 2906 2907 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface(); 2908 assert(IFace && "should not reference ivar from this context"); 2909 2910 // If we're referencing an invalid decl, just return this as a silent 2911 // error node. The error diagnostic was already emitted on the decl. 2912 if (IV->isInvalidDecl()) 2913 return ExprError(); 2914 2915 // Check if referencing a field with __attribute__((deprecated)). 2916 if (DiagnoseUseOfDecl(IV, Loc)) 2917 return ExprError(); 2918 2919 // FIXME: This should use a new expr for a direct reference, don't 2920 // turn this into Self->ivar, just return a BareIVarExpr or something. 2921 IdentifierInfo &II = Context.Idents.get("self"); 2922 UnqualifiedId SelfName; 2923 SelfName.setImplicitSelfParam(&II); 2924 CXXScopeSpec SelfScopeSpec; 2925 SourceLocation TemplateKWLoc; 2926 ExprResult SelfExpr = 2927 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName, 2928 /*HasTrailingLParen=*/false, 2929 /*IsAddressOfOperand=*/false); 2930 if (SelfExpr.isInvalid()) 2931 return ExprError(); 2932 2933 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2934 if (SelfExpr.isInvalid()) 2935 return ExprError(); 2936 2937 MarkAnyDeclReferenced(Loc, IV, true); 2938 2939 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2940 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2941 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2942 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2943 2944 ObjCIvarRefExpr *Result = new (Context) 2945 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2946 IV->getLocation(), SelfExpr.get(), true, true); 2947 2948 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2949 if (!isUnevaluatedContext() && 2950 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2951 getCurFunction()->recordUseOfWeak(Result); 2952 } 2953 if (getLangOpts().ObjCAutoRefCount && !isUnevaluatedContext()) 2954 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl()) 2955 ImplicitlyRetainedSelfLocs.push_back({Loc, BD}); 2956 2957 return Result; 2958 } 2959 2960 /// The parser has read a name in, and Sema has detected that we're currently 2961 /// inside an ObjC method. Perform some additional checks and determine if we 2962 /// should form a reference to an ivar. If so, build an expression referencing 2963 /// that ivar. 2964 ExprResult 2965 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2966 IdentifierInfo *II, bool AllowBuiltinCreation) { 2967 // FIXME: Integrate this lookup step into LookupParsedName. 2968 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II); 2969 if (Ivar.isInvalid()) 2970 return ExprError(); 2971 if (Ivar.isUsable()) 2972 return BuildIvarRefExpr(S, Lookup.getNameLoc(), 2973 cast<ObjCIvarDecl>(Ivar.get())); 2974 2975 if (Lookup.empty() && II && AllowBuiltinCreation) 2976 LookupBuiltin(Lookup); 2977 2978 // Sentinel value saying that we didn't do anything special. 2979 return ExprResult(false); 2980 } 2981 2982 /// Cast a base object to a member's actual type. 2983 /// 2984 /// There are two relevant checks: 2985 /// 2986 /// C++ [class.access.base]p7: 2987 /// 2988 /// If a class member access operator [...] is used to access a non-static 2989 /// data member or non-static member function, the reference is ill-formed if 2990 /// the left operand [...] cannot be implicitly converted to a pointer to the 2991 /// naming class of the right operand. 2992 /// 2993 /// C++ [expr.ref]p7: 2994 /// 2995 /// If E2 is a non-static data member or a non-static member function, the 2996 /// program is ill-formed if the class of which E2 is directly a member is an 2997 /// ambiguous base (11.8) of the naming class (11.9.3) of E2. 2998 /// 2999 /// Note that the latter check does not consider access; the access of the 3000 /// "real" base class is checked as appropriate when checking the access of the 3001 /// member name. 3002 ExprResult 3003 Sema::PerformObjectMemberConversion(Expr *From, 3004 NestedNameSpecifier *Qualifier, 3005 NamedDecl *FoundDecl, 3006 NamedDecl *Member) { 3007 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 3008 if (!RD) 3009 return From; 3010 3011 QualType DestRecordType; 3012 QualType DestType; 3013 QualType FromRecordType; 3014 QualType FromType = From->getType(); 3015 bool PointerConversions = false; 3016 if (isa<FieldDecl>(Member)) { 3017 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 3018 auto FromPtrType = FromType->getAs<PointerType>(); 3019 DestRecordType = Context.getAddrSpaceQualType( 3020 DestRecordType, FromPtrType 3021 ? FromType->getPointeeType().getAddressSpace() 3022 : FromType.getAddressSpace()); 3023 3024 if (FromPtrType) { 3025 DestType = Context.getPointerType(DestRecordType); 3026 FromRecordType = FromPtrType->getPointeeType(); 3027 PointerConversions = true; 3028 } else { 3029 DestType = DestRecordType; 3030 FromRecordType = FromType; 3031 } 3032 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 3033 if (Method->isStatic()) 3034 return From; 3035 3036 DestType = Method->getThisType(); 3037 DestRecordType = DestType->getPointeeType(); 3038 3039 if (FromType->getAs<PointerType>()) { 3040 FromRecordType = FromType->getPointeeType(); 3041 PointerConversions = true; 3042 } else { 3043 FromRecordType = FromType; 3044 DestType = DestRecordType; 3045 } 3046 3047 LangAS FromAS = FromRecordType.getAddressSpace(); 3048 LangAS DestAS = DestRecordType.getAddressSpace(); 3049 if (FromAS != DestAS) { 3050 QualType FromRecordTypeWithoutAS = 3051 Context.removeAddrSpaceQualType(FromRecordType); 3052 QualType FromTypeWithDestAS = 3053 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS); 3054 if (PointerConversions) 3055 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS); 3056 From = ImpCastExprToType(From, FromTypeWithDestAS, 3057 CK_AddressSpaceConversion, From->getValueKind()) 3058 .get(); 3059 } 3060 } else { 3061 // No conversion necessary. 3062 return From; 3063 } 3064 3065 if (DestType->isDependentType() || FromType->isDependentType()) 3066 return From; 3067 3068 // If the unqualified types are the same, no conversion is necessary. 3069 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3070 return From; 3071 3072 SourceRange FromRange = From->getSourceRange(); 3073 SourceLocation FromLoc = FromRange.getBegin(); 3074 3075 ExprValueKind VK = From->getValueKind(); 3076 3077 // C++ [class.member.lookup]p8: 3078 // [...] Ambiguities can often be resolved by qualifying a name with its 3079 // class name. 3080 // 3081 // If the member was a qualified name and the qualified referred to a 3082 // specific base subobject type, we'll cast to that intermediate type 3083 // first and then to the object in which the member is declared. That allows 3084 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 3085 // 3086 // class Base { public: int x; }; 3087 // class Derived1 : public Base { }; 3088 // class Derived2 : public Base { }; 3089 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 3090 // 3091 // void VeryDerived::f() { 3092 // x = 17; // error: ambiguous base subobjects 3093 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 3094 // } 3095 if (Qualifier && Qualifier->getAsType()) { 3096 QualType QType = QualType(Qualifier->getAsType(), 0); 3097 assert(QType->isRecordType() && "lookup done with non-record type"); 3098 3099 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0); 3100 3101 // In C++98, the qualifier type doesn't actually have to be a base 3102 // type of the object type, in which case we just ignore it. 3103 // Otherwise build the appropriate casts. 3104 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 3105 CXXCastPath BasePath; 3106 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 3107 FromLoc, FromRange, &BasePath)) 3108 return ExprError(); 3109 3110 if (PointerConversions) 3111 QType = Context.getPointerType(QType); 3112 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 3113 VK, &BasePath).get(); 3114 3115 FromType = QType; 3116 FromRecordType = QRecordType; 3117 3118 // If the qualifier type was the same as the destination type, 3119 // we're done. 3120 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 3121 return From; 3122 } 3123 } 3124 3125 CXXCastPath BasePath; 3126 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 3127 FromLoc, FromRange, &BasePath, 3128 /*IgnoreAccess=*/true)) 3129 return ExprError(); 3130 3131 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 3132 VK, &BasePath); 3133 } 3134 3135 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 3136 const LookupResult &R, 3137 bool HasTrailingLParen) { 3138 // Only when used directly as the postfix-expression of a call. 3139 if (!HasTrailingLParen) 3140 return false; 3141 3142 // Never if a scope specifier was provided. 3143 if (SS.isSet()) 3144 return false; 3145 3146 // Only in C++ or ObjC++. 3147 if (!getLangOpts().CPlusPlus) 3148 return false; 3149 3150 // Turn off ADL when we find certain kinds of declarations during 3151 // normal lookup: 3152 for (NamedDecl *D : R) { 3153 // C++0x [basic.lookup.argdep]p3: 3154 // -- a declaration of a class member 3155 // Since using decls preserve this property, we check this on the 3156 // original decl. 3157 if (D->isCXXClassMember()) 3158 return false; 3159 3160 // C++0x [basic.lookup.argdep]p3: 3161 // -- a block-scope function declaration that is not a 3162 // using-declaration 3163 // NOTE: we also trigger this for function templates (in fact, we 3164 // don't check the decl type at all, since all other decl types 3165 // turn off ADL anyway). 3166 if (isa<UsingShadowDecl>(D)) 3167 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3168 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 3169 return false; 3170 3171 // C++0x [basic.lookup.argdep]p3: 3172 // -- a declaration that is neither a function or a function 3173 // template 3174 // And also for builtin functions. 3175 if (isa<FunctionDecl>(D)) { 3176 FunctionDecl *FDecl = cast<FunctionDecl>(D); 3177 3178 // But also builtin functions. 3179 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 3180 return false; 3181 } else if (!isa<FunctionTemplateDecl>(D)) 3182 return false; 3183 } 3184 3185 return true; 3186 } 3187 3188 3189 /// Diagnoses obvious problems with the use of the given declaration 3190 /// as an expression. This is only actually called for lookups that 3191 /// were not overloaded, and it doesn't promise that the declaration 3192 /// will in fact be used. 3193 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D, 3194 bool AcceptInvalid) { 3195 if (D->isInvalidDecl() && !AcceptInvalid) 3196 return true; 3197 3198 if (isa<TypedefNameDecl>(D)) { 3199 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 3200 return true; 3201 } 3202 3203 if (isa<ObjCInterfaceDecl>(D)) { 3204 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 3205 return true; 3206 } 3207 3208 if (isa<NamespaceDecl>(D)) { 3209 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 3210 return true; 3211 } 3212 3213 return false; 3214 } 3215 3216 // Certain multiversion types should be treated as overloaded even when there is 3217 // only one result. 3218 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 3219 assert(R.isSingleResult() && "Expected only a single result"); 3220 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 3221 return FD && 3222 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 3223 } 3224 3225 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3226 LookupResult &R, bool NeedsADL, 3227 bool AcceptInvalidDecl) { 3228 // If this is a single, fully-resolved result and we don't need ADL, 3229 // just build an ordinary singleton decl ref. 3230 if (!NeedsADL && R.isSingleResult() && 3231 !R.getAsSingle<FunctionTemplateDecl>() && 3232 !ShouldLookupResultBeMultiVersionOverload(R)) 3233 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 3234 R.getRepresentativeDecl(), nullptr, 3235 AcceptInvalidDecl); 3236 3237 // We only need to check the declaration if there's exactly one 3238 // result, because in the overloaded case the results can only be 3239 // functions and function templates. 3240 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 3241 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(), 3242 AcceptInvalidDecl)) 3243 return ExprError(); 3244 3245 // Otherwise, just build an unresolved lookup expression. Suppress 3246 // any lookup-related diagnostics; we'll hash these out later, when 3247 // we've picked a target. 3248 R.suppressDiagnostics(); 3249 3250 UnresolvedLookupExpr *ULE 3251 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 3252 SS.getWithLocInContext(Context), 3253 R.getLookupNameInfo(), 3254 NeedsADL, R.isOverloadedResult(), 3255 R.begin(), R.end()); 3256 3257 return ULE; 3258 } 3259 3260 static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, 3261 SourceLocation loc, 3262 ValueDecl *var); 3263 3264 /// Complete semantic analysis for a reference to the given declaration. 3265 ExprResult Sema::BuildDeclarationNameExpr( 3266 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3267 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 3268 bool AcceptInvalidDecl) { 3269 assert(D && "Cannot refer to a NULL declaration"); 3270 assert(!isa<FunctionTemplateDecl>(D) && 3271 "Cannot refer unambiguously to a function template"); 3272 3273 SourceLocation Loc = NameInfo.getLoc(); 3274 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) { 3275 // Recovery from invalid cases (e.g. D is an invalid Decl). 3276 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up 3277 // diagnostics, as invalid decls use int as a fallback type. 3278 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {}); 3279 } 3280 3281 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 3282 // Specifically diagnose references to class templates that are missing 3283 // a template argument list. 3284 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 3285 return ExprError(); 3286 } 3287 3288 // Make sure that we're referring to a value. 3289 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) { 3290 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange(); 3291 Diag(D->getLocation(), diag::note_declared_at); 3292 return ExprError(); 3293 } 3294 3295 // Check whether this declaration can be used. Note that we suppress 3296 // this check when we're going to perform argument-dependent lookup 3297 // on this function name, because this might not be the function 3298 // that overload resolution actually selects. 3299 if (DiagnoseUseOfDecl(D, Loc)) 3300 return ExprError(); 3301 3302 auto *VD = cast<ValueDecl>(D); 3303 3304 // Only create DeclRefExpr's for valid Decl's. 3305 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 3306 return ExprError(); 3307 3308 // Handle members of anonymous structs and unions. If we got here, 3309 // and the reference is to a class member indirect field, then this 3310 // must be the subject of a pointer-to-member expression. 3311 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 3312 if (!indirectField->isCXXClassMember()) 3313 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 3314 indirectField); 3315 3316 QualType type = VD->getType(); 3317 if (type.isNull()) 3318 return ExprError(); 3319 ExprValueKind valueKind = VK_PRValue; 3320 3321 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of 3322 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value, 3323 // is expanded by some outer '...' in the context of the use. 3324 type = type.getNonPackExpansionType(); 3325 3326 switch (D->getKind()) { 3327 // Ignore all the non-ValueDecl kinds. 3328 #define ABSTRACT_DECL(kind) 3329 #define VALUE(type, base) 3330 #define DECL(type, base) case Decl::type: 3331 #include "clang/AST/DeclNodes.inc" 3332 llvm_unreachable("invalid value decl kind"); 3333 3334 // These shouldn't make it here. 3335 case Decl::ObjCAtDefsField: 3336 llvm_unreachable("forming non-member reference to ivar?"); 3337 3338 // Enum constants are always r-values and never references. 3339 // Unresolved using declarations are dependent. 3340 case Decl::EnumConstant: 3341 case Decl::UnresolvedUsingValue: 3342 case Decl::OMPDeclareReduction: 3343 case Decl::OMPDeclareMapper: 3344 valueKind = VK_PRValue; 3345 break; 3346 3347 // Fields and indirect fields that got here must be for 3348 // pointer-to-member expressions; we just call them l-values for 3349 // internal consistency, because this subexpression doesn't really 3350 // exist in the high-level semantics. 3351 case Decl::Field: 3352 case Decl::IndirectField: 3353 case Decl::ObjCIvar: 3354 assert(getLangOpts().CPlusPlus && "building reference to field in C?"); 3355 3356 // These can't have reference type in well-formed programs, but 3357 // for internal consistency we do this anyway. 3358 type = type.getNonReferenceType(); 3359 valueKind = VK_LValue; 3360 break; 3361 3362 // Non-type template parameters are either l-values or r-values 3363 // depending on the type. 3364 case Decl::NonTypeTemplateParm: { 3365 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 3366 type = reftype->getPointeeType(); 3367 valueKind = VK_LValue; // even if the parameter is an r-value reference 3368 break; 3369 } 3370 3371 // [expr.prim.id.unqual]p2: 3372 // If the entity is a template parameter object for a template 3373 // parameter of type T, the type of the expression is const T. 3374 // [...] The expression is an lvalue if the entity is a [...] template 3375 // parameter object. 3376 if (type->isRecordType()) { 3377 type = type.getUnqualifiedType().withConst(); 3378 valueKind = VK_LValue; 3379 break; 3380 } 3381 3382 // For non-references, we need to strip qualifiers just in case 3383 // the template parameter was declared as 'const int' or whatever. 3384 valueKind = VK_PRValue; 3385 type = type.getUnqualifiedType(); 3386 break; 3387 } 3388 3389 case Decl::Var: 3390 case Decl::VarTemplateSpecialization: 3391 case Decl::VarTemplatePartialSpecialization: 3392 case Decl::Decomposition: 3393 case Decl::OMPCapturedExpr: 3394 // In C, "extern void blah;" is valid and is an r-value. 3395 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() && 3396 type->isVoidType()) { 3397 valueKind = VK_PRValue; 3398 break; 3399 } 3400 [[fallthrough]]; 3401 3402 case Decl::ImplicitParam: 3403 case Decl::ParmVar: { 3404 // These are always l-values. 3405 valueKind = VK_LValue; 3406 type = type.getNonReferenceType(); 3407 3408 // FIXME: Does the addition of const really only apply in 3409 // potentially-evaluated contexts? Since the variable isn't actually 3410 // captured in an unevaluated context, it seems that the answer is no. 3411 if (!isUnevaluatedContext()) { 3412 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 3413 if (!CapturedType.isNull()) 3414 type = CapturedType; 3415 } 3416 3417 break; 3418 } 3419 3420 case Decl::Binding: 3421 // These are always lvalues. 3422 valueKind = VK_LValue; 3423 type = type.getNonReferenceType(); 3424 break; 3425 3426 case Decl::Function: { 3427 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 3428 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) { 3429 type = Context.BuiltinFnTy; 3430 valueKind = VK_PRValue; 3431 break; 3432 } 3433 } 3434 3435 const FunctionType *fty = type->castAs<FunctionType>(); 3436 3437 // If we're referring to a function with an __unknown_anytype 3438 // result type, make the entire expression __unknown_anytype. 3439 if (fty->getReturnType() == Context.UnknownAnyTy) { 3440 type = Context.UnknownAnyTy; 3441 valueKind = VK_PRValue; 3442 break; 3443 } 3444 3445 // Functions are l-values in C++. 3446 if (getLangOpts().CPlusPlus) { 3447 valueKind = VK_LValue; 3448 break; 3449 } 3450 3451 // C99 DR 316 says that, if a function type comes from a 3452 // function definition (without a prototype), that type is only 3453 // used for checking compatibility. Therefore, when referencing 3454 // the function, we pretend that we don't have the full function 3455 // type. 3456 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty)) 3457 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3458 fty->getExtInfo()); 3459 3460 // Functions are r-values in C. 3461 valueKind = VK_PRValue; 3462 break; 3463 } 3464 3465 case Decl::CXXDeductionGuide: 3466 llvm_unreachable("building reference to deduction guide"); 3467 3468 case Decl::MSProperty: 3469 case Decl::MSGuid: 3470 case Decl::TemplateParamObject: 3471 // FIXME: Should MSGuidDecl and template parameter objects be subject to 3472 // capture in OpenMP, or duplicated between host and device? 3473 valueKind = VK_LValue; 3474 break; 3475 3476 case Decl::UnnamedGlobalConstant: 3477 valueKind = VK_LValue; 3478 break; 3479 3480 case Decl::CXXMethod: 3481 // If we're referring to a method with an __unknown_anytype 3482 // result type, make the entire expression __unknown_anytype. 3483 // This should only be possible with a type written directly. 3484 if (const FunctionProtoType *proto = 3485 dyn_cast<FunctionProtoType>(VD->getType())) 3486 if (proto->getReturnType() == Context.UnknownAnyTy) { 3487 type = Context.UnknownAnyTy; 3488 valueKind = VK_PRValue; 3489 break; 3490 } 3491 3492 // C++ methods are l-values if static, r-values if non-static. 3493 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3494 valueKind = VK_LValue; 3495 break; 3496 } 3497 [[fallthrough]]; 3498 3499 case Decl::CXXConversion: 3500 case Decl::CXXDestructor: 3501 case Decl::CXXConstructor: 3502 valueKind = VK_PRValue; 3503 break; 3504 } 3505 3506 auto *E = 3507 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3508 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs); 3509 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We 3510 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type 3511 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus 3512 // diagnostics). 3513 if (VD->isInvalidDecl() && E) 3514 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E}); 3515 return E; 3516 } 3517 3518 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3519 SmallString<32> &Target) { 3520 Target.resize(CharByteWidth * (Source.size() + 1)); 3521 char *ResultPtr = &Target[0]; 3522 const llvm::UTF8 *ErrorPtr; 3523 bool success = 3524 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3525 (void)success; 3526 assert(success); 3527 Target.resize(ResultPtr - &Target[0]); 3528 } 3529 3530 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3531 PredefinedExpr::IdentKind IK) { 3532 // Pick the current block, lambda, captured statement or function. 3533 Decl *currentDecl = nullptr; 3534 if (const BlockScopeInfo *BSI = getCurBlock()) 3535 currentDecl = BSI->TheDecl; 3536 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3537 currentDecl = LSI->CallOperator; 3538 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3539 currentDecl = CSI->TheCapturedDecl; 3540 else 3541 currentDecl = getCurFunctionOrMethodDecl(); 3542 3543 if (!currentDecl) { 3544 Diag(Loc, diag::ext_predef_outside_function); 3545 currentDecl = Context.getTranslationUnitDecl(); 3546 } 3547 3548 QualType ResTy; 3549 StringLiteral *SL = nullptr; 3550 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3551 ResTy = Context.DependentTy; 3552 else { 3553 // Pre-defined identifiers are of type char[x], where x is the length of 3554 // the string. 3555 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3556 unsigned Length = Str.length(); 3557 3558 llvm::APInt LengthI(32, Length + 1); 3559 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3560 ResTy = 3561 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3562 SmallString<32> RawChars; 3563 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3564 Str, RawChars); 3565 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3566 ArrayType::Normal, 3567 /*IndexTypeQuals*/ 0); 3568 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3569 /*Pascal*/ false, ResTy, Loc); 3570 } else { 3571 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3572 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr, 3573 ArrayType::Normal, 3574 /*IndexTypeQuals*/ 0); 3575 SL = StringLiteral::Create(Context, Str, StringLiteral::Ordinary, 3576 /*Pascal*/ false, ResTy, Loc); 3577 } 3578 } 3579 3580 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3581 } 3582 3583 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3584 SourceLocation LParen, 3585 SourceLocation RParen, 3586 TypeSourceInfo *TSI) { 3587 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI); 3588 } 3589 3590 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, 3591 SourceLocation LParen, 3592 SourceLocation RParen, 3593 ParsedType ParsedTy) { 3594 TypeSourceInfo *TSI = nullptr; 3595 QualType Ty = GetTypeFromParser(ParsedTy, &TSI); 3596 3597 if (Ty.isNull()) 3598 return ExprError(); 3599 if (!TSI) 3600 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen); 3601 3602 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI); 3603 } 3604 3605 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3606 PredefinedExpr::IdentKind IK; 3607 3608 switch (Kind) { 3609 default: llvm_unreachable("Unknown simple primary expr!"); 3610 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3611 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3612 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3613 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3614 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3615 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3616 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3617 } 3618 3619 return BuildPredefinedExpr(Loc, IK); 3620 } 3621 3622 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3623 SmallString<16> CharBuffer; 3624 bool Invalid = false; 3625 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3626 if (Invalid) 3627 return ExprError(); 3628 3629 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3630 PP, Tok.getKind()); 3631 if (Literal.hadError()) 3632 return ExprError(); 3633 3634 QualType Ty; 3635 if (Literal.isWide()) 3636 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3637 else if (Literal.isUTF8() && getLangOpts().C2x) 3638 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C2x 3639 else if (Literal.isUTF8() && getLangOpts().Char8) 3640 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3641 else if (Literal.isUTF16()) 3642 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3643 else if (Literal.isUTF32()) 3644 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3645 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3646 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3647 else 3648 Ty = Context.CharTy; // 'x' -> char in C++; 3649 // u8'x' -> char in C11-C17 and in C++ without char8_t. 3650 3651 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3652 if (Literal.isWide()) 3653 Kind = CharacterLiteral::Wide; 3654 else if (Literal.isUTF16()) 3655 Kind = CharacterLiteral::UTF16; 3656 else if (Literal.isUTF32()) 3657 Kind = CharacterLiteral::UTF32; 3658 else if (Literal.isUTF8()) 3659 Kind = CharacterLiteral::UTF8; 3660 3661 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3662 Tok.getLocation()); 3663 3664 if (Literal.getUDSuffix().empty()) 3665 return Lit; 3666 3667 // We're building a user-defined literal. 3668 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3669 SourceLocation UDSuffixLoc = 3670 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3671 3672 // Make sure we're allowed user-defined literals here. 3673 if (!UDLScope) 3674 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3675 3676 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3677 // operator "" X (ch) 3678 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3679 Lit, Tok.getLocation()); 3680 } 3681 3682 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3683 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3684 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3685 Context.IntTy, Loc); 3686 } 3687 3688 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3689 QualType Ty, SourceLocation Loc) { 3690 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3691 3692 using llvm::APFloat; 3693 APFloat Val(Format); 3694 3695 APFloat::opStatus result = Literal.GetFloatValue(Val); 3696 3697 // Overflow is always an error, but underflow is only an error if 3698 // we underflowed to zero (APFloat reports denormals as underflow). 3699 if ((result & APFloat::opOverflow) || 3700 ((result & APFloat::opUnderflow) && Val.isZero())) { 3701 unsigned diagnostic; 3702 SmallString<20> buffer; 3703 if (result & APFloat::opOverflow) { 3704 diagnostic = diag::warn_float_overflow; 3705 APFloat::getLargest(Format).toString(buffer); 3706 } else { 3707 diagnostic = diag::warn_float_underflow; 3708 APFloat::getSmallest(Format).toString(buffer); 3709 } 3710 3711 S.Diag(Loc, diagnostic) 3712 << Ty 3713 << StringRef(buffer.data(), buffer.size()); 3714 } 3715 3716 bool isExact = (result == APFloat::opOK); 3717 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3718 } 3719 3720 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3721 assert(E && "Invalid expression"); 3722 3723 if (E->isValueDependent()) 3724 return false; 3725 3726 QualType QT = E->getType(); 3727 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3728 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3729 return true; 3730 } 3731 3732 llvm::APSInt ValueAPS; 3733 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3734 3735 if (R.isInvalid()) 3736 return true; 3737 3738 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3739 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3740 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3741 << toString(ValueAPS, 10) << ValueIsPositive; 3742 return true; 3743 } 3744 3745 return false; 3746 } 3747 3748 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3749 // Fast path for a single digit (which is quite common). A single digit 3750 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3751 if (Tok.getLength() == 1) { 3752 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3753 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3754 } 3755 3756 SmallString<128> SpellingBuffer; 3757 // NumericLiteralParser wants to overread by one character. Add padding to 3758 // the buffer in case the token is copied to the buffer. If getSpelling() 3759 // returns a StringRef to the memory buffer, it should have a null char at 3760 // the EOF, so it is also safe. 3761 SpellingBuffer.resize(Tok.getLength() + 1); 3762 3763 // Get the spelling of the token, which eliminates trigraphs, etc. 3764 bool Invalid = false; 3765 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3766 if (Invalid) 3767 return ExprError(); 3768 3769 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), 3770 PP.getSourceManager(), PP.getLangOpts(), 3771 PP.getTargetInfo(), PP.getDiagnostics()); 3772 if (Literal.hadError) 3773 return ExprError(); 3774 3775 if (Literal.hasUDSuffix()) { 3776 // We're building a user-defined literal. 3777 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3778 SourceLocation UDSuffixLoc = 3779 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3780 3781 // Make sure we're allowed user-defined literals here. 3782 if (!UDLScope) 3783 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3784 3785 QualType CookedTy; 3786 if (Literal.isFloatingLiteral()) { 3787 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3788 // long double, the literal is treated as a call of the form 3789 // operator "" X (f L) 3790 CookedTy = Context.LongDoubleTy; 3791 } else { 3792 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3793 // unsigned long long, the literal is treated as a call of the form 3794 // operator "" X (n ULL) 3795 CookedTy = Context.UnsignedLongLongTy; 3796 } 3797 3798 DeclarationName OpName = 3799 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3800 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3801 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3802 3803 SourceLocation TokLoc = Tok.getLocation(); 3804 3805 // Perform literal operator lookup to determine if we're building a raw 3806 // literal or a cooked one. 3807 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3808 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3809 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3810 /*AllowStringTemplatePack*/ false, 3811 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3812 case LOLR_ErrorNoDiagnostic: 3813 // Lookup failure for imaginary constants isn't fatal, there's still the 3814 // GNU extension producing _Complex types. 3815 break; 3816 case LOLR_Error: 3817 return ExprError(); 3818 case LOLR_Cooked: { 3819 Expr *Lit; 3820 if (Literal.isFloatingLiteral()) { 3821 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3822 } else { 3823 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3824 if (Literal.GetIntegerValue(ResultVal)) 3825 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3826 << /* Unsigned */ 1; 3827 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3828 Tok.getLocation()); 3829 } 3830 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3831 } 3832 3833 case LOLR_Raw: { 3834 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3835 // literal is treated as a call of the form 3836 // operator "" X ("n") 3837 unsigned Length = Literal.getUDSuffixOffset(); 3838 QualType StrTy = Context.getConstantArrayType( 3839 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3840 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0); 3841 Expr *Lit = 3842 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length), 3843 StringLiteral::Ordinary, 3844 /*Pascal*/ false, StrTy, &TokLoc, 1); 3845 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3846 } 3847 3848 case LOLR_Template: { 3849 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3850 // template), L is treated as a call fo the form 3851 // operator "" X <'c1', 'c2', ... 'ck'>() 3852 // where n is the source character sequence c1 c2 ... ck. 3853 TemplateArgumentListInfo ExplicitArgs; 3854 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3855 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3856 llvm::APSInt Value(CharBits, CharIsUnsigned); 3857 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3858 Value = TokSpelling[I]; 3859 TemplateArgument Arg(Context, Value, Context.CharTy); 3860 TemplateArgumentLocInfo ArgInfo; 3861 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3862 } 3863 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, TokLoc, 3864 &ExplicitArgs); 3865 } 3866 case LOLR_StringTemplatePack: 3867 llvm_unreachable("unexpected literal operator lookup result"); 3868 } 3869 } 3870 3871 Expr *Res; 3872 3873 if (Literal.isFixedPointLiteral()) { 3874 QualType Ty; 3875 3876 if (Literal.isAccum) { 3877 if (Literal.isHalf) { 3878 Ty = Context.ShortAccumTy; 3879 } else if (Literal.isLong) { 3880 Ty = Context.LongAccumTy; 3881 } else { 3882 Ty = Context.AccumTy; 3883 } 3884 } else if (Literal.isFract) { 3885 if (Literal.isHalf) { 3886 Ty = Context.ShortFractTy; 3887 } else if (Literal.isLong) { 3888 Ty = Context.LongFractTy; 3889 } else { 3890 Ty = Context.FractTy; 3891 } 3892 } 3893 3894 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3895 3896 bool isSigned = !Literal.isUnsigned; 3897 unsigned scale = Context.getFixedPointScale(Ty); 3898 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3899 3900 llvm::APInt Val(bit_width, 0, isSigned); 3901 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3902 bool ValIsZero = Val.isZero() && !Overflowed; 3903 3904 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3905 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3906 // Clause 6.4.4 - The value of a constant shall be in the range of 3907 // representable values for its type, with exception for constants of a 3908 // fract type with a value of exactly 1; such a constant shall denote 3909 // the maximal value for the type. 3910 --Val; 3911 else if (Val.ugt(MaxVal) || Overflowed) 3912 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3913 3914 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3915 Tok.getLocation(), scale); 3916 } else if (Literal.isFloatingLiteral()) { 3917 QualType Ty; 3918 if (Literal.isHalf){ 3919 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts())) 3920 Ty = Context.HalfTy; 3921 else { 3922 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3923 return ExprError(); 3924 } 3925 } else if (Literal.isFloat) 3926 Ty = Context.FloatTy; 3927 else if (Literal.isLong) 3928 Ty = Context.LongDoubleTy; 3929 else if (Literal.isFloat16) 3930 Ty = Context.Float16Ty; 3931 else if (Literal.isFloat128) 3932 Ty = Context.Float128Ty; 3933 else 3934 Ty = Context.DoubleTy; 3935 3936 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3937 3938 if (Ty == Context.DoubleTy) { 3939 if (getLangOpts().SinglePrecisionConstants) { 3940 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) { 3941 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3942 } 3943 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption( 3944 "cl_khr_fp64", getLangOpts())) { 3945 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3946 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64) 3947 << (getLangOpts().getOpenCLCompatibleVersion() >= 300); 3948 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3949 } 3950 } 3951 } else if (!Literal.isIntegerLiteral()) { 3952 return ExprError(); 3953 } else { 3954 QualType Ty; 3955 3956 // 'z/uz' literals are a C++2b feature. 3957 if (Literal.isSizeT) 3958 Diag(Tok.getLocation(), getLangOpts().CPlusPlus 3959 ? getLangOpts().CPlusPlus2b 3960 ? diag::warn_cxx20_compat_size_t_suffix 3961 : diag::ext_cxx2b_size_t_suffix 3962 : diag::err_cxx2b_size_t_suffix); 3963 3964 // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++, 3965 // but we do not currently support the suffix in C++ mode because it's not 3966 // entirely clear whether WG21 will prefer this suffix to return a library 3967 // type such as std::bit_int instead of returning a _BitInt. 3968 if (Literal.isBitInt && !getLangOpts().CPlusPlus) 3969 PP.Diag(Tok.getLocation(), getLangOpts().C2x 3970 ? diag::warn_c2x_compat_bitint_suffix 3971 : diag::ext_c2x_bitint_suffix); 3972 3973 // Get the value in the widest-possible width. What is "widest" depends on 3974 // whether the literal is a bit-precise integer or not. For a bit-precise 3975 // integer type, try to scan the source to determine how many bits are 3976 // needed to represent the value. This may seem a bit expensive, but trying 3977 // to get the integer value from an overly-wide APInt is *extremely* 3978 // expensive, so the naive approach of assuming 3979 // llvm::IntegerType::MAX_INT_BITS is a big performance hit. 3980 unsigned BitsNeeded = 3981 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded( 3982 Literal.getLiteralDigits(), Literal.getRadix()) 3983 : Context.getTargetInfo().getIntMaxTWidth(); 3984 llvm::APInt ResultVal(BitsNeeded, 0); 3985 3986 if (Literal.GetIntegerValue(ResultVal)) { 3987 // If this value didn't fit into uintmax_t, error and force to ull. 3988 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3989 << /* Unsigned */ 1; 3990 Ty = Context.UnsignedLongLongTy; 3991 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3992 "long long is not intmax_t?"); 3993 } else { 3994 // If this value fits into a ULL, try to figure out what else it fits into 3995 // according to the rules of C99 6.4.4.1p5. 3996 3997 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3998 // be an unsigned int. 3999 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 4000 4001 // Check from smallest to largest, picking the smallest type we can. 4002 unsigned Width = 0; 4003 4004 // Microsoft specific integer suffixes are explicitly sized. 4005 if (Literal.MicrosoftInteger) { 4006 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 4007 Width = 8; 4008 Ty = Context.CharTy; 4009 } else { 4010 Width = Literal.MicrosoftInteger; 4011 Ty = Context.getIntTypeForBitwidth(Width, 4012 /*Signed=*/!Literal.isUnsigned); 4013 } 4014 } 4015 4016 // Bit-precise integer literals are automagically-sized based on the 4017 // width required by the literal. 4018 if (Literal.isBitInt) { 4019 // The signed version has one more bit for the sign value. There are no 4020 // zero-width bit-precise integers, even if the literal value is 0. 4021 Width = std::max(ResultVal.getActiveBits(), 1u) + 4022 (Literal.isUnsigned ? 0u : 1u); 4023 4024 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH, 4025 // and reset the type to the largest supported width. 4026 unsigned int MaxBitIntWidth = 4027 Context.getTargetInfo().getMaxBitIntWidth(); 4028 if (Width > MaxBitIntWidth) { 4029 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 4030 << Literal.isUnsigned; 4031 Width = MaxBitIntWidth; 4032 } 4033 4034 // Reset the result value to the smaller APInt and select the correct 4035 // type to be used. Note, we zext even for signed values because the 4036 // literal itself is always an unsigned value (a preceeding - is a 4037 // unary operator, not part of the literal). 4038 ResultVal = ResultVal.zextOrTrunc(Width); 4039 Ty = Context.getBitIntType(Literal.isUnsigned, Width); 4040 } 4041 4042 // Check C++2b size_t literals. 4043 if (Literal.isSizeT) { 4044 assert(!Literal.MicrosoftInteger && 4045 "size_t literals can't be Microsoft literals"); 4046 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth( 4047 Context.getTargetInfo().getSizeType()); 4048 4049 // Does it fit in size_t? 4050 if (ResultVal.isIntN(SizeTSize)) { 4051 // Does it fit in ssize_t? 4052 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0) 4053 Ty = Context.getSignedSizeType(); 4054 else if (AllowUnsigned) 4055 Ty = Context.getSizeType(); 4056 Width = SizeTSize; 4057 } 4058 } 4059 4060 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong && 4061 !Literal.isSizeT) { 4062 // Are int/unsigned possibilities? 4063 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 4064 4065 // Does it fit in a unsigned int? 4066 if (ResultVal.isIntN(IntSize)) { 4067 // Does it fit in a signed int? 4068 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 4069 Ty = Context.IntTy; 4070 else if (AllowUnsigned) 4071 Ty = Context.UnsignedIntTy; 4072 Width = IntSize; 4073 } 4074 } 4075 4076 // Are long/unsigned long possibilities? 4077 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) { 4078 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 4079 4080 // Does it fit in a unsigned long? 4081 if (ResultVal.isIntN(LongSize)) { 4082 // Does it fit in a signed long? 4083 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 4084 Ty = Context.LongTy; 4085 else if (AllowUnsigned) 4086 Ty = Context.UnsignedLongTy; 4087 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 4088 // is compatible. 4089 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 4090 const unsigned LongLongSize = 4091 Context.getTargetInfo().getLongLongWidth(); 4092 Diag(Tok.getLocation(), 4093 getLangOpts().CPlusPlus 4094 ? Literal.isLong 4095 ? diag::warn_old_implicitly_unsigned_long_cxx 4096 : /*C++98 UB*/ diag:: 4097 ext_old_implicitly_unsigned_long_cxx 4098 : diag::warn_old_implicitly_unsigned_long) 4099 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 4100 : /*will be ill-formed*/ 1); 4101 Ty = Context.UnsignedLongTy; 4102 } 4103 Width = LongSize; 4104 } 4105 } 4106 4107 // Check long long if needed. 4108 if (Ty.isNull() && !Literal.isSizeT) { 4109 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 4110 4111 // Does it fit in a unsigned long long? 4112 if (ResultVal.isIntN(LongLongSize)) { 4113 // Does it fit in a signed long long? 4114 // To be compatible with MSVC, hex integer literals ending with the 4115 // LL or i64 suffix are always signed in Microsoft mode. 4116 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 4117 (getLangOpts().MSVCCompat && Literal.isLongLong))) 4118 Ty = Context.LongLongTy; 4119 else if (AllowUnsigned) 4120 Ty = Context.UnsignedLongLongTy; 4121 Width = LongLongSize; 4122 4123 // 'long long' is a C99 or C++11 feature, whether the literal 4124 // explicitly specified 'long long' or we needed the extra width. 4125 if (getLangOpts().CPlusPlus) 4126 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 4127 ? diag::warn_cxx98_compat_longlong 4128 : diag::ext_cxx11_longlong); 4129 else if (!getLangOpts().C99) 4130 Diag(Tok.getLocation(), diag::ext_c99_longlong); 4131 } 4132 } 4133 4134 // If we still couldn't decide a type, we either have 'size_t' literal 4135 // that is out of range, or a decimal literal that does not fit in a 4136 // signed long long and has no U suffix. 4137 if (Ty.isNull()) { 4138 if (Literal.isSizeT) 4139 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large) 4140 << Literal.isUnsigned; 4141 else 4142 Diag(Tok.getLocation(), 4143 diag::ext_integer_literal_too_large_for_signed); 4144 Ty = Context.UnsignedLongLongTy; 4145 Width = Context.getTargetInfo().getLongLongWidth(); 4146 } 4147 4148 if (ResultVal.getBitWidth() != Width) 4149 ResultVal = ResultVal.trunc(Width); 4150 } 4151 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 4152 } 4153 4154 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 4155 if (Literal.isImaginary) { 4156 Res = new (Context) ImaginaryLiteral(Res, 4157 Context.getComplexType(Res->getType())); 4158 4159 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 4160 } 4161 return Res; 4162 } 4163 4164 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 4165 assert(E && "ActOnParenExpr() missing expr"); 4166 QualType ExprTy = E->getType(); 4167 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() && 4168 !E->isLValue() && ExprTy->hasFloatingRepresentation()) 4169 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E); 4170 return new (Context) ParenExpr(L, R, E); 4171 } 4172 4173 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 4174 SourceLocation Loc, 4175 SourceRange ArgRange) { 4176 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 4177 // scalar or vector data type argument..." 4178 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 4179 // type (C99 6.2.5p18) or void. 4180 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 4181 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 4182 << T << ArgRange; 4183 return true; 4184 } 4185 4186 assert((T->isVoidType() || !T->isIncompleteType()) && 4187 "Scalar types should always be complete"); 4188 return false; 4189 } 4190 4191 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 4192 SourceLocation Loc, 4193 SourceRange ArgRange, 4194 UnaryExprOrTypeTrait TraitKind) { 4195 // Invalid types must be hard errors for SFINAE in C++. 4196 if (S.LangOpts.CPlusPlus) 4197 return true; 4198 4199 // C99 6.5.3.4p1: 4200 if (T->isFunctionType() && 4201 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 4202 TraitKind == UETT_PreferredAlignOf)) { 4203 // sizeof(function)/alignof(function) is allowed as an extension. 4204 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 4205 << getTraitSpelling(TraitKind) << ArgRange; 4206 return false; 4207 } 4208 4209 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 4210 // this is an error (OpenCL v1.1 s6.3.k) 4211 if (T->isVoidType()) { 4212 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 4213 : diag::ext_sizeof_alignof_void_type; 4214 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange; 4215 return false; 4216 } 4217 4218 return true; 4219 } 4220 4221 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 4222 SourceLocation Loc, 4223 SourceRange ArgRange, 4224 UnaryExprOrTypeTrait TraitKind) { 4225 // Reject sizeof(interface) and sizeof(interface<proto>) if the 4226 // runtime doesn't allow it. 4227 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 4228 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 4229 << T << (TraitKind == UETT_SizeOf) 4230 << ArgRange; 4231 return true; 4232 } 4233 4234 return false; 4235 } 4236 4237 /// Check whether E is a pointer from a decayed array type (the decayed 4238 /// pointer type is equal to T) and emit a warning if it is. 4239 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 4240 Expr *E) { 4241 // Don't warn if the operation changed the type. 4242 if (T != E->getType()) 4243 return; 4244 4245 // Now look for array decays. 4246 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 4247 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 4248 return; 4249 4250 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 4251 << ICE->getType() 4252 << ICE->getSubExpr()->getType(); 4253 } 4254 4255 /// Check the constraints on expression operands to unary type expression 4256 /// and type traits. 4257 /// 4258 /// Completes any types necessary and validates the constraints on the operand 4259 /// expression. The logic mostly mirrors the type-based overload, but may modify 4260 /// the expression as it completes the type for that expression through template 4261 /// instantiation, etc. 4262 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 4263 UnaryExprOrTypeTrait ExprKind) { 4264 QualType ExprTy = E->getType(); 4265 assert(!ExprTy->isReferenceType()); 4266 4267 bool IsUnevaluatedOperand = 4268 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 4269 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep); 4270 if (IsUnevaluatedOperand) { 4271 ExprResult Result = CheckUnevaluatedOperand(E); 4272 if (Result.isInvalid()) 4273 return true; 4274 E = Result.get(); 4275 } 4276 4277 // The operand for sizeof and alignof is in an unevaluated expression context, 4278 // so side effects could result in unintended consequences. 4279 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes 4280 // used to build SFINAE gadgets. 4281 // FIXME: Should we consider instantiation-dependent operands to 'alignof'? 4282 if (IsUnevaluatedOperand && !inTemplateInstantiation() && 4283 !E->isInstantiationDependent() && 4284 !E->getType()->isVariableArrayType() && 4285 E->HasSideEffects(Context, false)) 4286 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 4287 4288 if (ExprKind == UETT_VecStep) 4289 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 4290 E->getSourceRange()); 4291 4292 // Explicitly list some types as extensions. 4293 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 4294 E->getSourceRange(), ExprKind)) 4295 return false; 4296 4297 // 'alignof' applied to an expression only requires the base element type of 4298 // the expression to be complete. 'sizeof' requires the expression's type to 4299 // be complete (and will attempt to complete it if it's an array of unknown 4300 // bound). 4301 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4302 if (RequireCompleteSizedType( 4303 E->getExprLoc(), Context.getBaseElementType(E->getType()), 4304 diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4305 getTraitSpelling(ExprKind), E->getSourceRange())) 4306 return true; 4307 } else { 4308 if (RequireCompleteSizedExprType( 4309 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4310 getTraitSpelling(ExprKind), E->getSourceRange())) 4311 return true; 4312 } 4313 4314 // Completing the expression's type may have changed it. 4315 ExprTy = E->getType(); 4316 assert(!ExprTy->isReferenceType()); 4317 4318 if (ExprTy->isFunctionType()) { 4319 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 4320 << getTraitSpelling(ExprKind) << E->getSourceRange(); 4321 return true; 4322 } 4323 4324 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 4325 E->getSourceRange(), ExprKind)) 4326 return true; 4327 4328 if (ExprKind == UETT_SizeOf) { 4329 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 4330 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 4331 QualType OType = PVD->getOriginalType(); 4332 QualType Type = PVD->getType(); 4333 if (Type->isPointerType() && OType->isArrayType()) { 4334 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 4335 << Type << OType; 4336 Diag(PVD->getLocation(), diag::note_declared_at); 4337 } 4338 } 4339 } 4340 4341 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 4342 // decays into a pointer and returns an unintended result. This is most 4343 // likely a typo for "sizeof(array) op x". 4344 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 4345 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4346 BO->getLHS()); 4347 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 4348 BO->getRHS()); 4349 } 4350 } 4351 4352 return false; 4353 } 4354 4355 /// Check the constraints on operands to unary expression and type 4356 /// traits. 4357 /// 4358 /// This will complete any types necessary, and validate the various constraints 4359 /// on those operands. 4360 /// 4361 /// The UsualUnaryConversions() function is *not* called by this routine. 4362 /// C99 6.3.2.1p[2-4] all state: 4363 /// Except when it is the operand of the sizeof operator ... 4364 /// 4365 /// C++ [expr.sizeof]p4 4366 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 4367 /// standard conversions are not applied to the operand of sizeof. 4368 /// 4369 /// This policy is followed for all of the unary trait expressions. 4370 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 4371 SourceLocation OpLoc, 4372 SourceRange ExprRange, 4373 UnaryExprOrTypeTrait ExprKind) { 4374 if (ExprType->isDependentType()) 4375 return false; 4376 4377 // C++ [expr.sizeof]p2: 4378 // When applied to a reference or a reference type, the result 4379 // is the size of the referenced type. 4380 // C++11 [expr.alignof]p3: 4381 // When alignof is applied to a reference type, the result 4382 // shall be the alignment of the referenced type. 4383 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 4384 ExprType = Ref->getPointeeType(); 4385 4386 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 4387 // When alignof or _Alignof is applied to an array type, the result 4388 // is the alignment of the element type. 4389 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 4390 ExprKind == UETT_OpenMPRequiredSimdAlign) 4391 ExprType = Context.getBaseElementType(ExprType); 4392 4393 if (ExprKind == UETT_VecStep) 4394 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 4395 4396 // Explicitly list some types as extensions. 4397 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 4398 ExprKind)) 4399 return false; 4400 4401 if (RequireCompleteSizedType( 4402 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type, 4403 getTraitSpelling(ExprKind), ExprRange)) 4404 return true; 4405 4406 if (ExprType->isFunctionType()) { 4407 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 4408 << getTraitSpelling(ExprKind) << ExprRange; 4409 return true; 4410 } 4411 4412 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 4413 ExprKind)) 4414 return true; 4415 4416 return false; 4417 } 4418 4419 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 4420 // Cannot know anything else if the expression is dependent. 4421 if (E->isTypeDependent()) 4422 return false; 4423 4424 if (E->getObjectKind() == OK_BitField) { 4425 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 4426 << 1 << E->getSourceRange(); 4427 return true; 4428 } 4429 4430 ValueDecl *D = nullptr; 4431 Expr *Inner = E->IgnoreParens(); 4432 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) { 4433 D = DRE->getDecl(); 4434 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) { 4435 D = ME->getMemberDecl(); 4436 } 4437 4438 // If it's a field, require the containing struct to have a 4439 // complete definition so that we can compute the layout. 4440 // 4441 // This can happen in C++11 onwards, either by naming the member 4442 // in a way that is not transformed into a member access expression 4443 // (in an unevaluated operand, for instance), or by naming the member 4444 // in a trailing-return-type. 4445 // 4446 // For the record, since __alignof__ on expressions is a GCC 4447 // extension, GCC seems to permit this but always gives the 4448 // nonsensical answer 0. 4449 // 4450 // We don't really need the layout here --- we could instead just 4451 // directly check for all the appropriate alignment-lowing 4452 // attributes --- but that would require duplicating a lot of 4453 // logic that just isn't worth duplicating for such a marginal 4454 // use-case. 4455 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 4456 // Fast path this check, since we at least know the record has a 4457 // definition if we can find a member of it. 4458 if (!FD->getParent()->isCompleteDefinition()) { 4459 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 4460 << E->getSourceRange(); 4461 return true; 4462 } 4463 4464 // Otherwise, if it's a field, and the field doesn't have 4465 // reference type, then it must have a complete type (or be a 4466 // flexible array member, which we explicitly want to 4467 // white-list anyway), which makes the following checks trivial. 4468 if (!FD->getType()->isReferenceType()) 4469 return false; 4470 } 4471 4472 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 4473 } 4474 4475 bool Sema::CheckVecStepExpr(Expr *E) { 4476 E = E->IgnoreParens(); 4477 4478 // Cannot know anything else if the expression is dependent. 4479 if (E->isTypeDependent()) 4480 return false; 4481 4482 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 4483 } 4484 4485 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 4486 CapturingScopeInfo *CSI) { 4487 assert(T->isVariablyModifiedType()); 4488 assert(CSI != nullptr); 4489 4490 // We're going to walk down into the type and look for VLA expressions. 4491 do { 4492 const Type *Ty = T.getTypePtr(); 4493 switch (Ty->getTypeClass()) { 4494 #define TYPE(Class, Base) 4495 #define ABSTRACT_TYPE(Class, Base) 4496 #define NON_CANONICAL_TYPE(Class, Base) 4497 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 4498 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 4499 #include "clang/AST/TypeNodes.inc" 4500 T = QualType(); 4501 break; 4502 // These types are never variably-modified. 4503 case Type::Builtin: 4504 case Type::Complex: 4505 case Type::Vector: 4506 case Type::ExtVector: 4507 case Type::ConstantMatrix: 4508 case Type::Record: 4509 case Type::Enum: 4510 case Type::TemplateSpecialization: 4511 case Type::ObjCObject: 4512 case Type::ObjCInterface: 4513 case Type::ObjCObjectPointer: 4514 case Type::ObjCTypeParam: 4515 case Type::Pipe: 4516 case Type::BitInt: 4517 llvm_unreachable("type class is never variably-modified!"); 4518 case Type::Elaborated: 4519 T = cast<ElaboratedType>(Ty)->getNamedType(); 4520 break; 4521 case Type::Adjusted: 4522 T = cast<AdjustedType>(Ty)->getOriginalType(); 4523 break; 4524 case Type::Decayed: 4525 T = cast<DecayedType>(Ty)->getPointeeType(); 4526 break; 4527 case Type::Pointer: 4528 T = cast<PointerType>(Ty)->getPointeeType(); 4529 break; 4530 case Type::BlockPointer: 4531 T = cast<BlockPointerType>(Ty)->getPointeeType(); 4532 break; 4533 case Type::LValueReference: 4534 case Type::RValueReference: 4535 T = cast<ReferenceType>(Ty)->getPointeeType(); 4536 break; 4537 case Type::MemberPointer: 4538 T = cast<MemberPointerType>(Ty)->getPointeeType(); 4539 break; 4540 case Type::ConstantArray: 4541 case Type::IncompleteArray: 4542 // Losing element qualification here is fine. 4543 T = cast<ArrayType>(Ty)->getElementType(); 4544 break; 4545 case Type::VariableArray: { 4546 // Losing element qualification here is fine. 4547 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 4548 4549 // Unknown size indication requires no size computation. 4550 // Otherwise, evaluate and record it. 4551 auto Size = VAT->getSizeExpr(); 4552 if (Size && !CSI->isVLATypeCaptured(VAT) && 4553 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI))) 4554 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType()); 4555 4556 T = VAT->getElementType(); 4557 break; 4558 } 4559 case Type::FunctionProto: 4560 case Type::FunctionNoProto: 4561 T = cast<FunctionType>(Ty)->getReturnType(); 4562 break; 4563 case Type::Paren: 4564 case Type::TypeOf: 4565 case Type::UnaryTransform: 4566 case Type::Attributed: 4567 case Type::BTFTagAttributed: 4568 case Type::SubstTemplateTypeParm: 4569 case Type::MacroQualified: 4570 // Keep walking after single level desugaring. 4571 T = T.getSingleStepDesugaredType(Context); 4572 break; 4573 case Type::Typedef: 4574 T = cast<TypedefType>(Ty)->desugar(); 4575 break; 4576 case Type::Decltype: 4577 T = cast<DecltypeType>(Ty)->desugar(); 4578 break; 4579 case Type::Using: 4580 T = cast<UsingType>(Ty)->desugar(); 4581 break; 4582 case Type::Auto: 4583 case Type::DeducedTemplateSpecialization: 4584 T = cast<DeducedType>(Ty)->getDeducedType(); 4585 break; 4586 case Type::TypeOfExpr: 4587 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4588 break; 4589 case Type::Atomic: 4590 T = cast<AtomicType>(Ty)->getValueType(); 4591 break; 4592 } 4593 } while (!T.isNull() && T->isVariablyModifiedType()); 4594 } 4595 4596 /// Build a sizeof or alignof expression given a type operand. 4597 ExprResult 4598 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4599 SourceLocation OpLoc, 4600 UnaryExprOrTypeTrait ExprKind, 4601 SourceRange R) { 4602 if (!TInfo) 4603 return ExprError(); 4604 4605 QualType T = TInfo->getType(); 4606 4607 if (!T->isDependentType() && 4608 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4609 return ExprError(); 4610 4611 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4612 if (auto *TT = T->getAs<TypedefType>()) { 4613 for (auto I = FunctionScopes.rbegin(), 4614 E = std::prev(FunctionScopes.rend()); 4615 I != E; ++I) { 4616 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4617 if (CSI == nullptr) 4618 break; 4619 DeclContext *DC = nullptr; 4620 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4621 DC = LSI->CallOperator; 4622 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4623 DC = CRSI->TheCapturedDecl; 4624 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4625 DC = BSI->TheDecl; 4626 if (DC) { 4627 if (DC->containsDecl(TT->getDecl())) 4628 break; 4629 captureVariablyModifiedType(Context, T, CSI); 4630 } 4631 } 4632 } 4633 } 4634 4635 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4636 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf && 4637 TInfo->getType()->isVariablyModifiedType()) 4638 TInfo = TransformToPotentiallyEvaluated(TInfo); 4639 4640 return new (Context) UnaryExprOrTypeTraitExpr( 4641 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4642 } 4643 4644 /// Build a sizeof or alignof expression given an expression 4645 /// operand. 4646 ExprResult 4647 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4648 UnaryExprOrTypeTrait ExprKind) { 4649 ExprResult PE = CheckPlaceholderExpr(E); 4650 if (PE.isInvalid()) 4651 return ExprError(); 4652 4653 E = PE.get(); 4654 4655 // Verify that the operand is valid. 4656 bool isInvalid = false; 4657 if (E->isTypeDependent()) { 4658 // Delay type-checking for type-dependent expressions. 4659 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4660 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4661 } else if (ExprKind == UETT_VecStep) { 4662 isInvalid = CheckVecStepExpr(E); 4663 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4664 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4665 isInvalid = true; 4666 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4667 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4668 isInvalid = true; 4669 } else { 4670 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4671 } 4672 4673 if (isInvalid) 4674 return ExprError(); 4675 4676 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4677 PE = TransformToPotentiallyEvaluated(E); 4678 if (PE.isInvalid()) return ExprError(); 4679 E = PE.get(); 4680 } 4681 4682 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4683 return new (Context) UnaryExprOrTypeTraitExpr( 4684 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4685 } 4686 4687 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4688 /// expr and the same for @c alignof and @c __alignof 4689 /// Note that the ArgRange is invalid if isType is false. 4690 ExprResult 4691 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4692 UnaryExprOrTypeTrait ExprKind, bool IsType, 4693 void *TyOrEx, SourceRange ArgRange) { 4694 // If error parsing type, ignore. 4695 if (!TyOrEx) return ExprError(); 4696 4697 if (IsType) { 4698 TypeSourceInfo *TInfo; 4699 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4700 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4701 } 4702 4703 Expr *ArgEx = (Expr *)TyOrEx; 4704 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4705 return Result; 4706 } 4707 4708 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4709 bool IsReal) { 4710 if (V.get()->isTypeDependent()) 4711 return S.Context.DependentTy; 4712 4713 // _Real and _Imag are only l-values for normal l-values. 4714 if (V.get()->getObjectKind() != OK_Ordinary) { 4715 V = S.DefaultLvalueConversion(V.get()); 4716 if (V.isInvalid()) 4717 return QualType(); 4718 } 4719 4720 // These operators return the element type of a complex type. 4721 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4722 return CT->getElementType(); 4723 4724 // Otherwise they pass through real integer and floating point types here. 4725 if (V.get()->getType()->isArithmeticType()) 4726 return V.get()->getType(); 4727 4728 // Test for placeholders. 4729 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4730 if (PR.isInvalid()) return QualType(); 4731 if (PR.get() != V.get()) { 4732 V = PR; 4733 return CheckRealImagOperand(S, V, Loc, IsReal); 4734 } 4735 4736 // Reject anything else. 4737 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4738 << (IsReal ? "__real" : "__imag"); 4739 return QualType(); 4740 } 4741 4742 4743 4744 ExprResult 4745 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4746 tok::TokenKind Kind, Expr *Input) { 4747 UnaryOperatorKind Opc; 4748 switch (Kind) { 4749 default: llvm_unreachable("Unknown unary op!"); 4750 case tok::plusplus: Opc = UO_PostInc; break; 4751 case tok::minusminus: Opc = UO_PostDec; break; 4752 } 4753 4754 // Since this might is a postfix expression, get rid of ParenListExprs. 4755 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4756 if (Result.isInvalid()) return ExprError(); 4757 Input = Result.get(); 4758 4759 return BuildUnaryOp(S, OpLoc, Opc, Input); 4760 } 4761 4762 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4763 /// 4764 /// \return true on error 4765 static bool checkArithmeticOnObjCPointer(Sema &S, 4766 SourceLocation opLoc, 4767 Expr *op) { 4768 assert(op->getType()->isObjCObjectPointerType()); 4769 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4770 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4771 return false; 4772 4773 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4774 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4775 << op->getSourceRange(); 4776 return true; 4777 } 4778 4779 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4780 auto *BaseNoParens = Base->IgnoreParens(); 4781 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4782 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4783 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4784 } 4785 4786 // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent. 4787 // Typically this is DependentTy, but can sometimes be more precise. 4788 // 4789 // There are cases when we could determine a non-dependent type: 4790 // - LHS and RHS may have non-dependent types despite being type-dependent 4791 // (e.g. unbounded array static members of the current instantiation) 4792 // - one may be a dependent-sized array with known element type 4793 // - one may be a dependent-typed valid index (enum in current instantiation) 4794 // 4795 // We *always* return a dependent type, in such cases it is DependentTy. 4796 // This avoids creating type-dependent expressions with non-dependent types. 4797 // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275 4798 static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, 4799 const ASTContext &Ctx) { 4800 assert(LHS->isTypeDependent() || RHS->isTypeDependent()); 4801 QualType LTy = LHS->getType(), RTy = RHS->getType(); 4802 QualType Result = Ctx.DependentTy; 4803 if (RTy->isIntegralOrUnscopedEnumerationType()) { 4804 if (const PointerType *PT = LTy->getAs<PointerType>()) 4805 Result = PT->getPointeeType(); 4806 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe()) 4807 Result = AT->getElementType(); 4808 } else if (LTy->isIntegralOrUnscopedEnumerationType()) { 4809 if (const PointerType *PT = RTy->getAs<PointerType>()) 4810 Result = PT->getPointeeType(); 4811 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe()) 4812 Result = AT->getElementType(); 4813 } 4814 // Ensure we return a dependent type. 4815 return Result->isDependentType() ? Result : Ctx.DependentTy; 4816 } 4817 4818 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args); 4819 4820 ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, 4821 SourceLocation lbLoc, 4822 MultiExprArg ArgExprs, 4823 SourceLocation rbLoc) { 4824 4825 if (base && !base->getType().isNull() && 4826 base->hasPlaceholderType(BuiltinType::OMPArraySection)) 4827 return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(), 4828 SourceLocation(), /*Length*/ nullptr, 4829 /*Stride=*/nullptr, rbLoc); 4830 4831 // Since this might be a postfix expression, get rid of ParenListExprs. 4832 if (isa<ParenListExpr>(base)) { 4833 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4834 if (result.isInvalid()) 4835 return ExprError(); 4836 base = result.get(); 4837 } 4838 4839 // Check if base and idx form a MatrixSubscriptExpr. 4840 // 4841 // Helper to check for comma expressions, which are not allowed as indices for 4842 // matrix subscript expressions. 4843 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) { 4844 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) { 4845 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma) 4846 << SourceRange(base->getBeginLoc(), rbLoc); 4847 return true; 4848 } 4849 return false; 4850 }; 4851 // The matrix subscript operator ([][])is considered a single operator. 4852 // Separating the index expressions by parenthesis is not allowed. 4853 if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) && 4854 !isa<MatrixSubscriptExpr>(base)) { 4855 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index) 4856 << SourceRange(base->getBeginLoc(), rbLoc); 4857 return ExprError(); 4858 } 4859 // If the base is a MatrixSubscriptExpr, try to create a new 4860 // MatrixSubscriptExpr. 4861 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base); 4862 if (matSubscriptE) { 4863 assert(ArgExprs.size() == 1); 4864 if (CheckAndReportCommaError(ArgExprs.front())) 4865 return ExprError(); 4866 4867 assert(matSubscriptE->isIncomplete() && 4868 "base has to be an incomplete matrix subscript"); 4869 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(), 4870 matSubscriptE->getRowIdx(), 4871 ArgExprs.front(), rbLoc); 4872 } 4873 4874 // Handle any non-overload placeholder types in the base and index 4875 // expressions. We can't handle overloads here because the other 4876 // operand might be an overloadable type, in which case the overload 4877 // resolution for the operator overload should get the first crack 4878 // at the overload. 4879 bool IsMSPropertySubscript = false; 4880 if (base->getType()->isNonOverloadPlaceholderType()) { 4881 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4882 if (!IsMSPropertySubscript) { 4883 ExprResult result = CheckPlaceholderExpr(base); 4884 if (result.isInvalid()) 4885 return ExprError(); 4886 base = result.get(); 4887 } 4888 } 4889 4890 // If the base is a matrix type, try to create a new MatrixSubscriptExpr. 4891 if (base->getType()->isMatrixType()) { 4892 assert(ArgExprs.size() == 1); 4893 if (CheckAndReportCommaError(ArgExprs.front())) 4894 return ExprError(); 4895 4896 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr, 4897 rbLoc); 4898 } 4899 4900 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) { 4901 Expr *idx = ArgExprs[0]; 4902 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) || 4903 (isa<CXXOperatorCallExpr>(idx) && 4904 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) { 4905 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript) 4906 << SourceRange(base->getBeginLoc(), rbLoc); 4907 } 4908 } 4909 4910 if (ArgExprs.size() == 1 && 4911 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) { 4912 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]); 4913 if (result.isInvalid()) 4914 return ExprError(); 4915 ArgExprs[0] = result.get(); 4916 } else { 4917 if (checkArgsForPlaceholders(*this, ArgExprs)) 4918 return ExprError(); 4919 } 4920 4921 // Build an unanalyzed expression if either operand is type-dependent. 4922 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 && 4923 (base->isTypeDependent() || 4924 Expr::hasAnyTypeDependentArguments(ArgExprs))) { 4925 return new (Context) ArraySubscriptExpr( 4926 base, ArgExprs.front(), 4927 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()), 4928 VK_LValue, OK_Ordinary, rbLoc); 4929 } 4930 4931 // MSDN, property (C++) 4932 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4933 // This attribute can also be used in the declaration of an empty array in a 4934 // class or structure definition. For example: 4935 // __declspec(property(get=GetX, put=PutX)) int x[]; 4936 // The above statement indicates that x[] can be used with one or more array 4937 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4938 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4939 if (IsMSPropertySubscript) { 4940 assert(ArgExprs.size() == 1); 4941 // Build MS property subscript expression if base is MS property reference 4942 // or MS property subscript. 4943 return new (Context) 4944 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy, 4945 VK_LValue, OK_Ordinary, rbLoc); 4946 } 4947 4948 // Use C++ overloaded-operator rules if either operand has record 4949 // type. The spec says to do this if either type is *overloadable*, 4950 // but enum types can't declare subscript operators or conversion 4951 // operators, so there's nothing interesting for overload resolution 4952 // to do if there aren't any record types involved. 4953 // 4954 // ObjC pointers have their own subscripting logic that is not tied 4955 // to overload resolution and so should not take this path. 4956 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() && 4957 ((base->getType()->isRecordType() || 4958 (ArgExprs.size() != 1 || ArgExprs[0]->getType()->isRecordType())))) { 4959 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs); 4960 } 4961 4962 ExprResult Res = 4963 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc); 4964 4965 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get())) 4966 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get())); 4967 4968 return Res; 4969 } 4970 4971 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) { 4972 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 4973 InitializationKind Kind = 4974 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation()); 4975 InitializationSequence InitSeq(*this, Entity, Kind, E); 4976 return InitSeq.Perform(*this, Entity, Kind, E); 4977 } 4978 4979 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4980 Expr *ColumnIdx, 4981 SourceLocation RBLoc) { 4982 ExprResult BaseR = CheckPlaceholderExpr(Base); 4983 if (BaseR.isInvalid()) 4984 return BaseR; 4985 Base = BaseR.get(); 4986 4987 ExprResult RowR = CheckPlaceholderExpr(RowIdx); 4988 if (RowR.isInvalid()) 4989 return RowR; 4990 RowIdx = RowR.get(); 4991 4992 if (!ColumnIdx) 4993 return new (Context) MatrixSubscriptExpr( 4994 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc); 4995 4996 // Build an unanalyzed expression if any of the operands is type-dependent. 4997 if (Base->isTypeDependent() || RowIdx->isTypeDependent() || 4998 ColumnIdx->isTypeDependent()) 4999 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 5000 Context.DependentTy, RBLoc); 5001 5002 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx); 5003 if (ColumnR.isInvalid()) 5004 return ColumnR; 5005 ColumnIdx = ColumnR.get(); 5006 5007 // Check that IndexExpr is an integer expression. If it is a constant 5008 // expression, check that it is less than Dim (= the number of elements in the 5009 // corresponding dimension). 5010 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim, 5011 bool IsColumnIdx) -> Expr * { 5012 if (!IndexExpr->getType()->isIntegerType() && 5013 !IndexExpr->isTypeDependent()) { 5014 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer) 5015 << IsColumnIdx; 5016 return nullptr; 5017 } 5018 5019 if (std::optional<llvm::APSInt> Idx = 5020 IndexExpr->getIntegerConstantExpr(Context)) { 5021 if ((*Idx < 0 || *Idx >= Dim)) { 5022 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range) 5023 << IsColumnIdx << Dim; 5024 return nullptr; 5025 } 5026 } 5027 5028 ExprResult ConvExpr = 5029 tryConvertExprToType(IndexExpr, Context.getSizeType()); 5030 assert(!ConvExpr.isInvalid() && 5031 "should be able to convert any integer type to size type"); 5032 return ConvExpr.get(); 5033 }; 5034 5035 auto *MTy = Base->getType()->getAs<ConstantMatrixType>(); 5036 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false); 5037 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true); 5038 if (!RowIdx || !ColumnIdx) 5039 return ExprError(); 5040 5041 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx, 5042 MTy->getElementType(), RBLoc); 5043 } 5044 5045 void Sema::CheckAddressOfNoDeref(const Expr *E) { 5046 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 5047 const Expr *StrippedExpr = E->IgnoreParenImpCasts(); 5048 5049 // For expressions like `&(*s).b`, the base is recorded and what should be 5050 // checked. 5051 const MemberExpr *Member = nullptr; 5052 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow()) 5053 StrippedExpr = Member->getBase()->IgnoreParenImpCasts(); 5054 5055 LastRecord.PossibleDerefs.erase(StrippedExpr); 5056 } 5057 5058 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) { 5059 if (isUnevaluatedContext()) 5060 return; 5061 5062 QualType ResultTy = E->getType(); 5063 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back(); 5064 5065 // Bail if the element is an array since it is not memory access. 5066 if (isa<ArrayType>(ResultTy)) 5067 return; 5068 5069 if (ResultTy->hasAttr(attr::NoDeref)) { 5070 LastRecord.PossibleDerefs.insert(E); 5071 return; 5072 } 5073 5074 // Check if the base type is a pointer to a member access of a struct 5075 // marked with noderef. 5076 const Expr *Base = E->getBase(); 5077 QualType BaseTy = Base->getType(); 5078 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy))) 5079 // Not a pointer access 5080 return; 5081 5082 const MemberExpr *Member = nullptr; 5083 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) && 5084 Member->isArrow()) 5085 Base = Member->getBase(); 5086 5087 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) { 5088 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref)) 5089 LastRecord.PossibleDerefs.insert(E); 5090 } 5091 } 5092 5093 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 5094 Expr *LowerBound, 5095 SourceLocation ColonLocFirst, 5096 SourceLocation ColonLocSecond, 5097 Expr *Length, Expr *Stride, 5098 SourceLocation RBLoc) { 5099 if (Base->hasPlaceholderType() && 5100 !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) { 5101 ExprResult Result = CheckPlaceholderExpr(Base); 5102 if (Result.isInvalid()) 5103 return ExprError(); 5104 Base = Result.get(); 5105 } 5106 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 5107 ExprResult Result = CheckPlaceholderExpr(LowerBound); 5108 if (Result.isInvalid()) 5109 return ExprError(); 5110 Result = DefaultLvalueConversion(Result.get()); 5111 if (Result.isInvalid()) 5112 return ExprError(); 5113 LowerBound = Result.get(); 5114 } 5115 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 5116 ExprResult Result = CheckPlaceholderExpr(Length); 5117 if (Result.isInvalid()) 5118 return ExprError(); 5119 Result = DefaultLvalueConversion(Result.get()); 5120 if (Result.isInvalid()) 5121 return ExprError(); 5122 Length = Result.get(); 5123 } 5124 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) { 5125 ExprResult Result = CheckPlaceholderExpr(Stride); 5126 if (Result.isInvalid()) 5127 return ExprError(); 5128 Result = DefaultLvalueConversion(Result.get()); 5129 if (Result.isInvalid()) 5130 return ExprError(); 5131 Stride = Result.get(); 5132 } 5133 5134 // Build an unanalyzed expression if either operand is type-dependent. 5135 if (Base->isTypeDependent() || 5136 (LowerBound && 5137 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 5138 (Length && (Length->isTypeDependent() || Length->isValueDependent())) || 5139 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) { 5140 return new (Context) OMPArraySectionExpr( 5141 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue, 5142 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5143 } 5144 5145 // Perform default conversions. 5146 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 5147 QualType ResultTy; 5148 if (OriginalTy->isAnyPointerType()) { 5149 ResultTy = OriginalTy->getPointeeType(); 5150 } else if (OriginalTy->isArrayType()) { 5151 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 5152 } else { 5153 return ExprError( 5154 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 5155 << Base->getSourceRange()); 5156 } 5157 // C99 6.5.2.1p1 5158 if (LowerBound) { 5159 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 5160 LowerBound); 5161 if (Res.isInvalid()) 5162 return ExprError(Diag(LowerBound->getExprLoc(), 5163 diag::err_omp_typecheck_section_not_integer) 5164 << 0 << LowerBound->getSourceRange()); 5165 LowerBound = Res.get(); 5166 5167 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5168 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5169 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 5170 << 0 << LowerBound->getSourceRange(); 5171 } 5172 if (Length) { 5173 auto Res = 5174 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 5175 if (Res.isInvalid()) 5176 return ExprError(Diag(Length->getExprLoc(), 5177 diag::err_omp_typecheck_section_not_integer) 5178 << 1 << Length->getSourceRange()); 5179 Length = Res.get(); 5180 5181 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5182 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5183 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 5184 << 1 << Length->getSourceRange(); 5185 } 5186 if (Stride) { 5187 ExprResult Res = 5188 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride); 5189 if (Res.isInvalid()) 5190 return ExprError(Diag(Stride->getExprLoc(), 5191 diag::err_omp_typecheck_section_not_integer) 5192 << 1 << Stride->getSourceRange()); 5193 Stride = Res.get(); 5194 5195 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5196 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5197 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char) 5198 << 1 << Stride->getSourceRange(); 5199 } 5200 5201 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5202 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5203 // type. Note that functions are not objects, and that (in C99 parlance) 5204 // incomplete types are not object types. 5205 if (ResultTy->isFunctionType()) { 5206 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 5207 << ResultTy << Base->getSourceRange(); 5208 return ExprError(); 5209 } 5210 5211 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 5212 diag::err_omp_section_incomplete_type, Base)) 5213 return ExprError(); 5214 5215 if (LowerBound && !OriginalTy->isAnyPointerType()) { 5216 Expr::EvalResult Result; 5217 if (LowerBound->EvaluateAsInt(Result, Context)) { 5218 // OpenMP 5.0, [2.1.5 Array Sections] 5219 // The array section must be a subset of the original array. 5220 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 5221 if (LowerBoundValue.isNegative()) { 5222 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 5223 << LowerBound->getSourceRange(); 5224 return ExprError(); 5225 } 5226 } 5227 } 5228 5229 if (Length) { 5230 Expr::EvalResult Result; 5231 if (Length->EvaluateAsInt(Result, Context)) { 5232 // OpenMP 5.0, [2.1.5 Array Sections] 5233 // The length must evaluate to non-negative integers. 5234 llvm::APSInt LengthValue = Result.Val.getInt(); 5235 if (LengthValue.isNegative()) { 5236 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 5237 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true) 5238 << Length->getSourceRange(); 5239 return ExprError(); 5240 } 5241 } 5242 } else if (ColonLocFirst.isValid() && 5243 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 5244 !OriginalTy->isVariableArrayType()))) { 5245 // OpenMP 5.0, [2.1.5 Array Sections] 5246 // When the size of the array dimension is not known, the length must be 5247 // specified explicitly. 5248 Diag(ColonLocFirst, diag::err_omp_section_length_undefined) 5249 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 5250 return ExprError(); 5251 } 5252 5253 if (Stride) { 5254 Expr::EvalResult Result; 5255 if (Stride->EvaluateAsInt(Result, Context)) { 5256 // OpenMP 5.0, [2.1.5 Array Sections] 5257 // The stride must evaluate to a positive integer. 5258 llvm::APSInt StrideValue = Result.Val.getInt(); 5259 if (!StrideValue.isStrictlyPositive()) { 5260 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive) 5261 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true) 5262 << Stride->getSourceRange(); 5263 return ExprError(); 5264 } 5265 } 5266 } 5267 5268 if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) { 5269 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 5270 if (Result.isInvalid()) 5271 return ExprError(); 5272 Base = Result.get(); 5273 } 5274 return new (Context) OMPArraySectionExpr( 5275 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue, 5276 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc); 5277 } 5278 5279 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 5280 SourceLocation RParenLoc, 5281 ArrayRef<Expr *> Dims, 5282 ArrayRef<SourceRange> Brackets) { 5283 if (Base->hasPlaceholderType()) { 5284 ExprResult Result = CheckPlaceholderExpr(Base); 5285 if (Result.isInvalid()) 5286 return ExprError(); 5287 Result = DefaultLvalueConversion(Result.get()); 5288 if (Result.isInvalid()) 5289 return ExprError(); 5290 Base = Result.get(); 5291 } 5292 QualType BaseTy = Base->getType(); 5293 // Delay analysis of the types/expressions if instantiation/specialization is 5294 // required. 5295 if (!BaseTy->isPointerType() && Base->isTypeDependent()) 5296 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base, 5297 LParenLoc, RParenLoc, Dims, Brackets); 5298 if (!BaseTy->isPointerType() || 5299 (!Base->isTypeDependent() && 5300 BaseTy->getPointeeType()->isIncompleteType())) 5301 return ExprError(Diag(Base->getExprLoc(), 5302 diag::err_omp_non_pointer_type_array_shaping_base) 5303 << Base->getSourceRange()); 5304 5305 SmallVector<Expr *, 4> NewDims; 5306 bool ErrorFound = false; 5307 for (Expr *Dim : Dims) { 5308 if (Dim->hasPlaceholderType()) { 5309 ExprResult Result = CheckPlaceholderExpr(Dim); 5310 if (Result.isInvalid()) { 5311 ErrorFound = true; 5312 continue; 5313 } 5314 Result = DefaultLvalueConversion(Result.get()); 5315 if (Result.isInvalid()) { 5316 ErrorFound = true; 5317 continue; 5318 } 5319 Dim = Result.get(); 5320 } 5321 if (!Dim->isTypeDependent()) { 5322 ExprResult Result = 5323 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim); 5324 if (Result.isInvalid()) { 5325 ErrorFound = true; 5326 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer) 5327 << Dim->getSourceRange(); 5328 continue; 5329 } 5330 Dim = Result.get(); 5331 Expr::EvalResult EvResult; 5332 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) { 5333 // OpenMP 5.0, [2.1.4 Array Shaping] 5334 // Each si is an integral type expression that must evaluate to a 5335 // positive integer. 5336 llvm::APSInt Value = EvResult.Val.getInt(); 5337 if (!Value.isStrictlyPositive()) { 5338 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive) 5339 << toString(Value, /*Radix=*/10, /*Signed=*/true) 5340 << Dim->getSourceRange(); 5341 ErrorFound = true; 5342 continue; 5343 } 5344 } 5345 } 5346 NewDims.push_back(Dim); 5347 } 5348 if (ErrorFound) 5349 return ExprError(); 5350 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base, 5351 LParenLoc, RParenLoc, NewDims, Brackets); 5352 } 5353 5354 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 5355 SourceLocation LLoc, SourceLocation RLoc, 5356 ArrayRef<OMPIteratorData> Data) { 5357 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID; 5358 bool IsCorrect = true; 5359 for (const OMPIteratorData &D : Data) { 5360 TypeSourceInfo *TInfo = nullptr; 5361 SourceLocation StartLoc; 5362 QualType DeclTy; 5363 if (!D.Type.getAsOpaquePtr()) { 5364 // OpenMP 5.0, 2.1.6 Iterators 5365 // In an iterator-specifier, if the iterator-type is not specified then 5366 // the type of that iterator is of int type. 5367 DeclTy = Context.IntTy; 5368 StartLoc = D.DeclIdentLoc; 5369 } else { 5370 DeclTy = GetTypeFromParser(D.Type, &TInfo); 5371 StartLoc = TInfo->getTypeLoc().getBeginLoc(); 5372 } 5373 5374 bool IsDeclTyDependent = DeclTy->isDependentType() || 5375 DeclTy->containsUnexpandedParameterPack() || 5376 DeclTy->isInstantiationDependentType(); 5377 if (!IsDeclTyDependent) { 5378 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) { 5379 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5380 // The iterator-type must be an integral or pointer type. 5381 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5382 << DeclTy; 5383 IsCorrect = false; 5384 continue; 5385 } 5386 if (DeclTy.isConstant(Context)) { 5387 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++ 5388 // The iterator-type must not be const qualified. 5389 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer) 5390 << DeclTy; 5391 IsCorrect = false; 5392 continue; 5393 } 5394 } 5395 5396 // Iterator declaration. 5397 assert(D.DeclIdent && "Identifier expected."); 5398 // Always try to create iterator declarator to avoid extra error messages 5399 // about unknown declarations use. 5400 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc, 5401 D.DeclIdent, DeclTy, TInfo, SC_None); 5402 VD->setImplicit(); 5403 if (S) { 5404 // Check for conflicting previous declaration. 5405 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc); 5406 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5407 ForVisibleRedeclaration); 5408 Previous.suppressDiagnostics(); 5409 LookupName(Previous, S); 5410 5411 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false, 5412 /*AllowInlineNamespace=*/false); 5413 if (!Previous.empty()) { 5414 NamedDecl *Old = Previous.getRepresentativeDecl(); 5415 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName(); 5416 Diag(Old->getLocation(), diag::note_previous_definition); 5417 } else { 5418 PushOnScopeChains(VD, S); 5419 } 5420 } else { 5421 CurContext->addDecl(VD); 5422 } 5423 5424 /// Act on the iterator variable declaration. 5425 ActOnOpenMPIteratorVarDecl(VD); 5426 5427 Expr *Begin = D.Range.Begin; 5428 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) { 5429 ExprResult BeginRes = 5430 PerformImplicitConversion(Begin, DeclTy, AA_Converting); 5431 Begin = BeginRes.get(); 5432 } 5433 Expr *End = D.Range.End; 5434 if (!IsDeclTyDependent && End && !End->isTypeDependent()) { 5435 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting); 5436 End = EndRes.get(); 5437 } 5438 Expr *Step = D.Range.Step; 5439 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) { 5440 if (!Step->getType()->isIntegralType(Context)) { 5441 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral) 5442 << Step << Step->getSourceRange(); 5443 IsCorrect = false; 5444 continue; 5445 } 5446 std::optional<llvm::APSInt> Result = 5447 Step->getIntegerConstantExpr(Context); 5448 // OpenMP 5.0, 2.1.6 Iterators, Restrictions 5449 // If the step expression of a range-specification equals zero, the 5450 // behavior is unspecified. 5451 if (Result && Result->isZero()) { 5452 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero) 5453 << Step << Step->getSourceRange(); 5454 IsCorrect = false; 5455 continue; 5456 } 5457 } 5458 if (!Begin || !End || !IsCorrect) { 5459 IsCorrect = false; 5460 continue; 5461 } 5462 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back(); 5463 IDElem.IteratorDecl = VD; 5464 IDElem.AssignmentLoc = D.AssignLoc; 5465 IDElem.Range.Begin = Begin; 5466 IDElem.Range.End = End; 5467 IDElem.Range.Step = Step; 5468 IDElem.ColonLoc = D.ColonLoc; 5469 IDElem.SecondColonLoc = D.SecColonLoc; 5470 } 5471 if (!IsCorrect) { 5472 // Invalidate all created iterator declarations if error is found. 5473 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5474 if (Decl *ID = D.IteratorDecl) 5475 ID->setInvalidDecl(); 5476 } 5477 return ExprError(); 5478 } 5479 SmallVector<OMPIteratorHelperData, 4> Helpers; 5480 if (!CurContext->isDependentContext()) { 5481 // Build number of ityeration for each iteration range. 5482 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) : 5483 // ((Begini-Stepi-1-Endi) / -Stepi); 5484 for (OMPIteratorExpr::IteratorDefinition &D : ID) { 5485 // (Endi - Begini) 5486 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End, 5487 D.Range.Begin); 5488 if(!Res.isUsable()) { 5489 IsCorrect = false; 5490 continue; 5491 } 5492 ExprResult St, St1; 5493 if (D.Range.Step) { 5494 St = D.Range.Step; 5495 // (Endi - Begini) + Stepi 5496 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get()); 5497 if (!Res.isUsable()) { 5498 IsCorrect = false; 5499 continue; 5500 } 5501 // (Endi - Begini) + Stepi - 1 5502 Res = 5503 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(), 5504 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5505 if (!Res.isUsable()) { 5506 IsCorrect = false; 5507 continue; 5508 } 5509 // ((Endi - Begini) + Stepi - 1) / Stepi 5510 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get()); 5511 if (!Res.isUsable()) { 5512 IsCorrect = false; 5513 continue; 5514 } 5515 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step); 5516 // (Begini - Endi) 5517 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, 5518 D.Range.Begin, D.Range.End); 5519 if (!Res1.isUsable()) { 5520 IsCorrect = false; 5521 continue; 5522 } 5523 // (Begini - Endi) - Stepi 5524 Res1 = 5525 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get()); 5526 if (!Res1.isUsable()) { 5527 IsCorrect = false; 5528 continue; 5529 } 5530 // (Begini - Endi) - Stepi - 1 5531 Res1 = 5532 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(), 5533 ActOnIntegerConstant(D.AssignmentLoc, 1).get()); 5534 if (!Res1.isUsable()) { 5535 IsCorrect = false; 5536 continue; 5537 } 5538 // ((Begini - Endi) - Stepi - 1) / (-Stepi) 5539 Res1 = 5540 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get()); 5541 if (!Res1.isUsable()) { 5542 IsCorrect = false; 5543 continue; 5544 } 5545 // Stepi > 0. 5546 ExprResult CmpRes = 5547 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step, 5548 ActOnIntegerConstant(D.AssignmentLoc, 0).get()); 5549 if (!CmpRes.isUsable()) { 5550 IsCorrect = false; 5551 continue; 5552 } 5553 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(), 5554 Res.get(), Res1.get()); 5555 if (!Res.isUsable()) { 5556 IsCorrect = false; 5557 continue; 5558 } 5559 } 5560 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false); 5561 if (!Res.isUsable()) { 5562 IsCorrect = false; 5563 continue; 5564 } 5565 5566 // Build counter update. 5567 // Build counter. 5568 auto *CounterVD = 5569 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(), 5570 D.IteratorDecl->getBeginLoc(), nullptr, 5571 Res.get()->getType(), nullptr, SC_None); 5572 CounterVD->setImplicit(); 5573 ExprResult RefRes = 5574 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue, 5575 D.IteratorDecl->getBeginLoc()); 5576 // Build counter update. 5577 // I = Begini + counter * Stepi; 5578 ExprResult UpdateRes; 5579 if (D.Range.Step) { 5580 UpdateRes = CreateBuiltinBinOp( 5581 D.AssignmentLoc, BO_Mul, 5582 DefaultLvalueConversion(RefRes.get()).get(), St.get()); 5583 } else { 5584 UpdateRes = DefaultLvalueConversion(RefRes.get()); 5585 } 5586 if (!UpdateRes.isUsable()) { 5587 IsCorrect = false; 5588 continue; 5589 } 5590 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin, 5591 UpdateRes.get()); 5592 if (!UpdateRes.isUsable()) { 5593 IsCorrect = false; 5594 continue; 5595 } 5596 ExprResult VDRes = 5597 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl), 5598 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue, 5599 D.IteratorDecl->getBeginLoc()); 5600 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(), 5601 UpdateRes.get()); 5602 if (!UpdateRes.isUsable()) { 5603 IsCorrect = false; 5604 continue; 5605 } 5606 UpdateRes = 5607 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true); 5608 if (!UpdateRes.isUsable()) { 5609 IsCorrect = false; 5610 continue; 5611 } 5612 ExprResult CounterUpdateRes = 5613 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get()); 5614 if (!CounterUpdateRes.isUsable()) { 5615 IsCorrect = false; 5616 continue; 5617 } 5618 CounterUpdateRes = 5619 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true); 5620 if (!CounterUpdateRes.isUsable()) { 5621 IsCorrect = false; 5622 continue; 5623 } 5624 OMPIteratorHelperData &HD = Helpers.emplace_back(); 5625 HD.CounterVD = CounterVD; 5626 HD.Upper = Res.get(); 5627 HD.Update = UpdateRes.get(); 5628 HD.CounterUpdate = CounterUpdateRes.get(); 5629 } 5630 } else { 5631 Helpers.assign(ID.size(), {}); 5632 } 5633 if (!IsCorrect) { 5634 // Invalidate all created iterator declarations if error is found. 5635 for (const OMPIteratorExpr::IteratorDefinition &D : ID) { 5636 if (Decl *ID = D.IteratorDecl) 5637 ID->setInvalidDecl(); 5638 } 5639 return ExprError(); 5640 } 5641 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc, 5642 LLoc, RLoc, ID, Helpers); 5643 } 5644 5645 ExprResult 5646 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 5647 Expr *Idx, SourceLocation RLoc) { 5648 Expr *LHSExp = Base; 5649 Expr *RHSExp = Idx; 5650 5651 ExprValueKind VK = VK_LValue; 5652 ExprObjectKind OK = OK_Ordinary; 5653 5654 // Per C++ core issue 1213, the result is an xvalue if either operand is 5655 // a non-lvalue array, and an lvalue otherwise. 5656 if (getLangOpts().CPlusPlus11) { 5657 for (auto *Op : {LHSExp, RHSExp}) { 5658 Op = Op->IgnoreImplicit(); 5659 if (Op->getType()->isArrayType() && !Op->isLValue()) 5660 VK = VK_XValue; 5661 } 5662 } 5663 5664 // Perform default conversions. 5665 if (!LHSExp->getType()->getAs<VectorType>()) { 5666 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 5667 if (Result.isInvalid()) 5668 return ExprError(); 5669 LHSExp = Result.get(); 5670 } 5671 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 5672 if (Result.isInvalid()) 5673 return ExprError(); 5674 RHSExp = Result.get(); 5675 5676 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 5677 5678 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 5679 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 5680 // in the subscript position. As a result, we need to derive the array base 5681 // and index from the expression types. 5682 Expr *BaseExpr, *IndexExpr; 5683 QualType ResultType; 5684 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 5685 BaseExpr = LHSExp; 5686 IndexExpr = RHSExp; 5687 ResultType = 5688 getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext()); 5689 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 5690 BaseExpr = LHSExp; 5691 IndexExpr = RHSExp; 5692 ResultType = PTy->getPointeeType(); 5693 } else if (const ObjCObjectPointerType *PTy = 5694 LHSTy->getAs<ObjCObjectPointerType>()) { 5695 BaseExpr = LHSExp; 5696 IndexExpr = RHSExp; 5697 5698 // Use custom logic if this should be the pseudo-object subscript 5699 // expression. 5700 if (!LangOpts.isSubscriptPointerArithmetic()) 5701 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 5702 nullptr); 5703 5704 ResultType = PTy->getPointeeType(); 5705 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 5706 // Handle the uncommon case of "123[Ptr]". 5707 BaseExpr = RHSExp; 5708 IndexExpr = LHSExp; 5709 ResultType = PTy->getPointeeType(); 5710 } else if (const ObjCObjectPointerType *PTy = 5711 RHSTy->getAs<ObjCObjectPointerType>()) { 5712 // Handle the uncommon case of "123[Ptr]". 5713 BaseExpr = RHSExp; 5714 IndexExpr = LHSExp; 5715 ResultType = PTy->getPointeeType(); 5716 if (!LangOpts.isSubscriptPointerArithmetic()) { 5717 Diag(LLoc, diag::err_subscript_nonfragile_interface) 5718 << ResultType << BaseExpr->getSourceRange(); 5719 return ExprError(); 5720 } 5721 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 5722 BaseExpr = LHSExp; // vectors: V[123] 5723 IndexExpr = RHSExp; 5724 // We apply C++ DR1213 to vector subscripting too. 5725 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { 5726 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5727 if (Materialized.isInvalid()) 5728 return ExprError(); 5729 LHSExp = Materialized.get(); 5730 } 5731 VK = LHSExp->getValueKind(); 5732 if (VK != VK_PRValue) 5733 OK = OK_VectorComponent; 5734 5735 ResultType = VTy->getElementType(); 5736 QualType BaseType = BaseExpr->getType(); 5737 Qualifiers BaseQuals = BaseType.getQualifiers(); 5738 Qualifiers MemberQuals = ResultType.getQualifiers(); 5739 Qualifiers Combined = BaseQuals + MemberQuals; 5740 if (Combined != MemberQuals) 5741 ResultType = Context.getQualifiedType(ResultType, Combined); 5742 } else if (LHSTy->isBuiltinType() && 5743 LHSTy->getAs<BuiltinType>()->isVLSTBuiltinType()) { 5744 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>(); 5745 if (BTy->isSVEBool()) 5746 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t) 5747 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5748 5749 BaseExpr = LHSExp; 5750 IndexExpr = RHSExp; 5751 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) { 5752 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 5753 if (Materialized.isInvalid()) 5754 return ExprError(); 5755 LHSExp = Materialized.get(); 5756 } 5757 VK = LHSExp->getValueKind(); 5758 if (VK != VK_PRValue) 5759 OK = OK_VectorComponent; 5760 5761 ResultType = BTy->getSveEltType(Context); 5762 5763 QualType BaseType = BaseExpr->getType(); 5764 Qualifiers BaseQuals = BaseType.getQualifiers(); 5765 Qualifiers MemberQuals = ResultType.getQualifiers(); 5766 Qualifiers Combined = BaseQuals + MemberQuals; 5767 if (Combined != MemberQuals) 5768 ResultType = Context.getQualifiedType(ResultType, Combined); 5769 } else if (LHSTy->isArrayType()) { 5770 // If we see an array that wasn't promoted by 5771 // DefaultFunctionArrayLvalueConversion, it must be an array that 5772 // wasn't promoted because of the C90 rule that doesn't 5773 // allow promoting non-lvalue arrays. Warn, then 5774 // force the promotion here. 5775 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5776 << LHSExp->getSourceRange(); 5777 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 5778 CK_ArrayToPointerDecay).get(); 5779 LHSTy = LHSExp->getType(); 5780 5781 BaseExpr = LHSExp; 5782 IndexExpr = RHSExp; 5783 ResultType = LHSTy->castAs<PointerType>()->getPointeeType(); 5784 } else if (RHSTy->isArrayType()) { 5785 // Same as previous, except for 123[f().a] case 5786 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 5787 << RHSExp->getSourceRange(); 5788 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 5789 CK_ArrayToPointerDecay).get(); 5790 RHSTy = RHSExp->getType(); 5791 5792 BaseExpr = RHSExp; 5793 IndexExpr = LHSExp; 5794 ResultType = RHSTy->castAs<PointerType>()->getPointeeType(); 5795 } else { 5796 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 5797 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 5798 } 5799 // C99 6.5.2.1p1 5800 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 5801 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 5802 << IndexExpr->getSourceRange()); 5803 5804 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 5805 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 5806 && !IndexExpr->isTypeDependent()) 5807 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 5808 5809 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 5810 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 5811 // type. Note that Functions are not objects, and that (in C99 parlance) 5812 // incomplete types are not object types. 5813 if (ResultType->isFunctionType()) { 5814 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 5815 << ResultType << BaseExpr->getSourceRange(); 5816 return ExprError(); 5817 } 5818 5819 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 5820 // GNU extension: subscripting on pointer to void 5821 Diag(LLoc, diag::ext_gnu_subscript_void_type) 5822 << BaseExpr->getSourceRange(); 5823 5824 // C forbids expressions of unqualified void type from being l-values. 5825 // See IsCForbiddenLValueType. 5826 if (!ResultType.hasQualifiers()) 5827 VK = VK_PRValue; 5828 } else if (!ResultType->isDependentType() && 5829 RequireCompleteSizedType( 5830 LLoc, ResultType, 5831 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr)) 5832 return ExprError(); 5833 5834 assert(VK == VK_PRValue || LangOpts.CPlusPlus || 5835 !ResultType.isCForbiddenLValueType()); 5836 5837 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() && 5838 FunctionScopes.size() > 1) { 5839 if (auto *TT = 5840 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) { 5841 for (auto I = FunctionScopes.rbegin(), 5842 E = std::prev(FunctionScopes.rend()); 5843 I != E; ++I) { 5844 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 5845 if (CSI == nullptr) 5846 break; 5847 DeclContext *DC = nullptr; 5848 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 5849 DC = LSI->CallOperator; 5850 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 5851 DC = CRSI->TheCapturedDecl; 5852 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 5853 DC = BSI->TheDecl; 5854 if (DC) { 5855 if (DC->containsDecl(TT->getDecl())) 5856 break; 5857 captureVariablyModifiedType( 5858 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI); 5859 } 5860 } 5861 } 5862 } 5863 5864 return new (Context) 5865 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 5866 } 5867 5868 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5869 ParmVarDecl *Param, Expr *RewrittenInit, 5870 bool SkipImmediateInvocations) { 5871 if (Param->hasUnparsedDefaultArg()) { 5872 assert(!RewrittenInit && "Should not have a rewritten init expression yet"); 5873 // If we've already cleared out the location for the default argument, 5874 // that means we're parsing it right now. 5875 if (!UnparsedDefaultArgLocs.count(Param)) { 5876 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 5877 Diag(CallLoc, diag::note_recursive_default_argument_used_here); 5878 Param->setInvalidDecl(); 5879 return true; 5880 } 5881 5882 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later) 5883 << FD << cast<CXXRecordDecl>(FD->getDeclContext()); 5884 Diag(UnparsedDefaultArgLocs[Param], 5885 diag::note_default_argument_declared_here); 5886 return true; 5887 } 5888 5889 if (Param->hasUninstantiatedDefaultArg()) { 5890 assert(!RewrittenInit && "Should not have a rewitten init expression yet"); 5891 if (InstantiateDefaultArgument(CallLoc, FD, Param)) 5892 return true; 5893 } 5894 5895 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit(); 5896 assert(Init && "default argument but no initializer?"); 5897 5898 // If the default expression creates temporaries, we need to 5899 // push them to the current stack of expression temporaries so they'll 5900 // be properly destroyed. 5901 // FIXME: We should really be rebuilding the default argument with new 5902 // bound temporaries; see the comment in PR5810. 5903 // We don't need to do that with block decls, though, because 5904 // blocks in default argument expression can never capture anything. 5905 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) { 5906 // Set the "needs cleanups" bit regardless of whether there are 5907 // any explicit objects. 5908 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects()); 5909 // Append all the objects to the cleanup list. Right now, this 5910 // should always be a no-op, because blocks in default argument 5911 // expressions should never be able to capture anything. 5912 assert(!InitWithCleanup->getNumObjects() && 5913 "default argument expression has capturing blocks?"); 5914 } 5915 EnterExpressionEvaluationContext EvalContext( 5916 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 5917 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer = 5918 SkipImmediateInvocations; 5919 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables*/ true); 5920 return false; 5921 } 5922 5923 struct ImmediateCallVisitor : public RecursiveASTVisitor<ImmediateCallVisitor> { 5924 bool HasImmediateCalls = false; 5925 5926 bool shouldVisitImplicitCode() const { return true; } 5927 5928 bool VisitCallExpr(CallExpr *E) { 5929 if (const FunctionDecl *FD = E->getDirectCallee()) 5930 HasImmediateCalls |= FD->isConsteval(); 5931 return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E); 5932 } 5933 5934 // SourceLocExpr are not immediate invocations 5935 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr 5936 // need to be rebuilt so that they refer to the correct SourceLocation and 5937 // DeclContext. 5938 bool VisitSourceLocExpr(SourceLocExpr *E) { 5939 HasImmediateCalls = true; 5940 return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E); 5941 } 5942 5943 // A nested lambda might have parameters with immediate invocations 5944 // in their default arguments. 5945 // The compound statement is not visited (as it does not constitute a 5946 // subexpression). 5947 // FIXME: We should consider visiting and transforming captures 5948 // with init expressions. 5949 bool VisitLambdaExpr(LambdaExpr *E) { 5950 return VisitCXXMethodDecl(E->getCallOperator()); 5951 } 5952 5953 // Blocks don't support default parameters, and, as for lambdas, 5954 // we don't consider their body a subexpression. 5955 bool VisitBlockDecl(BlockDecl *B) { return false; } 5956 5957 bool VisitCompoundStmt(CompoundStmt *B) { return false; } 5958 5959 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 5960 return TraverseStmt(E->getExpr()); 5961 } 5962 5963 bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) { 5964 return TraverseStmt(E->getExpr()); 5965 } 5966 }; 5967 5968 struct EnsureImmediateInvocationInDefaultArgs 5969 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> { 5970 EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef) 5971 : TreeTransform(SemaRef) {} 5972 5973 // Lambda can only have immediate invocations in the default 5974 // args of their parameters, which is transformed upon calling the closure. 5975 // The body is not a subexpression, so we have nothing to do. 5976 // FIXME: Immediate calls in capture initializers should be transformed. 5977 ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; } 5978 ExprResult TransformBlockExpr(BlockExpr *E) { return E; } 5979 5980 // Make sure we don't rebuild the this pointer as it would 5981 // cause it to incorrectly point it to the outermost class 5982 // in the case of nested struct initialization. 5983 ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; } 5984 }; 5985 5986 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5987 FunctionDecl *FD, ParmVarDecl *Param, 5988 Expr *Init) { 5989 assert(Param->hasDefaultArg() && "can't build nonexistent default arg"); 5990 5991 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer(); 5992 5993 std::optional<ExpressionEvaluationContextRecord::InitializationContext> 5994 InitializationContext = 5995 OutermostDeclarationWithDelayedImmediateInvocations(); 5996 if (!InitializationContext.has_value()) 5997 InitializationContext.emplace(CallLoc, Param, CurContext); 5998 5999 if (!Init && !Param->hasUnparsedDefaultArg()) { 6000 // Mark that we are replacing a default argument first. 6001 // If we are instantiating a template we won't have to 6002 // retransform immediate calls. 6003 EnterExpressionEvaluationContext EvalContext( 6004 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 6005 6006 if (Param->hasUninstantiatedDefaultArg()) { 6007 if (InstantiateDefaultArgument(CallLoc, FD, Param)) 6008 return ExprError(); 6009 } 6010 // CWG2631 6011 // An immediate invocation that is not evaluated where it appears is 6012 // evaluated and checked for whether it is a constant expression at the 6013 // point where the enclosing initializer is used in a function call. 6014 ImmediateCallVisitor V; 6015 if (!NestedDefaultChecking) 6016 V.TraverseDecl(Param); 6017 if (V.HasImmediateCalls) { 6018 ExprEvalContexts.back().DelayedDefaultInitializationContext = { 6019 CallLoc, Param, CurContext}; 6020 EnsureImmediateInvocationInDefaultArgs Immediate(*this); 6021 ExprResult Res = Immediate.TransformInitializer(Param->getInit(), 6022 /*NotCopy=*/false); 6023 if (Res.isInvalid()) 6024 return ExprError(); 6025 Res = ConvertParamDefaultArgument(Param, Res.get(), 6026 Res.get()->getBeginLoc()); 6027 if (Res.isInvalid()) 6028 return ExprError(); 6029 Init = Res.get(); 6030 } 6031 } 6032 6033 if (CheckCXXDefaultArgExpr( 6034 CallLoc, FD, Param, Init, 6035 /*SkipImmediateInvocations=*/NestedDefaultChecking)) 6036 return ExprError(); 6037 6038 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param, 6039 Init, InitializationContext->Context); 6040 } 6041 6042 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 6043 assert(Field->hasInClassInitializer()); 6044 6045 // If we might have already tried and failed to instantiate, don't try again. 6046 if (Field->isInvalidDecl()) 6047 return ExprError(); 6048 6049 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 6050 6051 std::optional<ExpressionEvaluationContextRecord::InitializationContext> 6052 InitializationContext = 6053 OutermostDeclarationWithDelayedImmediateInvocations(); 6054 if (!InitializationContext.has_value()) 6055 InitializationContext.emplace(Loc, Field, CurContext); 6056 6057 Expr *Init = nullptr; 6058 6059 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer(); 6060 6061 EnterExpressionEvaluationContext EvalContext( 6062 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field); 6063 6064 if (!Field->getInClassInitializer()) { 6065 // Maybe we haven't instantiated the in-class initializer. Go check the 6066 // pattern FieldDecl to see if it has one. 6067 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 6068 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 6069 DeclContext::lookup_result Lookup = 6070 ClassPattern->lookup(Field->getDeclName()); 6071 6072 FieldDecl *Pattern = nullptr; 6073 for (auto *L : Lookup) { 6074 if ((Pattern = dyn_cast<FieldDecl>(L))) 6075 break; 6076 } 6077 assert(Pattern && "We must have set the Pattern!"); 6078 if (!Pattern->hasInClassInitializer() || 6079 InstantiateInClassInitializer(Loc, Field, Pattern, 6080 getTemplateInstantiationArgs(Field))) { 6081 Field->setInvalidDecl(); 6082 return ExprError(); 6083 } 6084 } 6085 } 6086 6087 // CWG2631 6088 // An immediate invocation that is not evaluated where it appears is 6089 // evaluated and checked for whether it is a constant expression at the 6090 // point where the enclosing initializer is used in a [...] a constructor 6091 // definition, or an aggregate initialization. 6092 ImmediateCallVisitor V; 6093 if (!NestedDefaultChecking) 6094 V.TraverseDecl(Field); 6095 if (V.HasImmediateCalls) { 6096 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field, 6097 CurContext}; 6098 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer = 6099 NestedDefaultChecking; 6100 6101 EnsureImmediateInvocationInDefaultArgs Immediate(*this); 6102 6103 ExprResult Res = 6104 Immediate.TransformInitializer(Field->getInClassInitializer(), 6105 /*CXXDirectInit=*/false); 6106 if (!Res.isInvalid()) 6107 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc); 6108 if (Res.isInvalid()) { 6109 Field->setInvalidDecl(); 6110 return ExprError(); 6111 } 6112 Init = Res.get(); 6113 } 6114 6115 if (Field->getInClassInitializer()) { 6116 Expr *E = Init ? Init : Field->getInClassInitializer(); 6117 if (!NestedDefaultChecking) 6118 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false); 6119 // C++11 [class.base.init]p7: 6120 // The initialization of each base and member constitutes a 6121 // full-expression. 6122 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false); 6123 if (Res.isInvalid()) { 6124 Field->setInvalidDecl(); 6125 return ExprError(); 6126 } 6127 Init = Res.get(); 6128 6129 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc, 6130 Field, InitializationContext->Context, 6131 Init); 6132 } 6133 6134 // DR1351: 6135 // If the brace-or-equal-initializer of a non-static data member 6136 // invokes a defaulted default constructor of its class or of an 6137 // enclosing class in a potentially evaluated subexpression, the 6138 // program is ill-formed. 6139 // 6140 // This resolution is unworkable: the exception specification of the 6141 // default constructor can be needed in an unevaluated context, in 6142 // particular, in the operand of a noexcept-expression, and we can be 6143 // unable to compute an exception specification for an enclosed class. 6144 // 6145 // Any attempt to resolve the exception specification of a defaulted default 6146 // constructor before the initializer is lexically complete will ultimately 6147 // come here at which point we can diagnose it. 6148 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 6149 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed) 6150 << OutermostClass << Field; 6151 Diag(Field->getEndLoc(), 6152 diag::note_default_member_initializer_not_yet_parsed); 6153 // Recover by marking the field invalid, unless we're in a SFINAE context. 6154 if (!isSFINAEContext()) 6155 Field->setInvalidDecl(); 6156 return ExprError(); 6157 } 6158 6159 Sema::VariadicCallType 6160 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 6161 Expr *Fn) { 6162 if (Proto && Proto->isVariadic()) { 6163 if (isa_and_nonnull<CXXConstructorDecl>(FDecl)) 6164 return VariadicConstructor; 6165 else if (Fn && Fn->getType()->isBlockPointerType()) 6166 return VariadicBlock; 6167 else if (FDecl) { 6168 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 6169 if (Method->isInstance()) 6170 return VariadicMethod; 6171 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 6172 return VariadicMethod; 6173 return VariadicFunction; 6174 } 6175 return VariadicDoesNotApply; 6176 } 6177 6178 namespace { 6179 class FunctionCallCCC final : public FunctionCallFilterCCC { 6180 public: 6181 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 6182 unsigned NumArgs, MemberExpr *ME) 6183 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 6184 FunctionName(FuncName) {} 6185 6186 bool ValidateCandidate(const TypoCorrection &candidate) override { 6187 if (!candidate.getCorrectionSpecifier() || 6188 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 6189 return false; 6190 } 6191 6192 return FunctionCallFilterCCC::ValidateCandidate(candidate); 6193 } 6194 6195 std::unique_ptr<CorrectionCandidateCallback> clone() override { 6196 return std::make_unique<FunctionCallCCC>(*this); 6197 } 6198 6199 private: 6200 const IdentifierInfo *const FunctionName; 6201 }; 6202 } 6203 6204 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 6205 FunctionDecl *FDecl, 6206 ArrayRef<Expr *> Args) { 6207 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 6208 DeclarationName FuncName = FDecl->getDeclName(); 6209 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 6210 6211 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 6212 if (TypoCorrection Corrected = S.CorrectTypo( 6213 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 6214 S.getScopeForContext(S.CurContext), nullptr, CCC, 6215 Sema::CTK_ErrorRecovery)) { 6216 if (NamedDecl *ND = Corrected.getFoundDecl()) { 6217 if (Corrected.isOverloaded()) { 6218 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 6219 OverloadCandidateSet::iterator Best; 6220 for (NamedDecl *CD : Corrected) { 6221 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 6222 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 6223 OCS); 6224 } 6225 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 6226 case OR_Success: 6227 ND = Best->FoundDecl; 6228 Corrected.setCorrectionDecl(ND); 6229 break; 6230 default: 6231 break; 6232 } 6233 } 6234 ND = ND->getUnderlyingDecl(); 6235 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 6236 return Corrected; 6237 } 6238 } 6239 return TypoCorrection(); 6240 } 6241 6242 /// ConvertArgumentsForCall - Converts the arguments specified in 6243 /// Args/NumArgs to the parameter types of the function FDecl with 6244 /// function prototype Proto. Call is the call expression itself, and 6245 /// Fn is the function expression. For a C++ member function, this 6246 /// routine does not attempt to convert the object argument. Returns 6247 /// true if the call is ill-formed. 6248 bool 6249 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 6250 FunctionDecl *FDecl, 6251 const FunctionProtoType *Proto, 6252 ArrayRef<Expr *> Args, 6253 SourceLocation RParenLoc, 6254 bool IsExecConfig) { 6255 // Bail out early if calling a builtin with custom typechecking. 6256 if (FDecl) 6257 if (unsigned ID = FDecl->getBuiltinID()) 6258 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 6259 return false; 6260 6261 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 6262 // assignment, to the types of the corresponding parameter, ... 6263 unsigned NumParams = Proto->getNumParams(); 6264 bool Invalid = false; 6265 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 6266 unsigned FnKind = Fn->getType()->isBlockPointerType() 6267 ? 1 /* block */ 6268 : (IsExecConfig ? 3 /* kernel function (exec config) */ 6269 : 0 /* function */); 6270 6271 // If too few arguments are available (and we don't have default 6272 // arguments for the remaining parameters), don't make the call. 6273 if (Args.size() < NumParams) { 6274 if (Args.size() < MinArgs) { 6275 TypoCorrection TC; 6276 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 6277 unsigned diag_id = 6278 MinArgs == NumParams && !Proto->isVariadic() 6279 ? diag::err_typecheck_call_too_few_args_suggest 6280 : diag::err_typecheck_call_too_few_args_at_least_suggest; 6281 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 6282 << static_cast<unsigned>(Args.size()) 6283 << TC.getCorrectionRange()); 6284 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 6285 Diag(RParenLoc, 6286 MinArgs == NumParams && !Proto->isVariadic() 6287 ? diag::err_typecheck_call_too_few_args_one 6288 : diag::err_typecheck_call_too_few_args_at_least_one) 6289 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 6290 else 6291 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 6292 ? diag::err_typecheck_call_too_few_args 6293 : diag::err_typecheck_call_too_few_args_at_least) 6294 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 6295 << Fn->getSourceRange(); 6296 6297 // Emit the location of the prototype. 6298 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 6299 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6300 6301 return true; 6302 } 6303 // We reserve space for the default arguments when we create 6304 // the call expression, before calling ConvertArgumentsForCall. 6305 assert((Call->getNumArgs() == NumParams) && 6306 "We should have reserved space for the default arguments before!"); 6307 } 6308 6309 // If too many are passed and not variadic, error on the extras and drop 6310 // them. 6311 if (Args.size() > NumParams) { 6312 if (!Proto->isVariadic()) { 6313 TypoCorrection TC; 6314 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 6315 unsigned diag_id = 6316 MinArgs == NumParams && !Proto->isVariadic() 6317 ? diag::err_typecheck_call_too_many_args_suggest 6318 : diag::err_typecheck_call_too_many_args_at_most_suggest; 6319 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 6320 << static_cast<unsigned>(Args.size()) 6321 << TC.getCorrectionRange()); 6322 } else if (NumParams == 1 && FDecl && 6323 FDecl->getParamDecl(0)->getDeclName()) 6324 Diag(Args[NumParams]->getBeginLoc(), 6325 MinArgs == NumParams 6326 ? diag::err_typecheck_call_too_many_args_one 6327 : diag::err_typecheck_call_too_many_args_at_most_one) 6328 << FnKind << FDecl->getParamDecl(0) 6329 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 6330 << SourceRange(Args[NumParams]->getBeginLoc(), 6331 Args.back()->getEndLoc()); 6332 else 6333 Diag(Args[NumParams]->getBeginLoc(), 6334 MinArgs == NumParams 6335 ? diag::err_typecheck_call_too_many_args 6336 : diag::err_typecheck_call_too_many_args_at_most) 6337 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 6338 << Fn->getSourceRange() 6339 << SourceRange(Args[NumParams]->getBeginLoc(), 6340 Args.back()->getEndLoc()); 6341 6342 // Emit the location of the prototype. 6343 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 6344 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 6345 6346 // This deletes the extra arguments. 6347 Call->shrinkNumArgs(NumParams); 6348 return true; 6349 } 6350 } 6351 SmallVector<Expr *, 8> AllArgs; 6352 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 6353 6354 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 6355 AllArgs, CallType); 6356 if (Invalid) 6357 return true; 6358 unsigned TotalNumArgs = AllArgs.size(); 6359 for (unsigned i = 0; i < TotalNumArgs; ++i) 6360 Call->setArg(i, AllArgs[i]); 6361 6362 Call->computeDependence(); 6363 return false; 6364 } 6365 6366 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 6367 const FunctionProtoType *Proto, 6368 unsigned FirstParam, ArrayRef<Expr *> Args, 6369 SmallVectorImpl<Expr *> &AllArgs, 6370 VariadicCallType CallType, bool AllowExplicit, 6371 bool IsListInitialization) { 6372 unsigned NumParams = Proto->getNumParams(); 6373 bool Invalid = false; 6374 size_t ArgIx = 0; 6375 // Continue to check argument types (even if we have too few/many args). 6376 for (unsigned i = FirstParam; i < NumParams; i++) { 6377 QualType ProtoArgType = Proto->getParamType(i); 6378 6379 Expr *Arg; 6380 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 6381 if (ArgIx < Args.size()) { 6382 Arg = Args[ArgIx++]; 6383 6384 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 6385 diag::err_call_incomplete_argument, Arg)) 6386 return true; 6387 6388 // Strip the unbridged-cast placeholder expression off, if applicable. 6389 bool CFAudited = false; 6390 if (Arg->getType() == Context.ARCUnbridgedCastTy && 6391 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 6392 (!Param || !Param->hasAttr<CFConsumedAttr>())) 6393 Arg = stripARCUnbridgedCast(Arg); 6394 else if (getLangOpts().ObjCAutoRefCount && 6395 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 6396 (!Param || !Param->hasAttr<CFConsumedAttr>())) 6397 CFAudited = true; 6398 6399 if (Proto->getExtParameterInfo(i).isNoEscape() && 6400 ProtoArgType->isBlockPointerType()) 6401 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 6402 BE->getBlockDecl()->setDoesNotEscape(); 6403 6404 InitializedEntity Entity = 6405 Param ? InitializedEntity::InitializeParameter(Context, Param, 6406 ProtoArgType) 6407 : InitializedEntity::InitializeParameter( 6408 Context, ProtoArgType, Proto->isParamConsumed(i)); 6409 6410 // Remember that parameter belongs to a CF audited API. 6411 if (CFAudited) 6412 Entity.setParameterCFAudited(); 6413 6414 ExprResult ArgE = PerformCopyInitialization( 6415 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 6416 if (ArgE.isInvalid()) 6417 return true; 6418 6419 Arg = ArgE.getAs<Expr>(); 6420 } else { 6421 assert(Param && "can't use default arguments without a known callee"); 6422 6423 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 6424 if (ArgExpr.isInvalid()) 6425 return true; 6426 6427 Arg = ArgExpr.getAs<Expr>(); 6428 } 6429 6430 // Check for array bounds violations for each argument to the call. This 6431 // check only triggers warnings when the argument isn't a more complex Expr 6432 // with its own checking, such as a BinaryOperator. 6433 CheckArrayAccess(Arg); 6434 6435 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 6436 CheckStaticArrayArgument(CallLoc, Param, Arg); 6437 6438 AllArgs.push_back(Arg); 6439 } 6440 6441 // If this is a variadic call, handle args passed through "...". 6442 if (CallType != VariadicDoesNotApply) { 6443 // Assume that extern "C" functions with variadic arguments that 6444 // return __unknown_anytype aren't *really* variadic. 6445 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 6446 FDecl->isExternC()) { 6447 for (Expr *A : Args.slice(ArgIx)) { 6448 QualType paramType; // ignored 6449 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 6450 Invalid |= arg.isInvalid(); 6451 AllArgs.push_back(arg.get()); 6452 } 6453 6454 // Otherwise do argument promotion, (C99 6.5.2.2p7). 6455 } else { 6456 for (Expr *A : Args.slice(ArgIx)) { 6457 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 6458 Invalid |= Arg.isInvalid(); 6459 AllArgs.push_back(Arg.get()); 6460 } 6461 } 6462 6463 // Check for array bounds violations. 6464 for (Expr *A : Args.slice(ArgIx)) 6465 CheckArrayAccess(A); 6466 } 6467 return Invalid; 6468 } 6469 6470 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 6471 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 6472 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 6473 TL = DTL.getOriginalLoc(); 6474 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 6475 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 6476 << ATL.getLocalSourceRange(); 6477 } 6478 6479 /// CheckStaticArrayArgument - If the given argument corresponds to a static 6480 /// array parameter, check that it is non-null, and that if it is formed by 6481 /// array-to-pointer decay, the underlying array is sufficiently large. 6482 /// 6483 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 6484 /// array type derivation, then for each call to the function, the value of the 6485 /// corresponding actual argument shall provide access to the first element of 6486 /// an array with at least as many elements as specified by the size expression. 6487 void 6488 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 6489 ParmVarDecl *Param, 6490 const Expr *ArgExpr) { 6491 // Static array parameters are not supported in C++. 6492 if (!Param || getLangOpts().CPlusPlus) 6493 return; 6494 6495 QualType OrigTy = Param->getOriginalType(); 6496 6497 const ArrayType *AT = Context.getAsArrayType(OrigTy); 6498 if (!AT || AT->getSizeModifier() != ArrayType::Static) 6499 return; 6500 6501 if (ArgExpr->isNullPointerConstant(Context, 6502 Expr::NPC_NeverValueDependent)) { 6503 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 6504 DiagnoseCalleeStaticArrayParam(*this, Param); 6505 return; 6506 } 6507 6508 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 6509 if (!CAT) 6510 return; 6511 6512 const ConstantArrayType *ArgCAT = 6513 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType()); 6514 if (!ArgCAT) 6515 return; 6516 6517 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(), 6518 ArgCAT->getElementType())) { 6519 if (ArgCAT->getSize().ult(CAT->getSize())) { 6520 Diag(CallLoc, diag::warn_static_array_too_small) 6521 << ArgExpr->getSourceRange() 6522 << (unsigned)ArgCAT->getSize().getZExtValue() 6523 << (unsigned)CAT->getSize().getZExtValue() << 0; 6524 DiagnoseCalleeStaticArrayParam(*this, Param); 6525 } 6526 return; 6527 } 6528 6529 std::optional<CharUnits> ArgSize = 6530 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT); 6531 std::optional<CharUnits> ParmSize = 6532 getASTContext().getTypeSizeInCharsIfKnown(CAT); 6533 if (ArgSize && ParmSize && *ArgSize < *ParmSize) { 6534 Diag(CallLoc, diag::warn_static_array_too_small) 6535 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity() 6536 << (unsigned)ParmSize->getQuantity() << 1; 6537 DiagnoseCalleeStaticArrayParam(*this, Param); 6538 } 6539 } 6540 6541 /// Given a function expression of unknown-any type, try to rebuild it 6542 /// to have a function type. 6543 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 6544 6545 /// Is the given type a placeholder that we need to lower out 6546 /// immediately during argument processing? 6547 static bool isPlaceholderToRemoveAsArg(QualType type) { 6548 // Placeholders are never sugared. 6549 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 6550 if (!placeholder) return false; 6551 6552 switch (placeholder->getKind()) { 6553 // Ignore all the non-placeholder types. 6554 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 6555 case BuiltinType::Id: 6556 #include "clang/Basic/OpenCLImageTypes.def" 6557 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 6558 case BuiltinType::Id: 6559 #include "clang/Basic/OpenCLExtensionTypes.def" 6560 // In practice we'll never use this, since all SVE types are sugared 6561 // via TypedefTypes rather than exposed directly as BuiltinTypes. 6562 #define SVE_TYPE(Name, Id, SingletonId) \ 6563 case BuiltinType::Id: 6564 #include "clang/Basic/AArch64SVEACLETypes.def" 6565 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 6566 case BuiltinType::Id: 6567 #include "clang/Basic/PPCTypes.def" 6568 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 6569 #include "clang/Basic/RISCVVTypes.def" 6570 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 6571 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 6572 #include "clang/AST/BuiltinTypes.def" 6573 return false; 6574 6575 // We cannot lower out overload sets; they might validly be resolved 6576 // by the call machinery. 6577 case BuiltinType::Overload: 6578 return false; 6579 6580 // Unbridged casts in ARC can be handled in some call positions and 6581 // should be left in place. 6582 case BuiltinType::ARCUnbridgedCast: 6583 return false; 6584 6585 // Pseudo-objects should be converted as soon as possible. 6586 case BuiltinType::PseudoObject: 6587 return true; 6588 6589 // The debugger mode could theoretically but currently does not try 6590 // to resolve unknown-typed arguments based on known parameter types. 6591 case BuiltinType::UnknownAny: 6592 return true; 6593 6594 // These are always invalid as call arguments and should be reported. 6595 case BuiltinType::BoundMember: 6596 case BuiltinType::BuiltinFn: 6597 case BuiltinType::IncompleteMatrixIdx: 6598 case BuiltinType::OMPArraySection: 6599 case BuiltinType::OMPArrayShaping: 6600 case BuiltinType::OMPIterator: 6601 return true; 6602 6603 } 6604 llvm_unreachable("bad builtin type kind"); 6605 } 6606 6607 /// Check an argument list for placeholders that we won't try to 6608 /// handle later. 6609 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 6610 // Apply this processing to all the arguments at once instead of 6611 // dying at the first failure. 6612 bool hasInvalid = false; 6613 for (size_t i = 0, e = args.size(); i != e; i++) { 6614 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 6615 ExprResult result = S.CheckPlaceholderExpr(args[i]); 6616 if (result.isInvalid()) hasInvalid = true; 6617 else args[i] = result.get(); 6618 } 6619 } 6620 return hasInvalid; 6621 } 6622 6623 /// If a builtin function has a pointer argument with no explicit address 6624 /// space, then it should be able to accept a pointer to any address 6625 /// space as input. In order to do this, we need to replace the 6626 /// standard builtin declaration with one that uses the same address space 6627 /// as the call. 6628 /// 6629 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 6630 /// it does not contain any pointer arguments without 6631 /// an address space qualifer. Otherwise the rewritten 6632 /// FunctionDecl is returned. 6633 /// TODO: Handle pointer return types. 6634 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 6635 FunctionDecl *FDecl, 6636 MultiExprArg ArgExprs) { 6637 6638 QualType DeclType = FDecl->getType(); 6639 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 6640 6641 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT || 6642 ArgExprs.size() < FT->getNumParams()) 6643 return nullptr; 6644 6645 bool NeedsNewDecl = false; 6646 unsigned i = 0; 6647 SmallVector<QualType, 8> OverloadParams; 6648 6649 for (QualType ParamType : FT->param_types()) { 6650 6651 // Convert array arguments to pointer to simplify type lookup. 6652 ExprResult ArgRes = 6653 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 6654 if (ArgRes.isInvalid()) 6655 return nullptr; 6656 Expr *Arg = ArgRes.get(); 6657 QualType ArgType = Arg->getType(); 6658 if (!ParamType->isPointerType() || 6659 ParamType.hasAddressSpace() || 6660 !ArgType->isPointerType() || 6661 !ArgType->getPointeeType().hasAddressSpace()) { 6662 OverloadParams.push_back(ParamType); 6663 continue; 6664 } 6665 6666 QualType PointeeType = ParamType->getPointeeType(); 6667 if (PointeeType.hasAddressSpace()) 6668 continue; 6669 6670 NeedsNewDecl = true; 6671 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 6672 6673 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 6674 OverloadParams.push_back(Context.getPointerType(PointeeType)); 6675 } 6676 6677 if (!NeedsNewDecl) 6678 return nullptr; 6679 6680 FunctionProtoType::ExtProtoInfo EPI; 6681 EPI.Variadic = FT->isVariadic(); 6682 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 6683 OverloadParams, EPI); 6684 DeclContext *Parent = FDecl->getParent(); 6685 FunctionDecl *OverloadDecl = FunctionDecl::Create( 6686 Context, Parent, FDecl->getLocation(), FDecl->getLocation(), 6687 FDecl->getIdentifier(), OverloadTy, 6688 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(), 6689 false, 6690 /*hasPrototype=*/true); 6691 SmallVector<ParmVarDecl*, 16> Params; 6692 FT = cast<FunctionProtoType>(OverloadTy); 6693 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 6694 QualType ParamType = FT->getParamType(i); 6695 ParmVarDecl *Parm = 6696 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 6697 SourceLocation(), nullptr, ParamType, 6698 /*TInfo=*/nullptr, SC_None, nullptr); 6699 Parm->setScopeInfo(0, i); 6700 Params.push_back(Parm); 6701 } 6702 OverloadDecl->setParams(Params); 6703 Sema->mergeDeclAttributes(OverloadDecl, FDecl); 6704 return OverloadDecl; 6705 } 6706 6707 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 6708 FunctionDecl *Callee, 6709 MultiExprArg ArgExprs) { 6710 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 6711 // similar attributes) really don't like it when functions are called with an 6712 // invalid number of args. 6713 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 6714 /*PartialOverloading=*/false) && 6715 !Callee->isVariadic()) 6716 return; 6717 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 6718 return; 6719 6720 if (const EnableIfAttr *Attr = 6721 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) { 6722 S.Diag(Fn->getBeginLoc(), 6723 isa<CXXMethodDecl>(Callee) 6724 ? diag::err_ovl_no_viable_member_function_in_call 6725 : diag::err_ovl_no_viable_function_in_call) 6726 << Callee << Callee->getSourceRange(); 6727 S.Diag(Callee->getLocation(), 6728 diag::note_ovl_candidate_disabled_by_function_cond_attr) 6729 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 6730 return; 6731 } 6732 } 6733 6734 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 6735 const UnresolvedMemberExpr *const UME, Sema &S) { 6736 6737 const auto GetFunctionLevelDCIfCXXClass = 6738 [](Sema &S) -> const CXXRecordDecl * { 6739 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 6740 if (!DC || !DC->getParent()) 6741 return nullptr; 6742 6743 // If the call to some member function was made from within a member 6744 // function body 'M' return return 'M's parent. 6745 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 6746 return MD->getParent()->getCanonicalDecl(); 6747 // else the call was made from within a default member initializer of a 6748 // class, so return the class. 6749 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 6750 return RD->getCanonicalDecl(); 6751 return nullptr; 6752 }; 6753 // If our DeclContext is neither a member function nor a class (in the 6754 // case of a lambda in a default member initializer), we can't have an 6755 // enclosing 'this'. 6756 6757 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 6758 if (!CurParentClass) 6759 return false; 6760 6761 // The naming class for implicit member functions call is the class in which 6762 // name lookup starts. 6763 const CXXRecordDecl *const NamingClass = 6764 UME->getNamingClass()->getCanonicalDecl(); 6765 assert(NamingClass && "Must have naming class even for implicit access"); 6766 6767 // If the unresolved member functions were found in a 'naming class' that is 6768 // related (either the same or derived from) to the class that contains the 6769 // member function that itself contained the implicit member access. 6770 6771 return CurParentClass == NamingClass || 6772 CurParentClass->isDerivedFrom(NamingClass); 6773 } 6774 6775 static void 6776 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6777 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 6778 6779 if (!UME) 6780 return; 6781 6782 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 6783 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 6784 // already been captured, or if this is an implicit member function call (if 6785 // it isn't, an attempt to capture 'this' should already have been made). 6786 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 6787 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 6788 return; 6789 6790 // Check if the naming class in which the unresolved members were found is 6791 // related (same as or is a base of) to the enclosing class. 6792 6793 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 6794 return; 6795 6796 6797 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 6798 // If the enclosing function is not dependent, then this lambda is 6799 // capture ready, so if we can capture this, do so. 6800 if (!EnclosingFunctionCtx->isDependentContext()) { 6801 // If the current lambda and all enclosing lambdas can capture 'this' - 6802 // then go ahead and capture 'this' (since our unresolved overload set 6803 // contains at least one non-static member function). 6804 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 6805 S.CheckCXXThisCapture(CallLoc); 6806 } else if (S.CurContext->isDependentContext()) { 6807 // ... since this is an implicit member reference, that might potentially 6808 // involve a 'this' capture, mark 'this' for potential capture in 6809 // enclosing lambdas. 6810 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 6811 CurLSI->addPotentialThisCapture(CallLoc); 6812 } 6813 } 6814 6815 // Once a call is fully resolved, warn for unqualified calls to specific 6816 // C++ standard functions, like move and forward. 6817 static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, CallExpr *Call) { 6818 // We are only checking unary move and forward so exit early here. 6819 if (Call->getNumArgs() != 1) 6820 return; 6821 6822 Expr *E = Call->getCallee()->IgnoreParenImpCasts(); 6823 if (!E || isa<UnresolvedLookupExpr>(E)) 6824 return; 6825 DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E); 6826 if (!DRE || !DRE->getLocation().isValid()) 6827 return; 6828 6829 if (DRE->getQualifier()) 6830 return; 6831 6832 const FunctionDecl *FD = Call->getDirectCallee(); 6833 if (!FD) 6834 return; 6835 6836 // Only warn for some functions deemed more frequent or problematic. 6837 unsigned BuiltinID = FD->getBuiltinID(); 6838 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward) 6839 return; 6840 6841 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function) 6842 << FD->getQualifiedNameAsString() 6843 << FixItHint::CreateInsertion(DRE->getLocation(), "std::"); 6844 } 6845 6846 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6847 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6848 Expr *ExecConfig) { 6849 ExprResult Call = 6850 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6851 /*IsExecConfig=*/false, /*AllowRecovery=*/true); 6852 if (Call.isInvalid()) 6853 return Call; 6854 6855 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier 6856 // language modes. 6857 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) { 6858 if (ULE->hasExplicitTemplateArgs() && 6859 ULE->decls_begin() == ULE->decls_end()) { 6860 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20 6861 ? diag::warn_cxx17_compat_adl_only_template_id 6862 : diag::ext_adl_only_template_id) 6863 << ULE->getName(); 6864 } 6865 } 6866 6867 if (LangOpts.OpenMP) 6868 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc, 6869 ExecConfig); 6870 if (LangOpts.CPlusPlus) { 6871 CallExpr *CE = dyn_cast<CallExpr>(Call.get()); 6872 if (CE) 6873 DiagnosedUnqualifiedCallsToStdFunctions(*this, CE); 6874 } 6875 return Call; 6876 } 6877 6878 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments. 6879 /// This provides the location of the left/right parens and a list of comma 6880 /// locations. 6881 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 6882 MultiExprArg ArgExprs, SourceLocation RParenLoc, 6883 Expr *ExecConfig, bool IsExecConfig, 6884 bool AllowRecovery) { 6885 // Since this might be a postfix expression, get rid of ParenListExprs. 6886 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 6887 if (Result.isInvalid()) return ExprError(); 6888 Fn = Result.get(); 6889 6890 if (checkArgsForPlaceholders(*this, ArgExprs)) 6891 return ExprError(); 6892 6893 if (getLangOpts().CPlusPlus) { 6894 // If this is a pseudo-destructor expression, build the call immediately. 6895 if (isa<CXXPseudoDestructorExpr>(Fn)) { 6896 if (!ArgExprs.empty()) { 6897 // Pseudo-destructor calls should not have any arguments. 6898 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 6899 << FixItHint::CreateRemoval( 6900 SourceRange(ArgExprs.front()->getBeginLoc(), 6901 ArgExprs.back()->getEndLoc())); 6902 } 6903 6904 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy, 6905 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6906 } 6907 if (Fn->getType() == Context.PseudoObjectTy) { 6908 ExprResult result = CheckPlaceholderExpr(Fn); 6909 if (result.isInvalid()) return ExprError(); 6910 Fn = result.get(); 6911 } 6912 6913 // Determine whether this is a dependent call inside a C++ template, 6914 // in which case we won't do any semantic analysis now. 6915 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 6916 if (ExecConfig) { 6917 return CUDAKernelCallExpr::Create(Context, Fn, 6918 cast<CallExpr>(ExecConfig), ArgExprs, 6919 Context.DependentTy, VK_PRValue, 6920 RParenLoc, CurFPFeatureOverrides()); 6921 } else { 6922 6923 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 6924 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 6925 Fn->getBeginLoc()); 6926 6927 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6928 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6929 } 6930 } 6931 6932 // Determine whether this is a call to an object (C++ [over.call.object]). 6933 if (Fn->getType()->isRecordType()) 6934 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 6935 RParenLoc); 6936 6937 if (Fn->getType() == Context.UnknownAnyTy) { 6938 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6939 if (result.isInvalid()) return ExprError(); 6940 Fn = result.get(); 6941 } 6942 6943 if (Fn->getType() == Context.BoundMemberTy) { 6944 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6945 RParenLoc, ExecConfig, IsExecConfig, 6946 AllowRecovery); 6947 } 6948 } 6949 6950 // Check for overloaded calls. This can happen even in C due to extensions. 6951 if (Fn->getType() == Context.OverloadTy) { 6952 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 6953 6954 // We aren't supposed to apply this logic if there's an '&' involved. 6955 if (!find.HasFormOfMemberPointer) { 6956 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 6957 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy, 6958 VK_PRValue, RParenLoc, CurFPFeatureOverrides()); 6959 OverloadExpr *ovl = find.Expression; 6960 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 6961 return BuildOverloadedCallExpr( 6962 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 6963 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 6964 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 6965 RParenLoc, ExecConfig, IsExecConfig, 6966 AllowRecovery); 6967 } 6968 } 6969 6970 // If we're directly calling a function, get the appropriate declaration. 6971 if (Fn->getType() == Context.UnknownAnyTy) { 6972 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 6973 if (result.isInvalid()) return ExprError(); 6974 Fn = result.get(); 6975 } 6976 6977 Expr *NakedFn = Fn->IgnoreParens(); 6978 6979 bool CallingNDeclIndirectly = false; 6980 NamedDecl *NDecl = nullptr; 6981 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 6982 if (UnOp->getOpcode() == UO_AddrOf) { 6983 CallingNDeclIndirectly = true; 6984 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 6985 } 6986 } 6987 6988 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 6989 NDecl = DRE->getDecl(); 6990 6991 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 6992 if (FDecl && FDecl->getBuiltinID()) { 6993 // Rewrite the function decl for this builtin by replacing parameters 6994 // with no explicit address space with the address space of the arguments 6995 // in ArgExprs. 6996 if ((FDecl = 6997 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 6998 NDecl = FDecl; 6999 Fn = DeclRefExpr::Create( 7000 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 7001 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl, 7002 nullptr, DRE->isNonOdrUse()); 7003 } 7004 } 7005 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn)) 7006 NDecl = ME->getMemberDecl(); 7007 7008 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 7009 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 7010 FD, /*Complain=*/true, Fn->getBeginLoc())) 7011 return ExprError(); 7012 7013 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 7014 7015 // If this expression is a call to a builtin function in HIP device 7016 // compilation, allow a pointer-type argument to default address space to be 7017 // passed as a pointer-type parameter to a non-default address space. 7018 // If Arg is declared in the default address space and Param is declared 7019 // in a non-default address space, perform an implicit address space cast to 7020 // the parameter type. 7021 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD && 7022 FD->getBuiltinID()) { 7023 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) { 7024 ParmVarDecl *Param = FD->getParamDecl(Idx); 7025 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() || 7026 !ArgExprs[Idx]->getType()->isPointerType()) 7027 continue; 7028 7029 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace(); 7030 auto ArgTy = ArgExprs[Idx]->getType(); 7031 auto ArgPtTy = ArgTy->getPointeeType(); 7032 auto ArgAS = ArgPtTy.getAddressSpace(); 7033 7034 // Add address space cast if target address spaces are different 7035 bool NeedImplicitASC = 7036 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling. 7037 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS 7038 // or from specific AS which has target AS matching that of Param. 7039 getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS)); 7040 if (!NeedImplicitASC) 7041 continue; 7042 7043 // First, ensure that the Arg is an RValue. 7044 if (ArgExprs[Idx]->isGLValue()) { 7045 ArgExprs[Idx] = ImplicitCastExpr::Create( 7046 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx], 7047 nullptr, VK_PRValue, FPOptionsOverride()); 7048 } 7049 7050 // Construct a new arg type with address space of Param 7051 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers(); 7052 ArgPtQuals.setAddressSpace(ParamAS); 7053 auto NewArgPtTy = 7054 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals); 7055 auto NewArgTy = 7056 Context.getQualifiedType(Context.getPointerType(NewArgPtTy), 7057 ArgTy.getQualifiers()); 7058 7059 // Finally perform an implicit address space cast 7060 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy, 7061 CK_AddressSpaceConversion) 7062 .get(); 7063 } 7064 } 7065 } 7066 7067 if (Context.isDependenceAllowed() && 7068 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) { 7069 assert(!getLangOpts().CPlusPlus); 7070 assert((Fn->containsErrors() || 7071 llvm::any_of(ArgExprs, 7072 [](clang::Expr *E) { return E->containsErrors(); })) && 7073 "should only occur in error-recovery path."); 7074 QualType ReturnType = 7075 llvm::isa_and_nonnull<FunctionDecl>(NDecl) 7076 ? cast<FunctionDecl>(NDecl)->getCallResultType() 7077 : Context.DependentTy; 7078 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType, 7079 Expr::getValueKindForType(ReturnType), RParenLoc, 7080 CurFPFeatureOverrides()); 7081 } 7082 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 7083 ExecConfig, IsExecConfig); 7084 } 7085 7086 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id 7087 // with the specified CallArgs 7088 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, 7089 MultiExprArg CallArgs) { 7090 StringRef Name = Context.BuiltinInfo.getName(Id); 7091 LookupResult R(*this, &Context.Idents.get(Name), Loc, 7092 Sema::LookupOrdinaryName); 7093 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true); 7094 7095 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>(); 7096 assert(BuiltInDecl && "failed to find builtin declaration"); 7097 7098 ExprResult DeclRef = 7099 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc); 7100 assert(DeclRef.isUsable() && "Builtin reference cannot fail"); 7101 7102 ExprResult Call = 7103 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc); 7104 7105 assert(!Call.isInvalid() && "Call to builtin cannot fail!"); 7106 return Call.get(); 7107 } 7108 7109 /// Parse a __builtin_astype expression. 7110 /// 7111 /// __builtin_astype( value, dst type ) 7112 /// 7113 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 7114 SourceLocation BuiltinLoc, 7115 SourceLocation RParenLoc) { 7116 QualType DstTy = GetTypeFromParser(ParsedDestTy); 7117 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc); 7118 } 7119 7120 /// Create a new AsTypeExpr node (bitcast) from the arguments. 7121 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy, 7122 SourceLocation BuiltinLoc, 7123 SourceLocation RParenLoc) { 7124 ExprValueKind VK = VK_PRValue; 7125 ExprObjectKind OK = OK_Ordinary; 7126 QualType SrcTy = E->getType(); 7127 if (!SrcTy->isDependentType() && 7128 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)) 7129 return ExprError( 7130 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size) 7131 << DestTy << SrcTy << E->getSourceRange()); 7132 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc); 7133 } 7134 7135 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 7136 /// provided arguments. 7137 /// 7138 /// __builtin_convertvector( value, dst type ) 7139 /// 7140 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 7141 SourceLocation BuiltinLoc, 7142 SourceLocation RParenLoc) { 7143 TypeSourceInfo *TInfo; 7144 GetTypeFromParser(ParsedDestTy, &TInfo); 7145 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 7146 } 7147 7148 /// BuildResolvedCallExpr - Build a call to a resolved expression, 7149 /// i.e. an expression not of \p OverloadTy. The expression should 7150 /// unary-convert to an expression of function-pointer or 7151 /// block-pointer type. 7152 /// 7153 /// \param NDecl the declaration being called, if available 7154 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 7155 SourceLocation LParenLoc, 7156 ArrayRef<Expr *> Args, 7157 SourceLocation RParenLoc, Expr *Config, 7158 bool IsExecConfig, ADLCallKind UsesADL) { 7159 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 7160 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 7161 7162 // Functions with 'interrupt' attribute cannot be called directly. 7163 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 7164 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 7165 return ExprError(); 7166 } 7167 7168 // Interrupt handlers don't save off the VFP regs automatically on ARM, 7169 // so there's some risk when calling out to non-interrupt handler functions 7170 // that the callee might not preserve them. This is easy to diagnose here, 7171 // but can be very challenging to debug. 7172 // Likewise, X86 interrupt handlers may only call routines with attribute 7173 // no_caller_saved_registers since there is no efficient way to 7174 // save and restore the non-GPR state. 7175 if (auto *Caller = getCurFunctionDecl()) { 7176 if (Caller->hasAttr<ARMInterruptAttr>()) { 7177 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 7178 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) { 7179 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 7180 if (FDecl) 7181 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 7182 } 7183 } 7184 if (Caller->hasAttr<AnyX86InterruptAttr>() && 7185 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) { 7186 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave); 7187 if (FDecl) 7188 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl; 7189 } 7190 } 7191 7192 // Promote the function operand. 7193 // We special-case function promotion here because we only allow promoting 7194 // builtin functions to function pointers in the callee of a call. 7195 ExprResult Result; 7196 QualType ResultTy; 7197 if (BuiltinID && 7198 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 7199 // Extract the return type from the (builtin) function pointer type. 7200 // FIXME Several builtins still have setType in 7201 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 7202 // Builtins.def to ensure they are correct before removing setType calls. 7203 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 7204 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 7205 ResultTy = FDecl->getCallResultType(); 7206 } else { 7207 Result = CallExprUnaryConversions(Fn); 7208 ResultTy = Context.BoolTy; 7209 } 7210 if (Result.isInvalid()) 7211 return ExprError(); 7212 Fn = Result.get(); 7213 7214 // Check for a valid function type, but only if it is not a builtin which 7215 // requires custom type checking. These will be handled by 7216 // CheckBuiltinFunctionCall below just after creation of the call expression. 7217 const FunctionType *FuncT = nullptr; 7218 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 7219 retry: 7220 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 7221 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 7222 // have type pointer to function". 7223 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 7224 if (!FuncT) 7225 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 7226 << Fn->getType() << Fn->getSourceRange()); 7227 } else if (const BlockPointerType *BPT = 7228 Fn->getType()->getAs<BlockPointerType>()) { 7229 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 7230 } else { 7231 // Handle calls to expressions of unknown-any type. 7232 if (Fn->getType() == Context.UnknownAnyTy) { 7233 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 7234 if (rewrite.isInvalid()) 7235 return ExprError(); 7236 Fn = rewrite.get(); 7237 goto retry; 7238 } 7239 7240 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 7241 << Fn->getType() << Fn->getSourceRange()); 7242 } 7243 } 7244 7245 // Get the number of parameters in the function prototype, if any. 7246 // We will allocate space for max(Args.size(), NumParams) arguments 7247 // in the call expression. 7248 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 7249 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 7250 7251 CallExpr *TheCall; 7252 if (Config) { 7253 assert(UsesADL == ADLCallKind::NotADL && 7254 "CUDAKernelCallExpr should not use ADL"); 7255 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), 7256 Args, ResultTy, VK_PRValue, RParenLoc, 7257 CurFPFeatureOverrides(), NumParams); 7258 } else { 7259 TheCall = 7260 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 7261 CurFPFeatureOverrides(), NumParams, UsesADL); 7262 } 7263 7264 if (!Context.isDependenceAllowed()) { 7265 // Forget about the nulled arguments since typo correction 7266 // do not handle them well. 7267 TheCall->shrinkNumArgs(Args.size()); 7268 // C cannot always handle TypoExpr nodes in builtin calls and direct 7269 // function calls as their argument checking don't necessarily handle 7270 // dependent types properly, so make sure any TypoExprs have been 7271 // dealt with. 7272 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 7273 if (!Result.isUsable()) return ExprError(); 7274 CallExpr *TheOldCall = TheCall; 7275 TheCall = dyn_cast<CallExpr>(Result.get()); 7276 bool CorrectedTypos = TheCall != TheOldCall; 7277 if (!TheCall) return Result; 7278 Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 7279 7280 // A new call expression node was created if some typos were corrected. 7281 // However it may not have been constructed with enough storage. In this 7282 // case, rebuild the node with enough storage. The waste of space is 7283 // immaterial since this only happens when some typos were corrected. 7284 if (CorrectedTypos && Args.size() < NumParams) { 7285 if (Config) 7286 TheCall = CUDAKernelCallExpr::Create( 7287 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue, 7288 RParenLoc, CurFPFeatureOverrides(), NumParams); 7289 else 7290 TheCall = 7291 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc, 7292 CurFPFeatureOverrides(), NumParams, UsesADL); 7293 } 7294 // We can now handle the nulled arguments for the default arguments. 7295 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams)); 7296 } 7297 7298 // Bail out early if calling a builtin with custom type checking. 7299 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 7300 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 7301 7302 if (getLangOpts().CUDA) { 7303 if (Config) { 7304 // CUDA: Kernel calls must be to global functions 7305 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 7306 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 7307 << FDecl << Fn->getSourceRange()); 7308 7309 // CUDA: Kernel function must have 'void' return type 7310 if (!FuncT->getReturnType()->isVoidType() && 7311 !FuncT->getReturnType()->getAs<AutoType>() && 7312 !FuncT->getReturnType()->isInstantiationDependentType()) 7313 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 7314 << Fn->getType() << Fn->getSourceRange()); 7315 } else { 7316 // CUDA: Calls to global functions must be configured 7317 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 7318 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 7319 << FDecl << Fn->getSourceRange()); 7320 } 7321 } 7322 7323 // Check for a valid return type 7324 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 7325 FDecl)) 7326 return ExprError(); 7327 7328 // We know the result type of the call, set it. 7329 TheCall->setType(FuncT->getCallResultType(Context)); 7330 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 7331 7332 if (Proto) { 7333 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 7334 IsExecConfig)) 7335 return ExprError(); 7336 } else { 7337 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 7338 7339 if (FDecl) { 7340 // Check if we have too few/too many template arguments, based 7341 // on our knowledge of the function definition. 7342 const FunctionDecl *Def = nullptr; 7343 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 7344 Proto = Def->getType()->getAs<FunctionProtoType>(); 7345 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 7346 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 7347 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 7348 } 7349 7350 // If the function we're calling isn't a function prototype, but we have 7351 // a function prototype from a prior declaratiom, use that prototype. 7352 if (!FDecl->hasPrototype()) 7353 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 7354 } 7355 7356 // If we still haven't found a prototype to use but there are arguments to 7357 // the call, diagnose this as calling a function without a prototype. 7358 // However, if we found a function declaration, check to see if 7359 // -Wdeprecated-non-prototype was disabled where the function was declared. 7360 // If so, we will silence the diagnostic here on the assumption that this 7361 // interface is intentional and the user knows what they're doing. We will 7362 // also silence the diagnostic if there is a function declaration but it 7363 // was implicitly defined (the user already gets diagnostics about the 7364 // creation of the implicit function declaration, so the additional warning 7365 // is not helpful). 7366 if (!Proto && !Args.empty() && 7367 (!FDecl || (!FDecl->isImplicit() && 7368 !Diags.isIgnored(diag::warn_strict_uses_without_prototype, 7369 FDecl->getLocation())))) 7370 Diag(LParenLoc, diag::warn_strict_uses_without_prototype) 7371 << (FDecl != nullptr) << FDecl; 7372 7373 // Promote the arguments (C99 6.5.2.2p6). 7374 for (unsigned i = 0, e = Args.size(); i != e; i++) { 7375 Expr *Arg = Args[i]; 7376 7377 if (Proto && i < Proto->getNumParams()) { 7378 InitializedEntity Entity = InitializedEntity::InitializeParameter( 7379 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 7380 ExprResult ArgE = 7381 PerformCopyInitialization(Entity, SourceLocation(), Arg); 7382 if (ArgE.isInvalid()) 7383 return true; 7384 7385 Arg = ArgE.getAs<Expr>(); 7386 7387 } else { 7388 ExprResult ArgE = DefaultArgumentPromotion(Arg); 7389 7390 if (ArgE.isInvalid()) 7391 return true; 7392 7393 Arg = ArgE.getAs<Expr>(); 7394 } 7395 7396 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 7397 diag::err_call_incomplete_argument, Arg)) 7398 return ExprError(); 7399 7400 TheCall->setArg(i, Arg); 7401 } 7402 TheCall->computeDependence(); 7403 } 7404 7405 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 7406 if (!Method->isStatic()) 7407 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 7408 << Fn->getSourceRange()); 7409 7410 // Check for sentinels 7411 if (NDecl) 7412 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 7413 7414 // Warn for unions passing across security boundary (CMSE). 7415 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) { 7416 for (unsigned i = 0, e = Args.size(); i != e; i++) { 7417 if (const auto *RT = 7418 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) { 7419 if (RT->getDecl()->isOrContainsUnion()) 7420 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union) 7421 << 0 << i; 7422 } 7423 } 7424 } 7425 7426 // Do special checking on direct calls to functions. 7427 if (FDecl) { 7428 if (CheckFunctionCall(FDecl, TheCall, Proto)) 7429 return ExprError(); 7430 7431 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall); 7432 7433 if (BuiltinID) 7434 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 7435 } else if (NDecl) { 7436 if (CheckPointerCall(NDecl, TheCall, Proto)) 7437 return ExprError(); 7438 } else { 7439 if (CheckOtherCall(TheCall, Proto)) 7440 return ExprError(); 7441 } 7442 7443 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl); 7444 } 7445 7446 ExprResult 7447 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 7448 SourceLocation RParenLoc, Expr *InitExpr) { 7449 assert(Ty && "ActOnCompoundLiteral(): missing type"); 7450 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 7451 7452 TypeSourceInfo *TInfo; 7453 QualType literalType = GetTypeFromParser(Ty, &TInfo); 7454 if (!TInfo) 7455 TInfo = Context.getTrivialTypeSourceInfo(literalType); 7456 7457 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 7458 } 7459 7460 ExprResult 7461 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 7462 SourceLocation RParenLoc, Expr *LiteralExpr) { 7463 QualType literalType = TInfo->getType(); 7464 7465 if (literalType->isArrayType()) { 7466 if (RequireCompleteSizedType( 7467 LParenLoc, Context.getBaseElementType(literalType), 7468 diag::err_array_incomplete_or_sizeless_type, 7469 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 7470 return ExprError(); 7471 if (literalType->isVariableArrayType()) { 7472 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc, 7473 diag::err_variable_object_no_init)) { 7474 return ExprError(); 7475 } 7476 } 7477 } else if (!literalType->isDependentType() && 7478 RequireCompleteType(LParenLoc, literalType, 7479 diag::err_typecheck_decl_incomplete_type, 7480 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 7481 return ExprError(); 7482 7483 InitializedEntity Entity 7484 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 7485 InitializationKind Kind 7486 = InitializationKind::CreateCStyleCast(LParenLoc, 7487 SourceRange(LParenLoc, RParenLoc), 7488 /*InitList=*/true); 7489 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 7490 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 7491 &literalType); 7492 if (Result.isInvalid()) 7493 return ExprError(); 7494 LiteralExpr = Result.get(); 7495 7496 bool isFileScope = !CurContext->isFunctionOrMethod(); 7497 7498 // In C, compound literals are l-values for some reason. 7499 // For GCC compatibility, in C++, file-scope array compound literals with 7500 // constant initializers are also l-values, and compound literals are 7501 // otherwise prvalues. 7502 // 7503 // (GCC also treats C++ list-initialized file-scope array prvalues with 7504 // constant initializers as l-values, but that's non-conforming, so we don't 7505 // follow it there.) 7506 // 7507 // FIXME: It would be better to handle the lvalue cases as materializing and 7508 // lifetime-extending a temporary object, but our materialized temporaries 7509 // representation only supports lifetime extension from a variable, not "out 7510 // of thin air". 7511 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 7512 // is bound to the result of applying array-to-pointer decay to the compound 7513 // literal. 7514 // FIXME: GCC supports compound literals of reference type, which should 7515 // obviously have a value kind derived from the kind of reference involved. 7516 ExprValueKind VK = 7517 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 7518 ? VK_PRValue 7519 : VK_LValue; 7520 7521 if (isFileScope) 7522 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 7523 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 7524 Expr *Init = ILE->getInit(i); 7525 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 7526 } 7527 7528 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 7529 VK, LiteralExpr, isFileScope); 7530 if (isFileScope) { 7531 if (!LiteralExpr->isTypeDependent() && 7532 !LiteralExpr->isValueDependent() && 7533 !literalType->isDependentType()) // C99 6.5.2.5p3 7534 if (CheckForConstantInitializer(LiteralExpr, literalType)) 7535 return ExprError(); 7536 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 7537 literalType.getAddressSpace() != LangAS::Default) { 7538 // Embedded-C extensions to C99 6.5.2.5: 7539 // "If the compound literal occurs inside the body of a function, the 7540 // type name shall not be qualified by an address-space qualifier." 7541 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 7542 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 7543 return ExprError(); 7544 } 7545 7546 if (!isFileScope && !getLangOpts().CPlusPlus) { 7547 // Compound literals that have automatic storage duration are destroyed at 7548 // the end of the scope in C; in C++, they're just temporaries. 7549 7550 // Emit diagnostics if it is or contains a C union type that is non-trivial 7551 // to destruct. 7552 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion()) 7553 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 7554 NTCUC_CompoundLiteral, NTCUK_Destruct); 7555 7556 // Diagnose jumps that enter or exit the lifetime of the compound literal. 7557 if (literalType.isDestructedType()) { 7558 Cleanup.setExprNeedsCleanups(true); 7559 ExprCleanupObjects.push_back(E); 7560 getCurFunction()->setHasBranchProtectedScope(); 7561 } 7562 } 7563 7564 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 7565 E->getType().hasNonTrivialToPrimitiveCopyCUnion()) 7566 checkNonTrivialCUnionInInitializer(E->getInitializer(), 7567 E->getInitializer()->getExprLoc()); 7568 7569 return MaybeBindToTemporary(E); 7570 } 7571 7572 ExprResult 7573 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7574 SourceLocation RBraceLoc) { 7575 // Only produce each kind of designated initialization diagnostic once. 7576 SourceLocation FirstDesignator; 7577 bool DiagnosedArrayDesignator = false; 7578 bool DiagnosedNestedDesignator = false; 7579 bool DiagnosedMixedDesignator = false; 7580 7581 // Check that any designated initializers are syntactically valid in the 7582 // current language mode. 7583 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7584 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) { 7585 if (FirstDesignator.isInvalid()) 7586 FirstDesignator = DIE->getBeginLoc(); 7587 7588 if (!getLangOpts().CPlusPlus) 7589 break; 7590 7591 if (!DiagnosedNestedDesignator && DIE->size() > 1) { 7592 DiagnosedNestedDesignator = true; 7593 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested) 7594 << DIE->getDesignatorsSourceRange(); 7595 } 7596 7597 for (auto &Desig : DIE->designators()) { 7598 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) { 7599 DiagnosedArrayDesignator = true; 7600 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array) 7601 << Desig.getSourceRange(); 7602 } 7603 } 7604 7605 if (!DiagnosedMixedDesignator && 7606 !isa<DesignatedInitExpr>(InitArgList[0])) { 7607 DiagnosedMixedDesignator = true; 7608 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7609 << DIE->getSourceRange(); 7610 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed) 7611 << InitArgList[0]->getSourceRange(); 7612 } 7613 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator && 7614 isa<DesignatedInitExpr>(InitArgList[0])) { 7615 DiagnosedMixedDesignator = true; 7616 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]); 7617 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed) 7618 << DIE->getSourceRange(); 7619 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed) 7620 << InitArgList[I]->getSourceRange(); 7621 } 7622 } 7623 7624 if (FirstDesignator.isValid()) { 7625 // Only diagnose designated initiaization as a C++20 extension if we didn't 7626 // already diagnose use of (non-C++20) C99 designator syntax. 7627 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator && 7628 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) { 7629 Diag(FirstDesignator, getLangOpts().CPlusPlus20 7630 ? diag::warn_cxx17_compat_designated_init 7631 : diag::ext_cxx_designated_init); 7632 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) { 7633 Diag(FirstDesignator, diag::ext_designated_init); 7634 } 7635 } 7636 7637 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc); 7638 } 7639 7640 ExprResult 7641 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 7642 SourceLocation RBraceLoc) { 7643 // Semantic analysis for initializers is done by ActOnDeclarator() and 7644 // CheckInitializer() - it requires knowledge of the object being initialized. 7645 7646 // Immediately handle non-overload placeholders. Overloads can be 7647 // resolved contextually, but everything else here can't. 7648 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 7649 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 7650 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 7651 7652 // Ignore failures; dropping the entire initializer list because 7653 // of one failure would be terrible for indexing/etc. 7654 if (result.isInvalid()) continue; 7655 7656 InitArgList[I] = result.get(); 7657 } 7658 } 7659 7660 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 7661 RBraceLoc); 7662 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 7663 return E; 7664 } 7665 7666 /// Do an explicit extend of the given block pointer if we're in ARC. 7667 void Sema::maybeExtendBlockObject(ExprResult &E) { 7668 assert(E.get()->getType()->isBlockPointerType()); 7669 assert(E.get()->isPRValue()); 7670 7671 // Only do this in an r-value context. 7672 if (!getLangOpts().ObjCAutoRefCount) return; 7673 7674 E = ImplicitCastExpr::Create( 7675 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(), 7676 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride()); 7677 Cleanup.setExprNeedsCleanups(true); 7678 } 7679 7680 /// Prepare a conversion of the given expression to an ObjC object 7681 /// pointer type. 7682 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 7683 QualType type = E.get()->getType(); 7684 if (type->isObjCObjectPointerType()) { 7685 return CK_BitCast; 7686 } else if (type->isBlockPointerType()) { 7687 maybeExtendBlockObject(E); 7688 return CK_BlockPointerToObjCPointerCast; 7689 } else { 7690 assert(type->isPointerType()); 7691 return CK_CPointerToObjCPointerCast; 7692 } 7693 } 7694 7695 /// Prepares for a scalar cast, performing all the necessary stages 7696 /// except the final cast and returning the kind required. 7697 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 7698 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 7699 // Also, callers should have filtered out the invalid cases with 7700 // pointers. Everything else should be possible. 7701 7702 QualType SrcTy = Src.get()->getType(); 7703 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 7704 return CK_NoOp; 7705 7706 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 7707 case Type::STK_MemberPointer: 7708 llvm_unreachable("member pointer type in C"); 7709 7710 case Type::STK_CPointer: 7711 case Type::STK_BlockPointer: 7712 case Type::STK_ObjCObjectPointer: 7713 switch (DestTy->getScalarTypeKind()) { 7714 case Type::STK_CPointer: { 7715 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 7716 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 7717 if (SrcAS != DestAS) 7718 return CK_AddressSpaceConversion; 7719 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 7720 return CK_NoOp; 7721 return CK_BitCast; 7722 } 7723 case Type::STK_BlockPointer: 7724 return (SrcKind == Type::STK_BlockPointer 7725 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 7726 case Type::STK_ObjCObjectPointer: 7727 if (SrcKind == Type::STK_ObjCObjectPointer) 7728 return CK_BitCast; 7729 if (SrcKind == Type::STK_CPointer) 7730 return CK_CPointerToObjCPointerCast; 7731 maybeExtendBlockObject(Src); 7732 return CK_BlockPointerToObjCPointerCast; 7733 case Type::STK_Bool: 7734 return CK_PointerToBoolean; 7735 case Type::STK_Integral: 7736 return CK_PointerToIntegral; 7737 case Type::STK_Floating: 7738 case Type::STK_FloatingComplex: 7739 case Type::STK_IntegralComplex: 7740 case Type::STK_MemberPointer: 7741 case Type::STK_FixedPoint: 7742 llvm_unreachable("illegal cast from pointer"); 7743 } 7744 llvm_unreachable("Should have returned before this"); 7745 7746 case Type::STK_FixedPoint: 7747 switch (DestTy->getScalarTypeKind()) { 7748 case Type::STK_FixedPoint: 7749 return CK_FixedPointCast; 7750 case Type::STK_Bool: 7751 return CK_FixedPointToBoolean; 7752 case Type::STK_Integral: 7753 return CK_FixedPointToIntegral; 7754 case Type::STK_Floating: 7755 return CK_FixedPointToFloating; 7756 case Type::STK_IntegralComplex: 7757 case Type::STK_FloatingComplex: 7758 Diag(Src.get()->getExprLoc(), 7759 diag::err_unimplemented_conversion_with_fixed_point_type) 7760 << DestTy; 7761 return CK_IntegralCast; 7762 case Type::STK_CPointer: 7763 case Type::STK_ObjCObjectPointer: 7764 case Type::STK_BlockPointer: 7765 case Type::STK_MemberPointer: 7766 llvm_unreachable("illegal cast to pointer type"); 7767 } 7768 llvm_unreachable("Should have returned before this"); 7769 7770 case Type::STK_Bool: // casting from bool is like casting from an integer 7771 case Type::STK_Integral: 7772 switch (DestTy->getScalarTypeKind()) { 7773 case Type::STK_CPointer: 7774 case Type::STK_ObjCObjectPointer: 7775 case Type::STK_BlockPointer: 7776 if (Src.get()->isNullPointerConstant(Context, 7777 Expr::NPC_ValueDependentIsNull)) 7778 return CK_NullToPointer; 7779 return CK_IntegralToPointer; 7780 case Type::STK_Bool: 7781 return CK_IntegralToBoolean; 7782 case Type::STK_Integral: 7783 return CK_IntegralCast; 7784 case Type::STK_Floating: 7785 return CK_IntegralToFloating; 7786 case Type::STK_IntegralComplex: 7787 Src = ImpCastExprToType(Src.get(), 7788 DestTy->castAs<ComplexType>()->getElementType(), 7789 CK_IntegralCast); 7790 return CK_IntegralRealToComplex; 7791 case Type::STK_FloatingComplex: 7792 Src = ImpCastExprToType(Src.get(), 7793 DestTy->castAs<ComplexType>()->getElementType(), 7794 CK_IntegralToFloating); 7795 return CK_FloatingRealToComplex; 7796 case Type::STK_MemberPointer: 7797 llvm_unreachable("member pointer type in C"); 7798 case Type::STK_FixedPoint: 7799 return CK_IntegralToFixedPoint; 7800 } 7801 llvm_unreachable("Should have returned before this"); 7802 7803 case Type::STK_Floating: 7804 switch (DestTy->getScalarTypeKind()) { 7805 case Type::STK_Floating: 7806 return CK_FloatingCast; 7807 case Type::STK_Bool: 7808 return CK_FloatingToBoolean; 7809 case Type::STK_Integral: 7810 return CK_FloatingToIntegral; 7811 case Type::STK_FloatingComplex: 7812 Src = ImpCastExprToType(Src.get(), 7813 DestTy->castAs<ComplexType>()->getElementType(), 7814 CK_FloatingCast); 7815 return CK_FloatingRealToComplex; 7816 case Type::STK_IntegralComplex: 7817 Src = ImpCastExprToType(Src.get(), 7818 DestTy->castAs<ComplexType>()->getElementType(), 7819 CK_FloatingToIntegral); 7820 return CK_IntegralRealToComplex; 7821 case Type::STK_CPointer: 7822 case Type::STK_ObjCObjectPointer: 7823 case Type::STK_BlockPointer: 7824 llvm_unreachable("valid float->pointer cast?"); 7825 case Type::STK_MemberPointer: 7826 llvm_unreachable("member pointer type in C"); 7827 case Type::STK_FixedPoint: 7828 return CK_FloatingToFixedPoint; 7829 } 7830 llvm_unreachable("Should have returned before this"); 7831 7832 case Type::STK_FloatingComplex: 7833 switch (DestTy->getScalarTypeKind()) { 7834 case Type::STK_FloatingComplex: 7835 return CK_FloatingComplexCast; 7836 case Type::STK_IntegralComplex: 7837 return CK_FloatingComplexToIntegralComplex; 7838 case Type::STK_Floating: { 7839 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7840 if (Context.hasSameType(ET, DestTy)) 7841 return CK_FloatingComplexToReal; 7842 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 7843 return CK_FloatingCast; 7844 } 7845 case Type::STK_Bool: 7846 return CK_FloatingComplexToBoolean; 7847 case Type::STK_Integral: 7848 Src = ImpCastExprToType(Src.get(), 7849 SrcTy->castAs<ComplexType>()->getElementType(), 7850 CK_FloatingComplexToReal); 7851 return CK_FloatingToIntegral; 7852 case Type::STK_CPointer: 7853 case Type::STK_ObjCObjectPointer: 7854 case Type::STK_BlockPointer: 7855 llvm_unreachable("valid complex float->pointer cast?"); 7856 case Type::STK_MemberPointer: 7857 llvm_unreachable("member pointer type in C"); 7858 case Type::STK_FixedPoint: 7859 Diag(Src.get()->getExprLoc(), 7860 diag::err_unimplemented_conversion_with_fixed_point_type) 7861 << SrcTy; 7862 return CK_IntegralCast; 7863 } 7864 llvm_unreachable("Should have returned before this"); 7865 7866 case Type::STK_IntegralComplex: 7867 switch (DestTy->getScalarTypeKind()) { 7868 case Type::STK_FloatingComplex: 7869 return CK_IntegralComplexToFloatingComplex; 7870 case Type::STK_IntegralComplex: 7871 return CK_IntegralComplexCast; 7872 case Type::STK_Integral: { 7873 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 7874 if (Context.hasSameType(ET, DestTy)) 7875 return CK_IntegralComplexToReal; 7876 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 7877 return CK_IntegralCast; 7878 } 7879 case Type::STK_Bool: 7880 return CK_IntegralComplexToBoolean; 7881 case Type::STK_Floating: 7882 Src = ImpCastExprToType(Src.get(), 7883 SrcTy->castAs<ComplexType>()->getElementType(), 7884 CK_IntegralComplexToReal); 7885 return CK_IntegralToFloating; 7886 case Type::STK_CPointer: 7887 case Type::STK_ObjCObjectPointer: 7888 case Type::STK_BlockPointer: 7889 llvm_unreachable("valid complex int->pointer cast?"); 7890 case Type::STK_MemberPointer: 7891 llvm_unreachable("member pointer type in C"); 7892 case Type::STK_FixedPoint: 7893 Diag(Src.get()->getExprLoc(), 7894 diag::err_unimplemented_conversion_with_fixed_point_type) 7895 << SrcTy; 7896 return CK_IntegralCast; 7897 } 7898 llvm_unreachable("Should have returned before this"); 7899 } 7900 7901 llvm_unreachable("Unhandled scalar cast"); 7902 } 7903 7904 static bool breakDownVectorType(QualType type, uint64_t &len, 7905 QualType &eltType) { 7906 // Vectors are simple. 7907 if (const VectorType *vecType = type->getAs<VectorType>()) { 7908 len = vecType->getNumElements(); 7909 eltType = vecType->getElementType(); 7910 assert(eltType->isScalarType()); 7911 return true; 7912 } 7913 7914 // We allow lax conversion to and from non-vector types, but only if 7915 // they're real types (i.e. non-complex, non-pointer scalar types). 7916 if (!type->isRealType()) return false; 7917 7918 len = 1; 7919 eltType = type; 7920 return true; 7921 } 7922 7923 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the 7924 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST) 7925 /// allowed? 7926 /// 7927 /// This will also return false if the two given types do not make sense from 7928 /// the perspective of SVE bitcasts. 7929 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) { 7930 assert(srcTy->isVectorType() || destTy->isVectorType()); 7931 7932 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) { 7933 if (!FirstType->isSizelessBuiltinType()) 7934 return false; 7935 7936 const auto *VecTy = SecondType->getAs<VectorType>(); 7937 return VecTy && 7938 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector; 7939 }; 7940 7941 return ValidScalableConversion(srcTy, destTy) || 7942 ValidScalableConversion(destTy, srcTy); 7943 } 7944 7945 /// Are the two types matrix types and do they have the same dimensions i.e. 7946 /// do they have the same number of rows and the same number of columns? 7947 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) { 7948 if (!destTy->isMatrixType() || !srcTy->isMatrixType()) 7949 return false; 7950 7951 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>(); 7952 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>(); 7953 7954 return matSrcType->getNumRows() == matDestType->getNumRows() && 7955 matSrcType->getNumColumns() == matDestType->getNumColumns(); 7956 } 7957 7958 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) { 7959 assert(DestTy->isVectorType() || SrcTy->isVectorType()); 7960 7961 uint64_t SrcLen, DestLen; 7962 QualType SrcEltTy, DestEltTy; 7963 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) 7964 return false; 7965 if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) 7966 return false; 7967 7968 // ASTContext::getTypeSize will return the size rounded up to a 7969 // power of 2, so instead of using that, we need to use the raw 7970 // element size multiplied by the element count. 7971 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy); 7972 uint64_t DestEltSize = Context.getTypeSize(DestEltTy); 7973 7974 return (SrcLen * SrcEltSize == DestLen * DestEltSize); 7975 } 7976 7977 // This returns true if at least one of the types is an altivec vector. 7978 bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) { 7979 assert((DestTy->isVectorType() || SrcTy->isVectorType()) && 7980 "expected at least one type to be a vector here"); 7981 7982 bool IsSrcTyAltivec = 7983 SrcTy->isVectorType() && (SrcTy->castAs<VectorType>()->getVectorKind() == 7984 VectorType::AltiVecVector); 7985 bool IsDestTyAltivec = DestTy->isVectorType() && 7986 (DestTy->castAs<VectorType>()->getVectorKind() == 7987 VectorType::AltiVecVector); 7988 7989 return (IsSrcTyAltivec || IsDestTyAltivec); 7990 } 7991 7992 // This returns true if both vectors have the same element type. 7993 bool Sema::areSameVectorElemTypes(QualType SrcTy, QualType DestTy) { 7994 assert((DestTy->isVectorType() || SrcTy->isVectorType()) && 7995 "expected at least one type to be a vector here"); 7996 7997 uint64_t SrcLen, DestLen; 7998 QualType SrcEltTy, DestEltTy; 7999 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy)) 8000 return false; 8001 if (!breakDownVectorType(DestTy, DestLen, DestEltTy)) 8002 return false; 8003 8004 return (SrcEltTy == DestEltTy); 8005 } 8006 8007 /// Are the two types lax-compatible vector types? That is, given 8008 /// that one of them is a vector, do they have equal storage sizes, 8009 /// where the storage size is the number of elements times the element 8010 /// size? 8011 /// 8012 /// This will also return false if either of the types is neither a 8013 /// vector nor a real type. 8014 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 8015 assert(destTy->isVectorType() || srcTy->isVectorType()); 8016 8017 // Disallow lax conversions between scalars and ExtVectors (these 8018 // conversions are allowed for other vector types because common headers 8019 // depend on them). Most scalar OP ExtVector cases are handled by the 8020 // splat path anyway, which does what we want (convert, not bitcast). 8021 // What this rules out for ExtVectors is crazy things like char4*float. 8022 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 8023 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 8024 8025 return areVectorTypesSameSize(srcTy, destTy); 8026 } 8027 8028 /// Is this a legal conversion between two types, one of which is 8029 /// known to be a vector type? 8030 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 8031 assert(destTy->isVectorType() || srcTy->isVectorType()); 8032 8033 switch (Context.getLangOpts().getLaxVectorConversions()) { 8034 case LangOptions::LaxVectorConversionKind::None: 8035 return false; 8036 8037 case LangOptions::LaxVectorConversionKind::Integer: 8038 if (!srcTy->isIntegralOrEnumerationType()) { 8039 auto *Vec = srcTy->getAs<VectorType>(); 8040 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 8041 return false; 8042 } 8043 if (!destTy->isIntegralOrEnumerationType()) { 8044 auto *Vec = destTy->getAs<VectorType>(); 8045 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType()) 8046 return false; 8047 } 8048 // OK, integer (vector) -> integer (vector) bitcast. 8049 break; 8050 8051 case LangOptions::LaxVectorConversionKind::All: 8052 break; 8053 } 8054 8055 return areLaxCompatibleVectorTypes(srcTy, destTy); 8056 } 8057 8058 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, 8059 CastKind &Kind) { 8060 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) { 8061 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) { 8062 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes) 8063 << DestTy << SrcTy << R; 8064 } 8065 } else if (SrcTy->isMatrixType()) { 8066 return Diag(R.getBegin(), 8067 diag::err_invalid_conversion_between_matrix_and_type) 8068 << SrcTy << DestTy << R; 8069 } else if (DestTy->isMatrixType()) { 8070 return Diag(R.getBegin(), 8071 diag::err_invalid_conversion_between_matrix_and_type) 8072 << DestTy << SrcTy << R; 8073 } 8074 8075 Kind = CK_MatrixCast; 8076 return false; 8077 } 8078 8079 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 8080 CastKind &Kind) { 8081 assert(VectorTy->isVectorType() && "Not a vector type!"); 8082 8083 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 8084 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 8085 return Diag(R.getBegin(), 8086 Ty->isVectorType() ? 8087 diag::err_invalid_conversion_between_vectors : 8088 diag::err_invalid_conversion_between_vector_and_integer) 8089 << VectorTy << Ty << R; 8090 } else 8091 return Diag(R.getBegin(), 8092 diag::err_invalid_conversion_between_vector_and_scalar) 8093 << VectorTy << Ty << R; 8094 8095 Kind = CK_BitCast; 8096 return false; 8097 } 8098 8099 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 8100 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 8101 8102 if (DestElemTy == SplattedExpr->getType()) 8103 return SplattedExpr; 8104 8105 assert(DestElemTy->isFloatingType() || 8106 DestElemTy->isIntegralOrEnumerationType()); 8107 8108 CastKind CK; 8109 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 8110 // OpenCL requires that we convert `true` boolean expressions to -1, but 8111 // only when splatting vectors. 8112 if (DestElemTy->isFloatingType()) { 8113 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 8114 // in two steps: boolean to signed integral, then to floating. 8115 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 8116 CK_BooleanToSignedIntegral); 8117 SplattedExpr = CastExprRes.get(); 8118 CK = CK_IntegralToFloating; 8119 } else { 8120 CK = CK_BooleanToSignedIntegral; 8121 } 8122 } else { 8123 ExprResult CastExprRes = SplattedExpr; 8124 CK = PrepareScalarCast(CastExprRes, DestElemTy); 8125 if (CastExprRes.isInvalid()) 8126 return ExprError(); 8127 SplattedExpr = CastExprRes.get(); 8128 } 8129 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 8130 } 8131 8132 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 8133 Expr *CastExpr, CastKind &Kind) { 8134 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 8135 8136 QualType SrcTy = CastExpr->getType(); 8137 8138 // If SrcTy is a VectorType, the total size must match to explicitly cast to 8139 // an ExtVectorType. 8140 // In OpenCL, casts between vectors of different types are not allowed. 8141 // (See OpenCL 6.2). 8142 if (SrcTy->isVectorType()) { 8143 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 8144 (getLangOpts().OpenCL && 8145 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 8146 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 8147 << DestTy << SrcTy << R; 8148 return ExprError(); 8149 } 8150 Kind = CK_BitCast; 8151 return CastExpr; 8152 } 8153 8154 // All non-pointer scalars can be cast to ExtVector type. The appropriate 8155 // conversion will take place first from scalar to elt type, and then 8156 // splat from elt type to vector. 8157 if (SrcTy->isPointerType()) 8158 return Diag(R.getBegin(), 8159 diag::err_invalid_conversion_between_vector_and_scalar) 8160 << DestTy << SrcTy << R; 8161 8162 Kind = CK_VectorSplat; 8163 return prepareVectorSplat(DestTy, CastExpr); 8164 } 8165 8166 ExprResult 8167 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 8168 Declarator &D, ParsedType &Ty, 8169 SourceLocation RParenLoc, Expr *CastExpr) { 8170 assert(!D.isInvalidType() && (CastExpr != nullptr) && 8171 "ActOnCastExpr(): missing type or expr"); 8172 8173 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 8174 if (D.isInvalidType()) 8175 return ExprError(); 8176 8177 if (getLangOpts().CPlusPlus) { 8178 // Check that there are no default arguments (C++ only). 8179 CheckExtraCXXDefaultArguments(D); 8180 } else { 8181 // Make sure any TypoExprs have been dealt with. 8182 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 8183 if (!Res.isUsable()) 8184 return ExprError(); 8185 CastExpr = Res.get(); 8186 } 8187 8188 checkUnusedDeclAttributes(D); 8189 8190 QualType castType = castTInfo->getType(); 8191 Ty = CreateParsedType(castType, castTInfo); 8192 8193 bool isVectorLiteral = false; 8194 8195 // Check for an altivec or OpenCL literal, 8196 // i.e. all the elements are integer constants. 8197 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 8198 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 8199 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 8200 && castType->isVectorType() && (PE || PLE)) { 8201 if (PLE && PLE->getNumExprs() == 0) { 8202 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 8203 return ExprError(); 8204 } 8205 if (PE || PLE->getNumExprs() == 1) { 8206 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 8207 if (!E->isTypeDependent() && !E->getType()->isVectorType()) 8208 isVectorLiteral = true; 8209 } 8210 else 8211 isVectorLiteral = true; 8212 } 8213 8214 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 8215 // then handle it as such. 8216 if (isVectorLiteral) 8217 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 8218 8219 // If the Expr being casted is a ParenListExpr, handle it specially. 8220 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 8221 // sequence of BinOp comma operators. 8222 if (isa<ParenListExpr>(CastExpr)) { 8223 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 8224 if (Result.isInvalid()) return ExprError(); 8225 CastExpr = Result.get(); 8226 } 8227 8228 if (getLangOpts().CPlusPlus && !castType->isVoidType()) 8229 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 8230 8231 CheckTollFreeBridgeCast(castType, CastExpr); 8232 8233 CheckObjCBridgeRelatedCast(castType, CastExpr); 8234 8235 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 8236 8237 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 8238 } 8239 8240 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 8241 SourceLocation RParenLoc, Expr *E, 8242 TypeSourceInfo *TInfo) { 8243 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 8244 "Expected paren or paren list expression"); 8245 8246 Expr **exprs; 8247 unsigned numExprs; 8248 Expr *subExpr; 8249 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 8250 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 8251 LiteralLParenLoc = PE->getLParenLoc(); 8252 LiteralRParenLoc = PE->getRParenLoc(); 8253 exprs = PE->getExprs(); 8254 numExprs = PE->getNumExprs(); 8255 } else { // isa<ParenExpr> by assertion at function entrance 8256 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 8257 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 8258 subExpr = cast<ParenExpr>(E)->getSubExpr(); 8259 exprs = &subExpr; 8260 numExprs = 1; 8261 } 8262 8263 QualType Ty = TInfo->getType(); 8264 assert(Ty->isVectorType() && "Expected vector type"); 8265 8266 SmallVector<Expr *, 8> initExprs; 8267 const VectorType *VTy = Ty->castAs<VectorType>(); 8268 unsigned numElems = VTy->getNumElements(); 8269 8270 // '(...)' form of vector initialization in AltiVec: the number of 8271 // initializers must be one or must match the size of the vector. 8272 // If a single value is specified in the initializer then it will be 8273 // replicated to all the components of the vector 8274 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty, 8275 VTy->getElementType())) 8276 return ExprError(); 8277 if (ShouldSplatAltivecScalarInCast(VTy)) { 8278 // The number of initializers must be one or must match the size of the 8279 // vector. If a single value is specified in the initializer then it will 8280 // be replicated to all the components of the vector 8281 if (numExprs == 1) { 8282 QualType ElemTy = VTy->getElementType(); 8283 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 8284 if (Literal.isInvalid()) 8285 return ExprError(); 8286 Literal = ImpCastExprToType(Literal.get(), ElemTy, 8287 PrepareScalarCast(Literal, ElemTy)); 8288 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 8289 } 8290 else if (numExprs < numElems) { 8291 Diag(E->getExprLoc(), 8292 diag::err_incorrect_number_of_vector_initializers); 8293 return ExprError(); 8294 } 8295 else 8296 initExprs.append(exprs, exprs + numExprs); 8297 } 8298 else { 8299 // For OpenCL, when the number of initializers is a single value, 8300 // it will be replicated to all components of the vector. 8301 if (getLangOpts().OpenCL && 8302 VTy->getVectorKind() == VectorType::GenericVector && 8303 numExprs == 1) { 8304 QualType ElemTy = VTy->getElementType(); 8305 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 8306 if (Literal.isInvalid()) 8307 return ExprError(); 8308 Literal = ImpCastExprToType(Literal.get(), ElemTy, 8309 PrepareScalarCast(Literal, ElemTy)); 8310 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 8311 } 8312 8313 initExprs.append(exprs, exprs + numExprs); 8314 } 8315 // FIXME: This means that pretty-printing the final AST will produce curly 8316 // braces instead of the original commas. 8317 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 8318 initExprs, LiteralRParenLoc); 8319 initE->setType(Ty); 8320 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 8321 } 8322 8323 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 8324 /// the ParenListExpr into a sequence of comma binary operators. 8325 ExprResult 8326 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 8327 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 8328 if (!E) 8329 return OrigExpr; 8330 8331 ExprResult Result(E->getExpr(0)); 8332 8333 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 8334 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 8335 E->getExpr(i)); 8336 8337 if (Result.isInvalid()) return ExprError(); 8338 8339 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 8340 } 8341 8342 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 8343 SourceLocation R, 8344 MultiExprArg Val) { 8345 return ParenListExpr::Create(Context, L, Val, R); 8346 } 8347 8348 /// Emit a specialized diagnostic when one expression is a null pointer 8349 /// constant and the other is not a pointer. Returns true if a diagnostic is 8350 /// emitted. 8351 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 8352 SourceLocation QuestionLoc) { 8353 Expr *NullExpr = LHSExpr; 8354 Expr *NonPointerExpr = RHSExpr; 8355 Expr::NullPointerConstantKind NullKind = 8356 NullExpr->isNullPointerConstant(Context, 8357 Expr::NPC_ValueDependentIsNotNull); 8358 8359 if (NullKind == Expr::NPCK_NotNull) { 8360 NullExpr = RHSExpr; 8361 NonPointerExpr = LHSExpr; 8362 NullKind = 8363 NullExpr->isNullPointerConstant(Context, 8364 Expr::NPC_ValueDependentIsNotNull); 8365 } 8366 8367 if (NullKind == Expr::NPCK_NotNull) 8368 return false; 8369 8370 if (NullKind == Expr::NPCK_ZeroExpression) 8371 return false; 8372 8373 if (NullKind == Expr::NPCK_ZeroLiteral) { 8374 // In this case, check to make sure that we got here from a "NULL" 8375 // string in the source code. 8376 NullExpr = NullExpr->IgnoreParenImpCasts(); 8377 SourceLocation loc = NullExpr->getExprLoc(); 8378 if (!findMacroSpelling(loc, "NULL")) 8379 return false; 8380 } 8381 8382 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 8383 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 8384 << NonPointerExpr->getType() << DiagType 8385 << NonPointerExpr->getSourceRange(); 8386 return true; 8387 } 8388 8389 /// Return false if the condition expression is valid, true otherwise. 8390 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 8391 QualType CondTy = Cond->getType(); 8392 8393 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 8394 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 8395 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8396 << CondTy << Cond->getSourceRange(); 8397 return true; 8398 } 8399 8400 // C99 6.5.15p2 8401 if (CondTy->isScalarType()) return false; 8402 8403 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 8404 << CondTy << Cond->getSourceRange(); 8405 return true; 8406 } 8407 8408 /// Return false if the NullExpr can be promoted to PointerTy, 8409 /// true otherwise. 8410 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 8411 QualType PointerTy) { 8412 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 8413 !NullExpr.get()->isNullPointerConstant(S.Context, 8414 Expr::NPC_ValueDependentIsNull)) 8415 return true; 8416 8417 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 8418 return false; 8419 } 8420 8421 /// Checks compatibility between two pointers and return the resulting 8422 /// type. 8423 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 8424 ExprResult &RHS, 8425 SourceLocation Loc) { 8426 QualType LHSTy = LHS.get()->getType(); 8427 QualType RHSTy = RHS.get()->getType(); 8428 8429 if (S.Context.hasSameType(LHSTy, RHSTy)) { 8430 // Two identical pointers types are always compatible. 8431 return S.Context.getCommonSugaredType(LHSTy, RHSTy); 8432 } 8433 8434 QualType lhptee, rhptee; 8435 8436 // Get the pointee types. 8437 bool IsBlockPointer = false; 8438 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 8439 lhptee = LHSBTy->getPointeeType(); 8440 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 8441 IsBlockPointer = true; 8442 } else { 8443 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8444 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8445 } 8446 8447 // C99 6.5.15p6: If both operands are pointers to compatible types or to 8448 // differently qualified versions of compatible types, the result type is 8449 // a pointer to an appropriately qualified version of the composite 8450 // type. 8451 8452 // Only CVR-qualifiers exist in the standard, and the differently-qualified 8453 // clause doesn't make sense for our extensions. E.g. address space 2 should 8454 // be incompatible with address space 3: they may live on different devices or 8455 // anything. 8456 Qualifiers lhQual = lhptee.getQualifiers(); 8457 Qualifiers rhQual = rhptee.getQualifiers(); 8458 8459 LangAS ResultAddrSpace = LangAS::Default; 8460 LangAS LAddrSpace = lhQual.getAddressSpace(); 8461 LangAS RAddrSpace = rhQual.getAddressSpace(); 8462 8463 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 8464 // spaces is disallowed. 8465 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 8466 ResultAddrSpace = LAddrSpace; 8467 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 8468 ResultAddrSpace = RAddrSpace; 8469 else { 8470 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8471 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 8472 << RHS.get()->getSourceRange(); 8473 return QualType(); 8474 } 8475 8476 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 8477 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 8478 lhQual.removeCVRQualifiers(); 8479 rhQual.removeCVRQualifiers(); 8480 8481 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 8482 // (C99 6.7.3) for address spaces. We assume that the check should behave in 8483 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 8484 // qual types are compatible iff 8485 // * corresponded types are compatible 8486 // * CVR qualifiers are equal 8487 // * address spaces are equal 8488 // Thus for conditional operator we merge CVR and address space unqualified 8489 // pointees and if there is a composite type we return a pointer to it with 8490 // merged qualifiers. 8491 LHSCastKind = 8492 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 8493 RHSCastKind = 8494 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 8495 lhQual.removeAddressSpace(); 8496 rhQual.removeAddressSpace(); 8497 8498 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 8499 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 8500 8501 QualType CompositeTy = S.Context.mergeTypes( 8502 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false, 8503 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true); 8504 8505 if (CompositeTy.isNull()) { 8506 // In this situation, we assume void* type. No especially good 8507 // reason, but this is what gcc does, and we do have to pick 8508 // to get a consistent AST. 8509 QualType incompatTy; 8510 incompatTy = S.Context.getPointerType( 8511 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 8512 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 8513 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 8514 8515 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 8516 // for casts between types with incompatible address space qualifiers. 8517 // For the following code the compiler produces casts between global and 8518 // local address spaces of the corresponded innermost pointees: 8519 // local int *global *a; 8520 // global int *global *b; 8521 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 8522 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 8523 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8524 << RHS.get()->getSourceRange(); 8525 8526 return incompatTy; 8527 } 8528 8529 // The pointer types are compatible. 8530 // In case of OpenCL ResultTy should have the address space qualifier 8531 // which is a superset of address spaces of both the 2nd and the 3rd 8532 // operands of the conditional operator. 8533 QualType ResultTy = [&, ResultAddrSpace]() { 8534 if (S.getLangOpts().OpenCL) { 8535 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 8536 CompositeQuals.setAddressSpace(ResultAddrSpace); 8537 return S.Context 8538 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 8539 .withCVRQualifiers(MergedCVRQual); 8540 } 8541 return CompositeTy.withCVRQualifiers(MergedCVRQual); 8542 }(); 8543 if (IsBlockPointer) 8544 ResultTy = S.Context.getBlockPointerType(ResultTy); 8545 else 8546 ResultTy = S.Context.getPointerType(ResultTy); 8547 8548 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 8549 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 8550 return ResultTy; 8551 } 8552 8553 /// Return the resulting type when the operands are both block pointers. 8554 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 8555 ExprResult &LHS, 8556 ExprResult &RHS, 8557 SourceLocation Loc) { 8558 QualType LHSTy = LHS.get()->getType(); 8559 QualType RHSTy = RHS.get()->getType(); 8560 8561 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 8562 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 8563 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 8564 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8565 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8566 return destType; 8567 } 8568 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 8569 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8570 << RHS.get()->getSourceRange(); 8571 return QualType(); 8572 } 8573 8574 // We have 2 block pointer types. 8575 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8576 } 8577 8578 /// Return the resulting type when the operands are both pointers. 8579 static QualType 8580 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 8581 ExprResult &RHS, 8582 SourceLocation Loc) { 8583 // get the pointer types 8584 QualType LHSTy = LHS.get()->getType(); 8585 QualType RHSTy = RHS.get()->getType(); 8586 8587 // get the "pointed to" types 8588 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 8589 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 8590 8591 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 8592 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 8593 // Figure out necessary qualifiers (C99 6.5.15p6) 8594 QualType destPointee 8595 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 8596 QualType destType = S.Context.getPointerType(destPointee); 8597 // Add qualifiers if necessary. 8598 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 8599 // Promote to void*. 8600 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 8601 return destType; 8602 } 8603 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 8604 QualType destPointee 8605 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 8606 QualType destType = S.Context.getPointerType(destPointee); 8607 // Add qualifiers if necessary. 8608 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 8609 // Promote to void*. 8610 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 8611 return destType; 8612 } 8613 8614 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 8615 } 8616 8617 /// Return false if the first expression is not an integer and the second 8618 /// expression is not a pointer, true otherwise. 8619 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 8620 Expr* PointerExpr, SourceLocation Loc, 8621 bool IsIntFirstExpr) { 8622 if (!PointerExpr->getType()->isPointerType() || 8623 !Int.get()->getType()->isIntegerType()) 8624 return false; 8625 8626 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 8627 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 8628 8629 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 8630 << Expr1->getType() << Expr2->getType() 8631 << Expr1->getSourceRange() << Expr2->getSourceRange(); 8632 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 8633 CK_IntegralToPointer); 8634 return true; 8635 } 8636 8637 /// Simple conversion between integer and floating point types. 8638 /// 8639 /// Used when handling the OpenCL conditional operator where the 8640 /// condition is a vector while the other operands are scalar. 8641 /// 8642 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 8643 /// types are either integer or floating type. Between the two 8644 /// operands, the type with the higher rank is defined as the "result 8645 /// type". The other operand needs to be promoted to the same type. No 8646 /// other type promotion is allowed. We cannot use 8647 /// UsualArithmeticConversions() for this purpose, since it always 8648 /// promotes promotable types. 8649 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 8650 ExprResult &RHS, 8651 SourceLocation QuestionLoc) { 8652 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 8653 if (LHS.isInvalid()) 8654 return QualType(); 8655 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8656 if (RHS.isInvalid()) 8657 return QualType(); 8658 8659 // For conversion purposes, we ignore any qualifiers. 8660 // For example, "const float" and "float" are equivalent. 8661 QualType LHSType = 8662 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 8663 QualType RHSType = 8664 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 8665 8666 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 8667 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8668 << LHSType << LHS.get()->getSourceRange(); 8669 return QualType(); 8670 } 8671 8672 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 8673 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 8674 << RHSType << RHS.get()->getSourceRange(); 8675 return QualType(); 8676 } 8677 8678 // If both types are identical, no conversion is needed. 8679 if (LHSType == RHSType) 8680 return LHSType; 8681 8682 // Now handle "real" floating types (i.e. float, double, long double). 8683 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 8684 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 8685 /*IsCompAssign = */ false); 8686 8687 // Finally, we have two differing integer types. 8688 return handleIntegerConversion<doIntegralCast, doIntegralCast> 8689 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 8690 } 8691 8692 /// Convert scalar operands to a vector that matches the 8693 /// condition in length. 8694 /// 8695 /// Used when handling the OpenCL conditional operator where the 8696 /// condition is a vector while the other operands are scalar. 8697 /// 8698 /// We first compute the "result type" for the scalar operands 8699 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 8700 /// into a vector of that type where the length matches the condition 8701 /// vector type. s6.11.6 requires that the element types of the result 8702 /// and the condition must have the same number of bits. 8703 static QualType 8704 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 8705 QualType CondTy, SourceLocation QuestionLoc) { 8706 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 8707 if (ResTy.isNull()) return QualType(); 8708 8709 const VectorType *CV = CondTy->getAs<VectorType>(); 8710 assert(CV); 8711 8712 // Determine the vector result type 8713 unsigned NumElements = CV->getNumElements(); 8714 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 8715 8716 // Ensure that all types have the same number of bits 8717 if (S.Context.getTypeSize(CV->getElementType()) 8718 != S.Context.getTypeSize(ResTy)) { 8719 // Since VectorTy is created internally, it does not pretty print 8720 // with an OpenCL name. Instead, we just print a description. 8721 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 8722 SmallString<64> Str; 8723 llvm::raw_svector_ostream OS(Str); 8724 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 8725 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8726 << CondTy << OS.str(); 8727 return QualType(); 8728 } 8729 8730 // Convert operands to the vector result type 8731 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 8732 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 8733 8734 return VectorTy; 8735 } 8736 8737 /// Return false if this is a valid OpenCL condition vector 8738 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 8739 SourceLocation QuestionLoc) { 8740 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 8741 // integral type. 8742 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 8743 assert(CondTy); 8744 QualType EleTy = CondTy->getElementType(); 8745 if (EleTy->isIntegerType()) return false; 8746 8747 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 8748 << Cond->getType() << Cond->getSourceRange(); 8749 return true; 8750 } 8751 8752 /// Return false if the vector condition type and the vector 8753 /// result type are compatible. 8754 /// 8755 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 8756 /// number of elements, and their element types have the same number 8757 /// of bits. 8758 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 8759 SourceLocation QuestionLoc) { 8760 const VectorType *CV = CondTy->getAs<VectorType>(); 8761 const VectorType *RV = VecResTy->getAs<VectorType>(); 8762 assert(CV && RV); 8763 8764 if (CV->getNumElements() != RV->getNumElements()) { 8765 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 8766 << CondTy << VecResTy; 8767 return true; 8768 } 8769 8770 QualType CVE = CV->getElementType(); 8771 QualType RVE = RV->getElementType(); 8772 8773 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 8774 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 8775 << CondTy << VecResTy; 8776 return true; 8777 } 8778 8779 return false; 8780 } 8781 8782 /// Return the resulting type for the conditional operator in 8783 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 8784 /// s6.3.i) when the condition is a vector type. 8785 static QualType 8786 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 8787 ExprResult &LHS, ExprResult &RHS, 8788 SourceLocation QuestionLoc) { 8789 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 8790 if (Cond.isInvalid()) 8791 return QualType(); 8792 QualType CondTy = Cond.get()->getType(); 8793 8794 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 8795 return QualType(); 8796 8797 // If either operand is a vector then find the vector type of the 8798 // result as specified in OpenCL v1.1 s6.3.i. 8799 if (LHS.get()->getType()->isVectorType() || 8800 RHS.get()->getType()->isVectorType()) { 8801 bool IsBoolVecLang = 8802 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus; 8803 QualType VecResTy = 8804 S.CheckVectorOperands(LHS, RHS, QuestionLoc, 8805 /*isCompAssign*/ false, 8806 /*AllowBothBool*/ true, 8807 /*AllowBoolConversions*/ false, 8808 /*AllowBooleanOperation*/ IsBoolVecLang, 8809 /*ReportInvalid*/ true); 8810 if (VecResTy.isNull()) 8811 return QualType(); 8812 // The result type must match the condition type as specified in 8813 // OpenCL v1.1 s6.11.6. 8814 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 8815 return QualType(); 8816 return VecResTy; 8817 } 8818 8819 // Both operands are scalar. 8820 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 8821 } 8822 8823 /// Return true if the Expr is block type 8824 static bool checkBlockType(Sema &S, const Expr *E) { 8825 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 8826 QualType Ty = CE->getCallee()->getType(); 8827 if (Ty->isBlockPointerType()) { 8828 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 8829 return true; 8830 } 8831 } 8832 return false; 8833 } 8834 8835 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 8836 /// In that case, LHS = cond. 8837 /// C99 6.5.15 8838 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 8839 ExprResult &RHS, ExprValueKind &VK, 8840 ExprObjectKind &OK, 8841 SourceLocation QuestionLoc) { 8842 8843 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 8844 if (!LHSResult.isUsable()) return QualType(); 8845 LHS = LHSResult; 8846 8847 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 8848 if (!RHSResult.isUsable()) return QualType(); 8849 RHS = RHSResult; 8850 8851 // C++ is sufficiently different to merit its own checker. 8852 if (getLangOpts().CPlusPlus) 8853 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 8854 8855 VK = VK_PRValue; 8856 OK = OK_Ordinary; 8857 8858 if (Context.isDependenceAllowed() && 8859 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() || 8860 RHS.get()->isTypeDependent())) { 8861 assert(!getLangOpts().CPlusPlus); 8862 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() || 8863 RHS.get()->containsErrors()) && 8864 "should only occur in error-recovery path."); 8865 return Context.DependentTy; 8866 } 8867 8868 // The OpenCL operator with a vector condition is sufficiently 8869 // different to merit its own checker. 8870 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) || 8871 Cond.get()->getType()->isExtVectorType()) 8872 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 8873 8874 // First, check the condition. 8875 Cond = UsualUnaryConversions(Cond.get()); 8876 if (Cond.isInvalid()) 8877 return QualType(); 8878 if (checkCondition(*this, Cond.get(), QuestionLoc)) 8879 return QualType(); 8880 8881 // Now check the two expressions. 8882 if (LHS.get()->getType()->isVectorType() || 8883 RHS.get()->getType()->isVectorType()) 8884 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false, 8885 /*AllowBothBool*/ true, 8886 /*AllowBoolConversions*/ false, 8887 /*AllowBooleanOperation*/ false, 8888 /*ReportInvalid*/ true); 8889 8890 QualType ResTy = 8891 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 8892 if (LHS.isInvalid() || RHS.isInvalid()) 8893 return QualType(); 8894 8895 QualType LHSTy = LHS.get()->getType(); 8896 QualType RHSTy = RHS.get()->getType(); 8897 8898 // Diagnose attempts to convert between __ibm128, __float128 and long double 8899 // where such conversions currently can't be handled. 8900 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 8901 Diag(QuestionLoc, 8902 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 8903 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8904 return QualType(); 8905 } 8906 8907 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 8908 // selection operator (?:). 8909 if (getLangOpts().OpenCL && 8910 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) { 8911 return QualType(); 8912 } 8913 8914 // If both operands have arithmetic type, do the usual arithmetic conversions 8915 // to find a common type: C99 6.5.15p3,5. 8916 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 8917 // Disallow invalid arithmetic conversions, such as those between bit- 8918 // precise integers types of different sizes, or between a bit-precise 8919 // integer and another type. 8920 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) { 8921 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 8922 << LHSTy << RHSTy << LHS.get()->getSourceRange() 8923 << RHS.get()->getSourceRange(); 8924 return QualType(); 8925 } 8926 8927 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 8928 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 8929 8930 return ResTy; 8931 } 8932 8933 // And if they're both bfloat (which isn't arithmetic), that's fine too. 8934 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) { 8935 return Context.getCommonSugaredType(LHSTy, RHSTy); 8936 } 8937 8938 // If both operands are the same structure or union type, the result is that 8939 // type. 8940 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 8941 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 8942 if (LHSRT->getDecl() == RHSRT->getDecl()) 8943 // "If both the operands have structure or union type, the result has 8944 // that type." This implies that CV qualifiers are dropped. 8945 return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(), 8946 RHSTy.getUnqualifiedType()); 8947 // FIXME: Type of conditional expression must be complete in C mode. 8948 } 8949 8950 // C99 6.5.15p5: "If both operands have void type, the result has void type." 8951 // The following || allows only one side to be void (a GCC-ism). 8952 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 8953 QualType ResTy; 8954 if (LHSTy->isVoidType() && RHSTy->isVoidType()) { 8955 ResTy = Context.getCommonSugaredType(LHSTy, RHSTy); 8956 } else if (RHSTy->isVoidType()) { 8957 ResTy = RHSTy; 8958 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void) 8959 << RHS.get()->getSourceRange(); 8960 } else { 8961 ResTy = LHSTy; 8962 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void) 8963 << LHS.get()->getSourceRange(); 8964 } 8965 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid); 8966 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid); 8967 return ResTy; 8968 } 8969 8970 // C2x 6.5.15p7: 8971 // ... if both the second and third operands have nullptr_t type, the 8972 // result also has that type. 8973 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy)) 8974 return ResTy; 8975 8976 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 8977 // the type of the other operand." 8978 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 8979 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 8980 8981 // All objective-c pointer type analysis is done here. 8982 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 8983 QuestionLoc); 8984 if (LHS.isInvalid() || RHS.isInvalid()) 8985 return QualType(); 8986 if (!compositeType.isNull()) 8987 return compositeType; 8988 8989 8990 // Handle block pointer types. 8991 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 8992 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 8993 QuestionLoc); 8994 8995 // Check constraints for C object pointers types (C99 6.5.15p3,6). 8996 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 8997 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 8998 QuestionLoc); 8999 9000 // GCC compatibility: soften pointer/integer mismatch. Note that 9001 // null pointers have been filtered out by this point. 9002 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 9003 /*IsIntFirstExpr=*/true)) 9004 return RHSTy; 9005 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 9006 /*IsIntFirstExpr=*/false)) 9007 return LHSTy; 9008 9009 // Allow ?: operations in which both operands have the same 9010 // built-in sizeless type. 9011 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy)) 9012 return Context.getCommonSugaredType(LHSTy, RHSTy); 9013 9014 // Emit a better diagnostic if one of the expressions is a null pointer 9015 // constant and the other is not a pointer type. In this case, the user most 9016 // likely forgot to take the address of the other expression. 9017 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 9018 return QualType(); 9019 9020 // Otherwise, the operands are not compatible. 9021 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 9022 << LHSTy << RHSTy << LHS.get()->getSourceRange() 9023 << RHS.get()->getSourceRange(); 9024 return QualType(); 9025 } 9026 9027 /// FindCompositeObjCPointerType - Helper method to find composite type of 9028 /// two objective-c pointer types of the two input expressions. 9029 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 9030 SourceLocation QuestionLoc) { 9031 QualType LHSTy = LHS.get()->getType(); 9032 QualType RHSTy = RHS.get()->getType(); 9033 9034 // Handle things like Class and struct objc_class*. Here we case the result 9035 // to the pseudo-builtin, because that will be implicitly cast back to the 9036 // redefinition type if an attempt is made to access its fields. 9037 if (LHSTy->isObjCClassType() && 9038 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 9039 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 9040 return LHSTy; 9041 } 9042 if (RHSTy->isObjCClassType() && 9043 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 9044 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 9045 return RHSTy; 9046 } 9047 // And the same for struct objc_object* / id 9048 if (LHSTy->isObjCIdType() && 9049 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 9050 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 9051 return LHSTy; 9052 } 9053 if (RHSTy->isObjCIdType() && 9054 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 9055 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 9056 return RHSTy; 9057 } 9058 // And the same for struct objc_selector* / SEL 9059 if (Context.isObjCSelType(LHSTy) && 9060 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 9061 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 9062 return LHSTy; 9063 } 9064 if (Context.isObjCSelType(RHSTy) && 9065 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 9066 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 9067 return RHSTy; 9068 } 9069 // Check constraints for Objective-C object pointers types. 9070 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 9071 9072 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 9073 // Two identical object pointer types are always compatible. 9074 return LHSTy; 9075 } 9076 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 9077 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 9078 QualType compositeType = LHSTy; 9079 9080 // If both operands are interfaces and either operand can be 9081 // assigned to the other, use that type as the composite 9082 // type. This allows 9083 // xxx ? (A*) a : (B*) b 9084 // where B is a subclass of A. 9085 // 9086 // Additionally, as for assignment, if either type is 'id' 9087 // allow silent coercion. Finally, if the types are 9088 // incompatible then make sure to use 'id' as the composite 9089 // type so the result is acceptable for sending messages to. 9090 9091 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 9092 // It could return the composite type. 9093 if (!(compositeType = 9094 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 9095 // Nothing more to do. 9096 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 9097 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 9098 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 9099 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 9100 } else if ((LHSOPT->isObjCQualifiedIdType() || 9101 RHSOPT->isObjCQualifiedIdType()) && 9102 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, 9103 true)) { 9104 // Need to handle "id<xx>" explicitly. 9105 // GCC allows qualified id and any Objective-C type to devolve to 9106 // id. Currently localizing to here until clear this should be 9107 // part of ObjCQualifiedIdTypesAreCompatible. 9108 compositeType = Context.getObjCIdType(); 9109 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 9110 compositeType = Context.getObjCIdType(); 9111 } else { 9112 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 9113 << LHSTy << RHSTy 9114 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9115 QualType incompatTy = Context.getObjCIdType(); 9116 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 9117 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 9118 return incompatTy; 9119 } 9120 // The object pointer types are compatible. 9121 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 9122 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 9123 return compositeType; 9124 } 9125 // Check Objective-C object pointer types and 'void *' 9126 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 9127 if (getLangOpts().ObjCAutoRefCount) { 9128 // ARC forbids the implicit conversion of object pointers to 'void *', 9129 // so these types are not compatible. 9130 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 9131 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9132 LHS = RHS = true; 9133 return QualType(); 9134 } 9135 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 9136 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 9137 QualType destPointee 9138 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 9139 QualType destType = Context.getPointerType(destPointee); 9140 // Add qualifiers if necessary. 9141 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 9142 // Promote to void*. 9143 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 9144 return destType; 9145 } 9146 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 9147 if (getLangOpts().ObjCAutoRefCount) { 9148 // ARC forbids the implicit conversion of object pointers to 'void *', 9149 // so these types are not compatible. 9150 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 9151 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9152 LHS = RHS = true; 9153 return QualType(); 9154 } 9155 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType(); 9156 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 9157 QualType destPointee 9158 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 9159 QualType destType = Context.getPointerType(destPointee); 9160 // Add qualifiers if necessary. 9161 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 9162 // Promote to void*. 9163 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 9164 return destType; 9165 } 9166 return QualType(); 9167 } 9168 9169 /// SuggestParentheses - Emit a note with a fixit hint that wraps 9170 /// ParenRange in parentheses. 9171 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 9172 const PartialDiagnostic &Note, 9173 SourceRange ParenRange) { 9174 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 9175 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 9176 EndLoc.isValid()) { 9177 Self.Diag(Loc, Note) 9178 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 9179 << FixItHint::CreateInsertion(EndLoc, ")"); 9180 } else { 9181 // We can't display the parentheses, so just show the bare note. 9182 Self.Diag(Loc, Note) << ParenRange; 9183 } 9184 } 9185 9186 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 9187 return BinaryOperator::isAdditiveOp(Opc) || 9188 BinaryOperator::isMultiplicativeOp(Opc) || 9189 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or; 9190 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and 9191 // not any of the logical operators. Bitwise-xor is commonly used as a 9192 // logical-xor because there is no logical-xor operator. The logical 9193 // operators, including uses of xor, have a high false positive rate for 9194 // precedence warnings. 9195 } 9196 9197 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 9198 /// expression, either using a built-in or overloaded operator, 9199 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 9200 /// expression. 9201 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 9202 Expr **RHSExprs) { 9203 // Don't strip parenthesis: we should not warn if E is in parenthesis. 9204 E = E->IgnoreImpCasts(); 9205 E = E->IgnoreConversionOperatorSingleStep(); 9206 E = E->IgnoreImpCasts(); 9207 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 9208 E = MTE->getSubExpr(); 9209 E = E->IgnoreImpCasts(); 9210 } 9211 9212 // Built-in binary operator. 9213 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 9214 if (IsArithmeticOp(OP->getOpcode())) { 9215 *Opcode = OP->getOpcode(); 9216 *RHSExprs = OP->getRHS(); 9217 return true; 9218 } 9219 } 9220 9221 // Overloaded operator. 9222 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 9223 if (Call->getNumArgs() != 2) 9224 return false; 9225 9226 // Make sure this is really a binary operator that is safe to pass into 9227 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 9228 OverloadedOperatorKind OO = Call->getOperator(); 9229 if (OO < OO_Plus || OO > OO_Arrow || 9230 OO == OO_PlusPlus || OO == OO_MinusMinus) 9231 return false; 9232 9233 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 9234 if (IsArithmeticOp(OpKind)) { 9235 *Opcode = OpKind; 9236 *RHSExprs = Call->getArg(1); 9237 return true; 9238 } 9239 } 9240 9241 return false; 9242 } 9243 9244 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 9245 /// or is a logical expression such as (x==y) which has int type, but is 9246 /// commonly interpreted as boolean. 9247 static bool ExprLooksBoolean(Expr *E) { 9248 E = E->IgnoreParenImpCasts(); 9249 9250 if (E->getType()->isBooleanType()) 9251 return true; 9252 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 9253 return OP->isComparisonOp() || OP->isLogicalOp(); 9254 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 9255 return OP->getOpcode() == UO_LNot; 9256 if (E->getType()->isPointerType()) 9257 return true; 9258 // FIXME: What about overloaded operator calls returning "unspecified boolean 9259 // type"s (commonly pointer-to-members)? 9260 9261 return false; 9262 } 9263 9264 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 9265 /// and binary operator are mixed in a way that suggests the programmer assumed 9266 /// the conditional operator has higher precedence, for example: 9267 /// "int x = a + someBinaryCondition ? 1 : 2". 9268 static void DiagnoseConditionalPrecedence(Sema &Self, 9269 SourceLocation OpLoc, 9270 Expr *Condition, 9271 Expr *LHSExpr, 9272 Expr *RHSExpr) { 9273 BinaryOperatorKind CondOpcode; 9274 Expr *CondRHS; 9275 9276 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 9277 return; 9278 if (!ExprLooksBoolean(CondRHS)) 9279 return; 9280 9281 // The condition is an arithmetic binary expression, with a right- 9282 // hand side that looks boolean, so warn. 9283 9284 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) 9285 ? diag::warn_precedence_bitwise_conditional 9286 : diag::warn_precedence_conditional; 9287 9288 Self.Diag(OpLoc, DiagID) 9289 << Condition->getSourceRange() 9290 << BinaryOperator::getOpcodeStr(CondOpcode); 9291 9292 SuggestParentheses( 9293 Self, OpLoc, 9294 Self.PDiag(diag::note_precedence_silence) 9295 << BinaryOperator::getOpcodeStr(CondOpcode), 9296 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 9297 9298 SuggestParentheses(Self, OpLoc, 9299 Self.PDiag(diag::note_precedence_conditional_first), 9300 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 9301 } 9302 9303 /// Compute the nullability of a conditional expression. 9304 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 9305 QualType LHSTy, QualType RHSTy, 9306 ASTContext &Ctx) { 9307 if (!ResTy->isAnyPointerType()) 9308 return ResTy; 9309 9310 auto GetNullability = [](QualType Ty) { 9311 std::optional<NullabilityKind> Kind = Ty->getNullability(); 9312 if (Kind) { 9313 // For our purposes, treat _Nullable_result as _Nullable. 9314 if (*Kind == NullabilityKind::NullableResult) 9315 return NullabilityKind::Nullable; 9316 return *Kind; 9317 } 9318 return NullabilityKind::Unspecified; 9319 }; 9320 9321 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 9322 NullabilityKind MergedKind; 9323 9324 // Compute nullability of a binary conditional expression. 9325 if (IsBin) { 9326 if (LHSKind == NullabilityKind::NonNull) 9327 MergedKind = NullabilityKind::NonNull; 9328 else 9329 MergedKind = RHSKind; 9330 // Compute nullability of a normal conditional expression. 9331 } else { 9332 if (LHSKind == NullabilityKind::Nullable || 9333 RHSKind == NullabilityKind::Nullable) 9334 MergedKind = NullabilityKind::Nullable; 9335 else if (LHSKind == NullabilityKind::NonNull) 9336 MergedKind = RHSKind; 9337 else if (RHSKind == NullabilityKind::NonNull) 9338 MergedKind = LHSKind; 9339 else 9340 MergedKind = NullabilityKind::Unspecified; 9341 } 9342 9343 // Return if ResTy already has the correct nullability. 9344 if (GetNullability(ResTy) == MergedKind) 9345 return ResTy; 9346 9347 // Strip all nullability from ResTy. 9348 while (ResTy->getNullability()) 9349 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 9350 9351 // Create a new AttributedType with the new nullability kind. 9352 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 9353 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 9354 } 9355 9356 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 9357 /// in the case of a the GNU conditional expr extension. 9358 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 9359 SourceLocation ColonLoc, 9360 Expr *CondExpr, Expr *LHSExpr, 9361 Expr *RHSExpr) { 9362 if (!Context.isDependenceAllowed()) { 9363 // C cannot handle TypoExpr nodes in the condition because it 9364 // doesn't handle dependent types properly, so make sure any TypoExprs have 9365 // been dealt with before checking the operands. 9366 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 9367 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 9368 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 9369 9370 if (!CondResult.isUsable()) 9371 return ExprError(); 9372 9373 if (LHSExpr) { 9374 if (!LHSResult.isUsable()) 9375 return ExprError(); 9376 } 9377 9378 if (!RHSResult.isUsable()) 9379 return ExprError(); 9380 9381 CondExpr = CondResult.get(); 9382 LHSExpr = LHSResult.get(); 9383 RHSExpr = RHSResult.get(); 9384 } 9385 9386 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 9387 // was the condition. 9388 OpaqueValueExpr *opaqueValue = nullptr; 9389 Expr *commonExpr = nullptr; 9390 if (!LHSExpr) { 9391 commonExpr = CondExpr; 9392 // Lower out placeholder types first. This is important so that we don't 9393 // try to capture a placeholder. This happens in few cases in C++; such 9394 // as Objective-C++'s dictionary subscripting syntax. 9395 if (commonExpr->hasPlaceholderType()) { 9396 ExprResult result = CheckPlaceholderExpr(commonExpr); 9397 if (!result.isUsable()) return ExprError(); 9398 commonExpr = result.get(); 9399 } 9400 // We usually want to apply unary conversions *before* saving, except 9401 // in the special case of a C++ l-value conditional. 9402 if (!(getLangOpts().CPlusPlus 9403 && !commonExpr->isTypeDependent() 9404 && commonExpr->getValueKind() == RHSExpr->getValueKind() 9405 && commonExpr->isGLValue() 9406 && commonExpr->isOrdinaryOrBitFieldObject() 9407 && RHSExpr->isOrdinaryOrBitFieldObject() 9408 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 9409 ExprResult commonRes = UsualUnaryConversions(commonExpr); 9410 if (commonRes.isInvalid()) 9411 return ExprError(); 9412 commonExpr = commonRes.get(); 9413 } 9414 9415 // If the common expression is a class or array prvalue, materialize it 9416 // so that we can safely refer to it multiple times. 9417 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() || 9418 commonExpr->getType()->isArrayType())) { 9419 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 9420 if (MatExpr.isInvalid()) 9421 return ExprError(); 9422 commonExpr = MatExpr.get(); 9423 } 9424 9425 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 9426 commonExpr->getType(), 9427 commonExpr->getValueKind(), 9428 commonExpr->getObjectKind(), 9429 commonExpr); 9430 LHSExpr = CondExpr = opaqueValue; 9431 } 9432 9433 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 9434 ExprValueKind VK = VK_PRValue; 9435 ExprObjectKind OK = OK_Ordinary; 9436 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 9437 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 9438 VK, OK, QuestionLoc); 9439 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 9440 RHS.isInvalid()) 9441 return ExprError(); 9442 9443 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 9444 RHS.get()); 9445 9446 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 9447 9448 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 9449 Context); 9450 9451 if (!commonExpr) 9452 return new (Context) 9453 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 9454 RHS.get(), result, VK, OK); 9455 9456 return new (Context) BinaryConditionalOperator( 9457 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 9458 ColonLoc, result, VK, OK); 9459 } 9460 9461 // Check if we have a conversion between incompatible cmse function pointer 9462 // types, that is, a conversion between a function pointer with the 9463 // cmse_nonsecure_call attribute and one without. 9464 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, 9465 QualType ToType) { 9466 if (const auto *ToFn = 9467 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) { 9468 if (const auto *FromFn = 9469 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) { 9470 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 9471 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 9472 9473 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall(); 9474 } 9475 } 9476 return false; 9477 } 9478 9479 // checkPointerTypesForAssignment - This is a very tricky routine (despite 9480 // being closely modeled after the C99 spec:-). The odd characteristic of this 9481 // routine is it effectively iqnores the qualifiers on the top level pointee. 9482 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 9483 // FIXME: add a couple examples in this comment. 9484 static Sema::AssignConvertType 9485 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType, 9486 SourceLocation Loc) { 9487 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9488 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9489 9490 // get the "pointed to" type (ignoring qualifiers at the top level) 9491 const Type *lhptee, *rhptee; 9492 Qualifiers lhq, rhq; 9493 std::tie(lhptee, lhq) = 9494 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 9495 std::tie(rhptee, rhq) = 9496 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 9497 9498 Sema::AssignConvertType ConvTy = Sema::Compatible; 9499 9500 // C99 6.5.16.1p1: This following citation is common to constraints 9501 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 9502 // qualifiers of the type *pointed to* by the right; 9503 9504 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 9505 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 9506 lhq.compatiblyIncludesObjCLifetime(rhq)) { 9507 // Ignore lifetime for further calculation. 9508 lhq.removeObjCLifetime(); 9509 rhq.removeObjCLifetime(); 9510 } 9511 9512 if (!lhq.compatiblyIncludes(rhq)) { 9513 // Treat address-space mismatches as fatal. 9514 if (!lhq.isAddressSpaceSupersetOf(rhq)) 9515 return Sema::IncompatiblePointerDiscardsQualifiers; 9516 9517 // It's okay to add or remove GC or lifetime qualifiers when converting to 9518 // and from void*. 9519 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 9520 .compatiblyIncludes( 9521 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 9522 && (lhptee->isVoidType() || rhptee->isVoidType())) 9523 ; // keep old 9524 9525 // Treat lifetime mismatches as fatal. 9526 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 9527 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 9528 9529 // For GCC/MS compatibility, other qualifier mismatches are treated 9530 // as still compatible in C. 9531 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9532 } 9533 9534 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 9535 // incomplete type and the other is a pointer to a qualified or unqualified 9536 // version of void... 9537 if (lhptee->isVoidType()) { 9538 if (rhptee->isIncompleteOrObjectType()) 9539 return ConvTy; 9540 9541 // As an extension, we allow cast to/from void* to function pointer. 9542 assert(rhptee->isFunctionType()); 9543 return Sema::FunctionVoidPointer; 9544 } 9545 9546 if (rhptee->isVoidType()) { 9547 if (lhptee->isIncompleteOrObjectType()) 9548 return ConvTy; 9549 9550 // As an extension, we allow cast to/from void* to function pointer. 9551 assert(lhptee->isFunctionType()); 9552 return Sema::FunctionVoidPointer; 9553 } 9554 9555 if (!S.Diags.isIgnored( 9556 diag::warn_typecheck_convert_incompatible_function_pointer_strict, 9557 Loc) && 9558 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() && 9559 !S.IsFunctionConversion(RHSType, LHSType, RHSType)) 9560 return Sema::IncompatibleFunctionPointerStrict; 9561 9562 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 9563 // unqualified versions of compatible types, ... 9564 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 9565 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 9566 // Check if the pointee types are compatible ignoring the sign. 9567 // We explicitly check for char so that we catch "char" vs 9568 // "unsigned char" on systems where "char" is unsigned. 9569 if (lhptee->isCharType()) 9570 ltrans = S.Context.UnsignedCharTy; 9571 else if (lhptee->hasSignedIntegerRepresentation()) 9572 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 9573 9574 if (rhptee->isCharType()) 9575 rtrans = S.Context.UnsignedCharTy; 9576 else if (rhptee->hasSignedIntegerRepresentation()) 9577 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 9578 9579 if (ltrans == rtrans) { 9580 // Types are compatible ignoring the sign. Qualifier incompatibility 9581 // takes priority over sign incompatibility because the sign 9582 // warning can be disabled. 9583 if (ConvTy != Sema::Compatible) 9584 return ConvTy; 9585 9586 return Sema::IncompatiblePointerSign; 9587 } 9588 9589 // If we are a multi-level pointer, it's possible that our issue is simply 9590 // one of qualification - e.g. char ** -> const char ** is not allowed. If 9591 // the eventual target type is the same and the pointers have the same 9592 // level of indirection, this must be the issue. 9593 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 9594 do { 9595 std::tie(lhptee, lhq) = 9596 cast<PointerType>(lhptee)->getPointeeType().split().asPair(); 9597 std::tie(rhptee, rhq) = 9598 cast<PointerType>(rhptee)->getPointeeType().split().asPair(); 9599 9600 // Inconsistent address spaces at this point is invalid, even if the 9601 // address spaces would be compatible. 9602 // FIXME: This doesn't catch address space mismatches for pointers of 9603 // different nesting levels, like: 9604 // __local int *** a; 9605 // int ** b = a; 9606 // It's not clear how to actually determine when such pointers are 9607 // invalidly incompatible. 9608 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 9609 return Sema::IncompatibleNestedPointerAddressSpaceMismatch; 9610 9611 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 9612 9613 if (lhptee == rhptee) 9614 return Sema::IncompatibleNestedPointerQualifiers; 9615 } 9616 9617 // General pointer incompatibility takes priority over qualifiers. 9618 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType()) 9619 return Sema::IncompatibleFunctionPointer; 9620 return Sema::IncompatiblePointer; 9621 } 9622 if (!S.getLangOpts().CPlusPlus && 9623 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 9624 return Sema::IncompatibleFunctionPointer; 9625 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans)) 9626 return Sema::IncompatibleFunctionPointer; 9627 return ConvTy; 9628 } 9629 9630 /// checkBlockPointerTypesForAssignment - This routine determines whether two 9631 /// block pointer types are compatible or whether a block and normal pointer 9632 /// are compatible. It is more restrict than comparing two function pointer 9633 // types. 9634 static Sema::AssignConvertType 9635 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 9636 QualType RHSType) { 9637 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 9638 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 9639 9640 QualType lhptee, rhptee; 9641 9642 // get the "pointed to" type (ignoring qualifiers at the top level) 9643 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 9644 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 9645 9646 // In C++, the types have to match exactly. 9647 if (S.getLangOpts().CPlusPlus) 9648 return Sema::IncompatibleBlockPointer; 9649 9650 Sema::AssignConvertType ConvTy = Sema::Compatible; 9651 9652 // For blocks we enforce that qualifiers are identical. 9653 Qualifiers LQuals = lhptee.getLocalQualifiers(); 9654 Qualifiers RQuals = rhptee.getLocalQualifiers(); 9655 if (S.getLangOpts().OpenCL) { 9656 LQuals.removeAddressSpace(); 9657 RQuals.removeAddressSpace(); 9658 } 9659 if (LQuals != RQuals) 9660 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 9661 9662 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 9663 // assignment. 9664 // The current behavior is similar to C++ lambdas. A block might be 9665 // assigned to a variable iff its return type and parameters are compatible 9666 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 9667 // an assignment. Presumably it should behave in way that a function pointer 9668 // assignment does in C, so for each parameter and return type: 9669 // * CVR and address space of LHS should be a superset of CVR and address 9670 // space of RHS. 9671 // * unqualified types should be compatible. 9672 if (S.getLangOpts().OpenCL) { 9673 if (!S.Context.typesAreBlockPointerCompatible( 9674 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 9675 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 9676 return Sema::IncompatibleBlockPointer; 9677 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 9678 return Sema::IncompatibleBlockPointer; 9679 9680 return ConvTy; 9681 } 9682 9683 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 9684 /// for assignment compatibility. 9685 static Sema::AssignConvertType 9686 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 9687 QualType RHSType) { 9688 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 9689 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 9690 9691 if (LHSType->isObjCBuiltinType()) { 9692 // Class is not compatible with ObjC object pointers. 9693 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 9694 !RHSType->isObjCQualifiedClassType()) 9695 return Sema::IncompatiblePointer; 9696 return Sema::Compatible; 9697 } 9698 if (RHSType->isObjCBuiltinType()) { 9699 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 9700 !LHSType->isObjCQualifiedClassType()) 9701 return Sema::IncompatiblePointer; 9702 return Sema::Compatible; 9703 } 9704 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9705 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType(); 9706 9707 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 9708 // make an exception for id<P> 9709 !LHSType->isObjCQualifiedIdType()) 9710 return Sema::CompatiblePointerDiscardsQualifiers; 9711 9712 if (S.Context.typesAreCompatible(LHSType, RHSType)) 9713 return Sema::Compatible; 9714 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 9715 return Sema::IncompatibleObjCQualifiedId; 9716 return Sema::IncompatiblePointer; 9717 } 9718 9719 Sema::AssignConvertType 9720 Sema::CheckAssignmentConstraints(SourceLocation Loc, 9721 QualType LHSType, QualType RHSType) { 9722 // Fake up an opaque expression. We don't actually care about what 9723 // cast operations are required, so if CheckAssignmentConstraints 9724 // adds casts to this they'll be wasted, but fortunately that doesn't 9725 // usually happen on valid code. 9726 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue); 9727 ExprResult RHSPtr = &RHSExpr; 9728 CastKind K; 9729 9730 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 9731 } 9732 9733 /// This helper function returns true if QT is a vector type that has element 9734 /// type ElementType. 9735 static bool isVector(QualType QT, QualType ElementType) { 9736 if (const VectorType *VT = QT->getAs<VectorType>()) 9737 return VT->getElementType().getCanonicalType() == ElementType; 9738 return false; 9739 } 9740 9741 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 9742 /// has code to accommodate several GCC extensions when type checking 9743 /// pointers. Here are some objectionable examples that GCC considers warnings: 9744 /// 9745 /// int a, *pint; 9746 /// short *pshort; 9747 /// struct foo *pfoo; 9748 /// 9749 /// pint = pshort; // warning: assignment from incompatible pointer type 9750 /// a = pint; // warning: assignment makes integer from pointer without a cast 9751 /// pint = a; // warning: assignment makes pointer from integer without a cast 9752 /// pint = pfoo; // warning: assignment from incompatible pointer type 9753 /// 9754 /// As a result, the code for dealing with pointers is more complex than the 9755 /// C99 spec dictates. 9756 /// 9757 /// Sets 'Kind' for any result kind except Incompatible. 9758 Sema::AssignConvertType 9759 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 9760 CastKind &Kind, bool ConvertRHS) { 9761 QualType RHSType = RHS.get()->getType(); 9762 QualType OrigLHSType = LHSType; 9763 9764 // Get canonical types. We're not formatting these types, just comparing 9765 // them. 9766 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 9767 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 9768 9769 // Common case: no conversion required. 9770 if (LHSType == RHSType) { 9771 Kind = CK_NoOp; 9772 return Compatible; 9773 } 9774 9775 // If the LHS has an __auto_type, there are no additional type constraints 9776 // to be worried about. 9777 if (const auto *AT = dyn_cast<AutoType>(LHSType)) { 9778 if (AT->isGNUAutoType()) { 9779 Kind = CK_NoOp; 9780 return Compatible; 9781 } 9782 } 9783 9784 // If we have an atomic type, try a non-atomic assignment, then just add an 9785 // atomic qualification step. 9786 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 9787 Sema::AssignConvertType result = 9788 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 9789 if (result != Compatible) 9790 return result; 9791 if (Kind != CK_NoOp && ConvertRHS) 9792 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 9793 Kind = CK_NonAtomicToAtomic; 9794 return Compatible; 9795 } 9796 9797 // If the left-hand side is a reference type, then we are in a 9798 // (rare!) case where we've allowed the use of references in C, 9799 // e.g., as a parameter type in a built-in function. In this case, 9800 // just make sure that the type referenced is compatible with the 9801 // right-hand side type. The caller is responsible for adjusting 9802 // LHSType so that the resulting expression does not have reference 9803 // type. 9804 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 9805 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 9806 Kind = CK_LValueBitCast; 9807 return Compatible; 9808 } 9809 return Incompatible; 9810 } 9811 9812 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 9813 // to the same ExtVector type. 9814 if (LHSType->isExtVectorType()) { 9815 if (RHSType->isExtVectorType()) 9816 return Incompatible; 9817 if (RHSType->isArithmeticType()) { 9818 // CK_VectorSplat does T -> vector T, so first cast to the element type. 9819 if (ConvertRHS) 9820 RHS = prepareVectorSplat(LHSType, RHS.get()); 9821 Kind = CK_VectorSplat; 9822 return Compatible; 9823 } 9824 } 9825 9826 // Conversions to or from vector type. 9827 if (LHSType->isVectorType() || RHSType->isVectorType()) { 9828 if (LHSType->isVectorType() && RHSType->isVectorType()) { 9829 // Allow assignments of an AltiVec vector type to an equivalent GCC 9830 // vector type and vice versa 9831 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 9832 Kind = CK_BitCast; 9833 return Compatible; 9834 } 9835 9836 // If we are allowing lax vector conversions, and LHS and RHS are both 9837 // vectors, the total size only needs to be the same. This is a bitcast; 9838 // no bits are changed but the result type is different. 9839 if (isLaxVectorConversion(RHSType, LHSType)) { 9840 // The default for lax vector conversions with Altivec vectors will 9841 // change, so if we are converting between vector types where 9842 // at least one is an Altivec vector, emit a warning. 9843 if (anyAltivecTypes(RHSType, LHSType) && 9844 !areSameVectorElemTypes(RHSType, LHSType)) 9845 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all) 9846 << RHSType << LHSType; 9847 Kind = CK_BitCast; 9848 return IncompatibleVectors; 9849 } 9850 } 9851 9852 // When the RHS comes from another lax conversion (e.g. binops between 9853 // scalars and vectors) the result is canonicalized as a vector. When the 9854 // LHS is also a vector, the lax is allowed by the condition above. Handle 9855 // the case where LHS is a scalar. 9856 if (LHSType->isScalarType()) { 9857 const VectorType *VecType = RHSType->getAs<VectorType>(); 9858 if (VecType && VecType->getNumElements() == 1 && 9859 isLaxVectorConversion(RHSType, LHSType)) { 9860 if (VecType->getVectorKind() == VectorType::AltiVecVector) 9861 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all) 9862 << RHSType << LHSType; 9863 ExprResult *VecExpr = &RHS; 9864 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 9865 Kind = CK_BitCast; 9866 return Compatible; 9867 } 9868 } 9869 9870 // Allow assignments between fixed-length and sizeless SVE vectors. 9871 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) || 9872 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType())) 9873 if (Context.areCompatibleSveTypes(LHSType, RHSType) || 9874 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) { 9875 Kind = CK_BitCast; 9876 return Compatible; 9877 } 9878 9879 return Incompatible; 9880 } 9881 9882 // Diagnose attempts to convert between __ibm128, __float128 and long double 9883 // where such conversions currently can't be handled. 9884 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 9885 return Incompatible; 9886 9887 // Disallow assigning a _Complex to a real type in C++ mode since it simply 9888 // discards the imaginary part. 9889 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 9890 !LHSType->getAs<ComplexType>()) 9891 return Incompatible; 9892 9893 // Arithmetic conversions. 9894 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 9895 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 9896 if (ConvertRHS) 9897 Kind = PrepareScalarCast(RHS, LHSType); 9898 return Compatible; 9899 } 9900 9901 // Conversions to normal pointers. 9902 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 9903 // U* -> T* 9904 if (isa<PointerType>(RHSType)) { 9905 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9906 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 9907 if (AddrSpaceL != AddrSpaceR) 9908 Kind = CK_AddressSpaceConversion; 9909 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 9910 Kind = CK_NoOp; 9911 else 9912 Kind = CK_BitCast; 9913 return checkPointerTypesForAssignment(*this, LHSType, RHSType, 9914 RHS.get()->getBeginLoc()); 9915 } 9916 9917 // int -> T* 9918 if (RHSType->isIntegerType()) { 9919 Kind = CK_IntegralToPointer; // FIXME: null? 9920 return IntToPointer; 9921 } 9922 9923 // C pointers are not compatible with ObjC object pointers, 9924 // with two exceptions: 9925 if (isa<ObjCObjectPointerType>(RHSType)) { 9926 // - conversions to void* 9927 if (LHSPointer->getPointeeType()->isVoidType()) { 9928 Kind = CK_BitCast; 9929 return Compatible; 9930 } 9931 9932 // - conversions from 'Class' to the redefinition type 9933 if (RHSType->isObjCClassType() && 9934 Context.hasSameType(LHSType, 9935 Context.getObjCClassRedefinitionType())) { 9936 Kind = CK_BitCast; 9937 return Compatible; 9938 } 9939 9940 Kind = CK_BitCast; 9941 return IncompatiblePointer; 9942 } 9943 9944 // U^ -> void* 9945 if (RHSType->getAs<BlockPointerType>()) { 9946 if (LHSPointer->getPointeeType()->isVoidType()) { 9947 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 9948 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9949 ->getPointeeType() 9950 .getAddressSpace(); 9951 Kind = 9952 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9953 return Compatible; 9954 } 9955 } 9956 9957 return Incompatible; 9958 } 9959 9960 // Conversions to block pointers. 9961 if (isa<BlockPointerType>(LHSType)) { 9962 // U^ -> T^ 9963 if (RHSType->isBlockPointerType()) { 9964 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 9965 ->getPointeeType() 9966 .getAddressSpace(); 9967 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 9968 ->getPointeeType() 9969 .getAddressSpace(); 9970 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 9971 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 9972 } 9973 9974 // int or null -> T^ 9975 if (RHSType->isIntegerType()) { 9976 Kind = CK_IntegralToPointer; // FIXME: null 9977 return IntToBlockPointer; 9978 } 9979 9980 // id -> T^ 9981 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 9982 Kind = CK_AnyPointerToBlockPointerCast; 9983 return Compatible; 9984 } 9985 9986 // void* -> T^ 9987 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 9988 if (RHSPT->getPointeeType()->isVoidType()) { 9989 Kind = CK_AnyPointerToBlockPointerCast; 9990 return Compatible; 9991 } 9992 9993 return Incompatible; 9994 } 9995 9996 // Conversions to Objective-C pointers. 9997 if (isa<ObjCObjectPointerType>(LHSType)) { 9998 // A* -> B* 9999 if (RHSType->isObjCObjectPointerType()) { 10000 Kind = CK_BitCast; 10001 Sema::AssignConvertType result = 10002 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 10003 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 10004 result == Compatible && 10005 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 10006 result = IncompatibleObjCWeakRef; 10007 return result; 10008 } 10009 10010 // int or null -> A* 10011 if (RHSType->isIntegerType()) { 10012 Kind = CK_IntegralToPointer; // FIXME: null 10013 return IntToPointer; 10014 } 10015 10016 // In general, C pointers are not compatible with ObjC object pointers, 10017 // with two exceptions: 10018 if (isa<PointerType>(RHSType)) { 10019 Kind = CK_CPointerToObjCPointerCast; 10020 10021 // - conversions from 'void*' 10022 if (RHSType->isVoidPointerType()) { 10023 return Compatible; 10024 } 10025 10026 // - conversions to 'Class' from its redefinition type 10027 if (LHSType->isObjCClassType() && 10028 Context.hasSameType(RHSType, 10029 Context.getObjCClassRedefinitionType())) { 10030 return Compatible; 10031 } 10032 10033 return IncompatiblePointer; 10034 } 10035 10036 // Only under strict condition T^ is compatible with an Objective-C pointer. 10037 if (RHSType->isBlockPointerType() && 10038 LHSType->isBlockCompatibleObjCPointerType(Context)) { 10039 if (ConvertRHS) 10040 maybeExtendBlockObject(RHS); 10041 Kind = CK_BlockPointerToObjCPointerCast; 10042 return Compatible; 10043 } 10044 10045 return Incompatible; 10046 } 10047 10048 // Conversions from pointers that are not covered by the above. 10049 if (isa<PointerType>(RHSType)) { 10050 // T* -> _Bool 10051 if (LHSType == Context.BoolTy) { 10052 Kind = CK_PointerToBoolean; 10053 return Compatible; 10054 } 10055 10056 // T* -> int 10057 if (LHSType->isIntegerType()) { 10058 Kind = CK_PointerToIntegral; 10059 return PointerToInt; 10060 } 10061 10062 return Incompatible; 10063 } 10064 10065 // Conversions from Objective-C pointers that are not covered by the above. 10066 if (isa<ObjCObjectPointerType>(RHSType)) { 10067 // T* -> _Bool 10068 if (LHSType == Context.BoolTy) { 10069 Kind = CK_PointerToBoolean; 10070 return Compatible; 10071 } 10072 10073 // T* -> int 10074 if (LHSType->isIntegerType()) { 10075 Kind = CK_PointerToIntegral; 10076 return PointerToInt; 10077 } 10078 10079 return Incompatible; 10080 } 10081 10082 // struct A -> struct B 10083 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 10084 if (Context.typesAreCompatible(LHSType, RHSType)) { 10085 Kind = CK_NoOp; 10086 return Compatible; 10087 } 10088 } 10089 10090 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 10091 Kind = CK_IntToOCLSampler; 10092 return Compatible; 10093 } 10094 10095 return Incompatible; 10096 } 10097 10098 /// Constructs a transparent union from an expression that is 10099 /// used to initialize the transparent union. 10100 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 10101 ExprResult &EResult, QualType UnionType, 10102 FieldDecl *Field) { 10103 // Build an initializer list that designates the appropriate member 10104 // of the transparent union. 10105 Expr *E = EResult.get(); 10106 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 10107 E, SourceLocation()); 10108 Initializer->setType(UnionType); 10109 Initializer->setInitializedFieldInUnion(Field); 10110 10111 // Build a compound literal constructing a value of the transparent 10112 // union type from this initializer list. 10113 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 10114 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 10115 VK_PRValue, Initializer, false); 10116 } 10117 10118 Sema::AssignConvertType 10119 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 10120 ExprResult &RHS) { 10121 QualType RHSType = RHS.get()->getType(); 10122 10123 // If the ArgType is a Union type, we want to handle a potential 10124 // transparent_union GCC extension. 10125 const RecordType *UT = ArgType->getAsUnionType(); 10126 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 10127 return Incompatible; 10128 10129 // The field to initialize within the transparent union. 10130 RecordDecl *UD = UT->getDecl(); 10131 FieldDecl *InitField = nullptr; 10132 // It's compatible if the expression matches any of the fields. 10133 for (auto *it : UD->fields()) { 10134 if (it->getType()->isPointerType()) { 10135 // If the transparent union contains a pointer type, we allow: 10136 // 1) void pointer 10137 // 2) null pointer constant 10138 if (RHSType->isPointerType()) 10139 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 10140 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 10141 InitField = it; 10142 break; 10143 } 10144 10145 if (RHS.get()->isNullPointerConstant(Context, 10146 Expr::NPC_ValueDependentIsNull)) { 10147 RHS = ImpCastExprToType(RHS.get(), it->getType(), 10148 CK_NullToPointer); 10149 InitField = it; 10150 break; 10151 } 10152 } 10153 10154 CastKind Kind; 10155 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 10156 == Compatible) { 10157 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 10158 InitField = it; 10159 break; 10160 } 10161 } 10162 10163 if (!InitField) 10164 return Incompatible; 10165 10166 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 10167 return Compatible; 10168 } 10169 10170 Sema::AssignConvertType 10171 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 10172 bool Diagnose, 10173 bool DiagnoseCFAudited, 10174 bool ConvertRHS) { 10175 // We need to be able to tell the caller whether we diagnosed a problem, if 10176 // they ask us to issue diagnostics. 10177 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 10178 10179 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 10180 // we can't avoid *all* modifications at the moment, so we need some somewhere 10181 // to put the updated value. 10182 ExprResult LocalRHS = CallerRHS; 10183 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 10184 10185 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) { 10186 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) { 10187 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) && 10188 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) { 10189 Diag(RHS.get()->getExprLoc(), 10190 diag::warn_noderef_to_dereferenceable_pointer) 10191 << RHS.get()->getSourceRange(); 10192 } 10193 } 10194 } 10195 10196 if (getLangOpts().CPlusPlus) { 10197 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 10198 // C++ 5.17p3: If the left operand is not of class type, the 10199 // expression is implicitly converted (C++ 4) to the 10200 // cv-unqualified type of the left operand. 10201 QualType RHSType = RHS.get()->getType(); 10202 if (Diagnose) { 10203 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 10204 AA_Assigning); 10205 } else { 10206 ImplicitConversionSequence ICS = 10207 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 10208 /*SuppressUserConversions=*/false, 10209 AllowedExplicit::None, 10210 /*InOverloadResolution=*/false, 10211 /*CStyle=*/false, 10212 /*AllowObjCWritebackConversion=*/false); 10213 if (ICS.isFailure()) 10214 return Incompatible; 10215 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 10216 ICS, AA_Assigning); 10217 } 10218 if (RHS.isInvalid()) 10219 return Incompatible; 10220 Sema::AssignConvertType result = Compatible; 10221 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 10222 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 10223 result = IncompatibleObjCWeakRef; 10224 return result; 10225 } 10226 10227 // FIXME: Currently, we fall through and treat C++ classes like C 10228 // structures. 10229 // FIXME: We also fall through for atomics; not sure what should 10230 // happen there, though. 10231 } else if (RHS.get()->getType() == Context.OverloadTy) { 10232 // As a set of extensions to C, we support overloading on functions. These 10233 // functions need to be resolved here. 10234 DeclAccessPair DAP; 10235 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 10236 RHS.get(), LHSType, /*Complain=*/false, DAP)) 10237 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 10238 else 10239 return Incompatible; 10240 } 10241 10242 // This check seems unnatural, however it is necessary to ensure the proper 10243 // conversion of functions/arrays. If the conversion were done for all 10244 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 10245 // expressions that suppress this implicit conversion (&, sizeof). This needs 10246 // to happen before we check for null pointer conversions because C does not 10247 // undergo the same implicit conversions as C++ does above (by the calls to 10248 // TryImplicitConversion() and PerformImplicitConversion()) which insert the 10249 // lvalue to rvalue cast before checking for null pointer constraints. This 10250 // addresses code like: nullptr_t val; int *ptr; ptr = val; 10251 // 10252 // Suppress this for references: C++ 8.5.3p5. 10253 if (!LHSType->isReferenceType()) { 10254 // FIXME: We potentially allocate here even if ConvertRHS is false. 10255 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 10256 if (RHS.isInvalid()) 10257 return Incompatible; 10258 } 10259 10260 // C99 6.5.16.1p1: the left operand is a pointer and the right is 10261 // a null pointer constant. 10262 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 10263 LHSType->isBlockPointerType()) && 10264 RHS.get()->isNullPointerConstant(Context, 10265 Expr::NPC_ValueDependentIsNull)) { 10266 if (Diagnose || ConvertRHS) { 10267 CastKind Kind; 10268 CXXCastPath Path; 10269 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 10270 /*IgnoreBaseAccess=*/false, Diagnose); 10271 if (ConvertRHS) 10272 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path); 10273 } 10274 return Compatible; 10275 } 10276 10277 // OpenCL queue_t type assignment. 10278 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 10279 Context, Expr::NPC_ValueDependentIsNull)) { 10280 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10281 return Compatible; 10282 } 10283 10284 CastKind Kind; 10285 Sema::AssignConvertType result = 10286 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 10287 10288 // C99 6.5.16.1p2: The value of the right operand is converted to the 10289 // type of the assignment expression. 10290 // CheckAssignmentConstraints allows the left-hand side to be a reference, 10291 // so that we can use references in built-in functions even in C. 10292 // The getNonReferenceType() call makes sure that the resulting expression 10293 // does not have reference type. 10294 if (result != Incompatible && RHS.get()->getType() != LHSType) { 10295 QualType Ty = LHSType.getNonLValueExprType(Context); 10296 Expr *E = RHS.get(); 10297 10298 // Check for various Objective-C errors. If we are not reporting 10299 // diagnostics and just checking for errors, e.g., during overload 10300 // resolution, return Incompatible to indicate the failure. 10301 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 10302 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 10303 Diagnose, DiagnoseCFAudited) != ACR_okay) { 10304 if (!Diagnose) 10305 return Incompatible; 10306 } 10307 if (getLangOpts().ObjC && 10308 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 10309 E->getType(), E, Diagnose) || 10310 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) { 10311 if (!Diagnose) 10312 return Incompatible; 10313 // Replace the expression with a corrected version and continue so we 10314 // can find further errors. 10315 RHS = E; 10316 return Compatible; 10317 } 10318 10319 if (ConvertRHS) 10320 RHS = ImpCastExprToType(E, Ty, Kind); 10321 } 10322 10323 return result; 10324 } 10325 10326 namespace { 10327 /// The original operand to an operator, prior to the application of the usual 10328 /// arithmetic conversions and converting the arguments of a builtin operator 10329 /// candidate. 10330 struct OriginalOperand { 10331 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 10332 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 10333 Op = MTE->getSubExpr(); 10334 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 10335 Op = BTE->getSubExpr(); 10336 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 10337 Orig = ICE->getSubExprAsWritten(); 10338 Conversion = ICE->getConversionFunction(); 10339 } 10340 } 10341 10342 QualType getType() const { return Orig->getType(); } 10343 10344 Expr *Orig; 10345 NamedDecl *Conversion; 10346 }; 10347 } 10348 10349 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 10350 ExprResult &RHS) { 10351 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 10352 10353 Diag(Loc, diag::err_typecheck_invalid_operands) 10354 << OrigLHS.getType() << OrigRHS.getType() 10355 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10356 10357 // If a user-defined conversion was applied to either of the operands prior 10358 // to applying the built-in operator rules, tell the user about it. 10359 if (OrigLHS.Conversion) { 10360 Diag(OrigLHS.Conversion->getLocation(), 10361 diag::note_typecheck_invalid_operands_converted) 10362 << 0 << LHS.get()->getType(); 10363 } 10364 if (OrigRHS.Conversion) { 10365 Diag(OrigRHS.Conversion->getLocation(), 10366 diag::note_typecheck_invalid_operands_converted) 10367 << 1 << RHS.get()->getType(); 10368 } 10369 10370 return QualType(); 10371 } 10372 10373 // Diagnose cases where a scalar was implicitly converted to a vector and 10374 // diagnose the underlying types. Otherwise, diagnose the error 10375 // as invalid vector logical operands for non-C++ cases. 10376 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 10377 ExprResult &RHS) { 10378 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 10379 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 10380 10381 bool LHSNatVec = LHSType->isVectorType(); 10382 bool RHSNatVec = RHSType->isVectorType(); 10383 10384 if (!(LHSNatVec && RHSNatVec)) { 10385 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 10386 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 10387 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 10388 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 10389 << Vector->getSourceRange(); 10390 return QualType(); 10391 } 10392 10393 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 10394 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 10395 << RHS.get()->getSourceRange(); 10396 10397 return QualType(); 10398 } 10399 10400 /// Try to convert a value of non-vector type to a vector type by converting 10401 /// the type to the element type of the vector and then performing a splat. 10402 /// If the language is OpenCL, we only use conversions that promote scalar 10403 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 10404 /// for float->int. 10405 /// 10406 /// OpenCL V2.0 6.2.6.p2: 10407 /// An error shall occur if any scalar operand type has greater rank 10408 /// than the type of the vector element. 10409 /// 10410 /// \param scalar - if non-null, actually perform the conversions 10411 /// \return true if the operation fails (but without diagnosing the failure) 10412 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 10413 QualType scalarTy, 10414 QualType vectorEltTy, 10415 QualType vectorTy, 10416 unsigned &DiagID) { 10417 // The conversion to apply to the scalar before splatting it, 10418 // if necessary. 10419 CastKind scalarCast = CK_NoOp; 10420 10421 if (vectorEltTy->isIntegralType(S.Context)) { 10422 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 10423 (scalarTy->isIntegerType() && 10424 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 10425 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 10426 return true; 10427 } 10428 if (!scalarTy->isIntegralType(S.Context)) 10429 return true; 10430 scalarCast = CK_IntegralCast; 10431 } else if (vectorEltTy->isRealFloatingType()) { 10432 if (scalarTy->isRealFloatingType()) { 10433 if (S.getLangOpts().OpenCL && 10434 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 10435 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 10436 return true; 10437 } 10438 scalarCast = CK_FloatingCast; 10439 } 10440 else if (scalarTy->isIntegralType(S.Context)) 10441 scalarCast = CK_IntegralToFloating; 10442 else 10443 return true; 10444 } else { 10445 return true; 10446 } 10447 10448 // Adjust scalar if desired. 10449 if (scalar) { 10450 if (scalarCast != CK_NoOp) 10451 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 10452 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 10453 } 10454 return false; 10455 } 10456 10457 /// Convert vector E to a vector with the same number of elements but different 10458 /// element type. 10459 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 10460 const auto *VecTy = E->getType()->getAs<VectorType>(); 10461 assert(VecTy && "Expression E must be a vector"); 10462 QualType NewVecTy = 10463 VecTy->isExtVectorType() 10464 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements()) 10465 : S.Context.getVectorType(ElementType, VecTy->getNumElements(), 10466 VecTy->getVectorKind()); 10467 10468 // Look through the implicit cast. Return the subexpression if its type is 10469 // NewVecTy. 10470 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 10471 if (ICE->getSubExpr()->getType() == NewVecTy) 10472 return ICE->getSubExpr(); 10473 10474 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 10475 return S.ImpCastExprToType(E, NewVecTy, Cast); 10476 } 10477 10478 /// Test if a (constant) integer Int can be casted to another integer type 10479 /// IntTy without losing precision. 10480 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 10481 QualType OtherIntTy) { 10482 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 10483 10484 // Reject cases where the value of the Int is unknown as that would 10485 // possibly cause truncation, but accept cases where the scalar can be 10486 // demoted without loss of precision. 10487 Expr::EvalResult EVResult; 10488 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 10489 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 10490 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 10491 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 10492 10493 if (CstInt) { 10494 // If the scalar is constant and is of a higher order and has more active 10495 // bits that the vector element type, reject it. 10496 llvm::APSInt Result = EVResult.Val.getInt(); 10497 unsigned NumBits = IntSigned 10498 ? (Result.isNegative() ? Result.getMinSignedBits() 10499 : Result.getActiveBits()) 10500 : Result.getActiveBits(); 10501 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 10502 return true; 10503 10504 // If the signedness of the scalar type and the vector element type 10505 // differs and the number of bits is greater than that of the vector 10506 // element reject it. 10507 return (IntSigned != OtherIntSigned && 10508 NumBits > S.Context.getIntWidth(OtherIntTy)); 10509 } 10510 10511 // Reject cases where the value of the scalar is not constant and it's 10512 // order is greater than that of the vector element type. 10513 return (Order < 0); 10514 } 10515 10516 /// Test if a (constant) integer Int can be casted to floating point type 10517 /// FloatTy without losing precision. 10518 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 10519 QualType FloatTy) { 10520 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 10521 10522 // Determine if the integer constant can be expressed as a floating point 10523 // number of the appropriate type. 10524 Expr::EvalResult EVResult; 10525 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 10526 10527 uint64_t Bits = 0; 10528 if (CstInt) { 10529 // Reject constants that would be truncated if they were converted to 10530 // the floating point type. Test by simple to/from conversion. 10531 // FIXME: Ideally the conversion to an APFloat and from an APFloat 10532 // could be avoided if there was a convertFromAPInt method 10533 // which could signal back if implicit truncation occurred. 10534 llvm::APSInt Result = EVResult.Val.getInt(); 10535 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 10536 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 10537 llvm::APFloat::rmTowardZero); 10538 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 10539 !IntTy->hasSignedIntegerRepresentation()); 10540 bool Ignored = false; 10541 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 10542 &Ignored); 10543 if (Result != ConvertBack) 10544 return true; 10545 } else { 10546 // Reject types that cannot be fully encoded into the mantissa of 10547 // the float. 10548 Bits = S.Context.getTypeSize(IntTy); 10549 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 10550 S.Context.getFloatTypeSemantics(FloatTy)); 10551 if (Bits > FloatPrec) 10552 return true; 10553 } 10554 10555 return false; 10556 } 10557 10558 /// Attempt to convert and splat Scalar into a vector whose types matches 10559 /// Vector following GCC conversion rules. The rule is that implicit 10560 /// conversion can occur when Scalar can be casted to match Vector's element 10561 /// type without causing truncation of Scalar. 10562 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 10563 ExprResult *Vector) { 10564 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 10565 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 10566 QualType VectorEltTy; 10567 10568 if (const auto *VT = VectorTy->getAs<VectorType>()) { 10569 assert(!isa<ExtVectorType>(VT) && 10570 "ExtVectorTypes should not be handled here!"); 10571 VectorEltTy = VT->getElementType(); 10572 } else if (VectorTy->isVLSTBuiltinType()) { 10573 VectorEltTy = 10574 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext()); 10575 } else { 10576 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here"); 10577 } 10578 10579 // Reject cases where the vector element type or the scalar element type are 10580 // not integral or floating point types. 10581 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 10582 return true; 10583 10584 // The conversion to apply to the scalar before splatting it, 10585 // if necessary. 10586 CastKind ScalarCast = CK_NoOp; 10587 10588 // Accept cases where the vector elements are integers and the scalar is 10589 // an integer. 10590 // FIXME: Notionally if the scalar was a floating point value with a precise 10591 // integral representation, we could cast it to an appropriate integer 10592 // type and then perform the rest of the checks here. GCC will perform 10593 // this conversion in some cases as determined by the input language. 10594 // We should accept it on a language independent basis. 10595 if (VectorEltTy->isIntegralType(S.Context) && 10596 ScalarTy->isIntegralType(S.Context) && 10597 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 10598 10599 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 10600 return true; 10601 10602 ScalarCast = CK_IntegralCast; 10603 } else if (VectorEltTy->isIntegralType(S.Context) && 10604 ScalarTy->isRealFloatingType()) { 10605 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy)) 10606 ScalarCast = CK_FloatingToIntegral; 10607 else 10608 return true; 10609 } else if (VectorEltTy->isRealFloatingType()) { 10610 if (ScalarTy->isRealFloatingType()) { 10611 10612 // Reject cases where the scalar type is not a constant and has a higher 10613 // Order than the vector element type. 10614 llvm::APFloat Result(0.0); 10615 10616 // Determine whether this is a constant scalar. In the event that the 10617 // value is dependent (and thus cannot be evaluated by the constant 10618 // evaluator), skip the evaluation. This will then diagnose once the 10619 // expression is instantiated. 10620 bool CstScalar = Scalar->get()->isValueDependent() || 10621 Scalar->get()->EvaluateAsFloat(Result, S.Context); 10622 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 10623 if (!CstScalar && Order < 0) 10624 return true; 10625 10626 // If the scalar cannot be safely casted to the vector element type, 10627 // reject it. 10628 if (CstScalar) { 10629 bool Truncated = false; 10630 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 10631 llvm::APFloat::rmNearestTiesToEven, &Truncated); 10632 if (Truncated) 10633 return true; 10634 } 10635 10636 ScalarCast = CK_FloatingCast; 10637 } else if (ScalarTy->isIntegralType(S.Context)) { 10638 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 10639 return true; 10640 10641 ScalarCast = CK_IntegralToFloating; 10642 } else 10643 return true; 10644 } else if (ScalarTy->isEnumeralType()) 10645 return true; 10646 10647 // Adjust scalar if desired. 10648 if (Scalar) { 10649 if (ScalarCast != CK_NoOp) 10650 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 10651 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 10652 } 10653 return false; 10654 } 10655 10656 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 10657 SourceLocation Loc, bool IsCompAssign, 10658 bool AllowBothBool, 10659 bool AllowBoolConversions, 10660 bool AllowBoolOperation, 10661 bool ReportInvalid) { 10662 if (!IsCompAssign) { 10663 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10664 if (LHS.isInvalid()) 10665 return QualType(); 10666 } 10667 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10668 if (RHS.isInvalid()) 10669 return QualType(); 10670 10671 // For conversion purposes, we ignore any qualifiers. 10672 // For example, "const float" and "float" are equivalent. 10673 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10674 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10675 10676 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 10677 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 10678 assert(LHSVecType || RHSVecType); 10679 10680 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) || 10681 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type())) 10682 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); 10683 10684 // AltiVec-style "vector bool op vector bool" combinations are allowed 10685 // for some operators but not others. 10686 if (!AllowBothBool && 10687 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10688 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 10689 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); 10690 10691 // This operation may not be performed on boolean vectors. 10692 if (!AllowBoolOperation && 10693 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType())) 10694 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType(); 10695 10696 // If the vector types are identical, return. 10697 if (Context.hasSameType(LHSType, RHSType)) 10698 return Context.getCommonSugaredType(LHSType, RHSType); 10699 10700 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 10701 if (LHSVecType && RHSVecType && 10702 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 10703 if (isa<ExtVectorType>(LHSVecType)) { 10704 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10705 return LHSType; 10706 } 10707 10708 if (!IsCompAssign) 10709 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10710 return RHSType; 10711 } 10712 10713 // AllowBoolConversions says that bool and non-bool AltiVec vectors 10714 // can be mixed, with the result being the non-bool type. The non-bool 10715 // operand must have integer element type. 10716 if (AllowBoolConversions && LHSVecType && RHSVecType && 10717 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 10718 (Context.getTypeSize(LHSVecType->getElementType()) == 10719 Context.getTypeSize(RHSVecType->getElementType()))) { 10720 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 10721 LHSVecType->getElementType()->isIntegerType() && 10722 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 10723 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10724 return LHSType; 10725 } 10726 if (!IsCompAssign && 10727 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 10728 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 10729 RHSVecType->getElementType()->isIntegerType()) { 10730 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10731 return RHSType; 10732 } 10733 } 10734 10735 // Expressions containing fixed-length and sizeless SVE vectors are invalid 10736 // since the ambiguity can affect the ABI. 10737 auto IsSveConversion = [](QualType FirstType, QualType SecondType) { 10738 const VectorType *VecType = SecondType->getAs<VectorType>(); 10739 return FirstType->isSizelessBuiltinType() && VecType && 10740 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector || 10741 VecType->getVectorKind() == 10742 VectorType::SveFixedLengthPredicateVector); 10743 }; 10744 10745 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) { 10746 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType; 10747 return QualType(); 10748 } 10749 10750 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid 10751 // since the ambiguity can affect the ABI. 10752 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) { 10753 const VectorType *FirstVecType = FirstType->getAs<VectorType>(); 10754 const VectorType *SecondVecType = SecondType->getAs<VectorType>(); 10755 10756 if (FirstVecType && SecondVecType) 10757 return FirstVecType->getVectorKind() == VectorType::GenericVector && 10758 (SecondVecType->getVectorKind() == 10759 VectorType::SveFixedLengthDataVector || 10760 SecondVecType->getVectorKind() == 10761 VectorType::SveFixedLengthPredicateVector); 10762 10763 return FirstType->isSizelessBuiltinType() && SecondVecType && 10764 SecondVecType->getVectorKind() == VectorType::GenericVector; 10765 }; 10766 10767 if (IsSveGnuConversion(LHSType, RHSType) || 10768 IsSveGnuConversion(RHSType, LHSType)) { 10769 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType; 10770 return QualType(); 10771 } 10772 10773 // If there's a vector type and a scalar, try to convert the scalar to 10774 // the vector element type and splat. 10775 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 10776 if (!RHSVecType) { 10777 if (isa<ExtVectorType>(LHSVecType)) { 10778 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 10779 LHSVecType->getElementType(), LHSType, 10780 DiagID)) 10781 return LHSType; 10782 } else { 10783 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10784 return LHSType; 10785 } 10786 } 10787 if (!LHSVecType) { 10788 if (isa<ExtVectorType>(RHSVecType)) { 10789 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 10790 LHSType, RHSVecType->getElementType(), 10791 RHSType, DiagID)) 10792 return RHSType; 10793 } else { 10794 if (LHS.get()->isLValue() || 10795 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10796 return RHSType; 10797 } 10798 } 10799 10800 // FIXME: The code below also handles conversion between vectors and 10801 // non-scalars, we should break this down into fine grained specific checks 10802 // and emit proper diagnostics. 10803 QualType VecType = LHSVecType ? LHSType : RHSType; 10804 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 10805 QualType OtherType = LHSVecType ? RHSType : LHSType; 10806 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 10807 if (isLaxVectorConversion(OtherType, VecType)) { 10808 if (anyAltivecTypes(RHSType, LHSType) && 10809 !areSameVectorElemTypes(RHSType, LHSType)) 10810 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType; 10811 // If we're allowing lax vector conversions, only the total (data) size 10812 // needs to be the same. For non compound assignment, if one of the types is 10813 // scalar, the result is always the vector type. 10814 if (!IsCompAssign) { 10815 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 10816 return VecType; 10817 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 10818 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 10819 // type. Note that this is already done by non-compound assignments in 10820 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 10821 // <1 x T> -> T. The result is also a vector type. 10822 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 10823 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 10824 ExprResult *RHSExpr = &RHS; 10825 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 10826 return VecType; 10827 } 10828 } 10829 10830 // Okay, the expression is invalid. 10831 10832 // If there's a non-vector, non-real operand, diagnose that. 10833 if ((!RHSVecType && !RHSType->isRealType()) || 10834 (!LHSVecType && !LHSType->isRealType())) { 10835 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10836 << LHSType << RHSType 10837 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10838 return QualType(); 10839 } 10840 10841 // OpenCL V1.1 6.2.6.p1: 10842 // If the operands are of more than one vector type, then an error shall 10843 // occur. Implicit conversions between vector types are not permitted, per 10844 // section 6.2.1. 10845 if (getLangOpts().OpenCL && 10846 RHSVecType && isa<ExtVectorType>(RHSVecType) && 10847 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 10848 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 10849 << RHSType; 10850 return QualType(); 10851 } 10852 10853 10854 // If there is a vector type that is not a ExtVector and a scalar, we reach 10855 // this point if scalar could not be converted to the vector's element type 10856 // without truncation. 10857 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 10858 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 10859 QualType Scalar = LHSVecType ? RHSType : LHSType; 10860 QualType Vector = LHSVecType ? LHSType : RHSType; 10861 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 10862 Diag(Loc, 10863 diag::err_typecheck_vector_not_convertable_implict_truncation) 10864 << ScalarOrVector << Scalar << Vector; 10865 10866 return QualType(); 10867 } 10868 10869 // Otherwise, use the generic diagnostic. 10870 Diag(Loc, DiagID) 10871 << LHSType << RHSType 10872 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10873 return QualType(); 10874 } 10875 10876 QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, 10877 SourceLocation Loc, 10878 bool IsCompAssign, 10879 ArithConvKind OperationKind) { 10880 if (!IsCompAssign) { 10881 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10882 if (LHS.isInvalid()) 10883 return QualType(); 10884 } 10885 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10886 if (RHS.isInvalid()) 10887 return QualType(); 10888 10889 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 10890 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 10891 10892 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>(); 10893 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>(); 10894 10895 unsigned DiagID = diag::err_typecheck_invalid_operands; 10896 if ((OperationKind == ACK_Arithmetic) && 10897 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) || 10898 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) { 10899 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 10900 << RHS.get()->getSourceRange(); 10901 return QualType(); 10902 } 10903 10904 if (Context.hasSameType(LHSType, RHSType)) 10905 return LHSType; 10906 10907 if (LHSType->isVLSTBuiltinType() && !RHSType->isVLSTBuiltinType()) { 10908 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 10909 return LHSType; 10910 } 10911 if (RHSType->isVLSTBuiltinType() && !LHSType->isVLSTBuiltinType()) { 10912 if (LHS.get()->isLValue() || 10913 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 10914 return RHSType; 10915 } 10916 10917 if ((!LHSType->isVLSTBuiltinType() && !LHSType->isRealType()) || 10918 (!RHSType->isVLSTBuiltinType() && !RHSType->isRealType())) { 10919 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 10920 << LHSType << RHSType << LHS.get()->getSourceRange() 10921 << RHS.get()->getSourceRange(); 10922 return QualType(); 10923 } 10924 10925 if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() && 10926 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC != 10927 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) { 10928 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 10929 << LHSType << RHSType << LHS.get()->getSourceRange() 10930 << RHS.get()->getSourceRange(); 10931 return QualType(); 10932 } 10933 10934 if (LHSType->isVLSTBuiltinType() || RHSType->isVLSTBuiltinType()) { 10935 QualType Scalar = LHSType->isVLSTBuiltinType() ? RHSType : LHSType; 10936 QualType Vector = LHSType->isVLSTBuiltinType() ? LHSType : RHSType; 10937 bool ScalarOrVector = 10938 LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType(); 10939 10940 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation) 10941 << ScalarOrVector << Scalar << Vector; 10942 10943 return QualType(); 10944 } 10945 10946 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 10947 << RHS.get()->getSourceRange(); 10948 return QualType(); 10949 } 10950 10951 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 10952 // expression. These are mainly cases where the null pointer is used as an 10953 // integer instead of a pointer. 10954 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 10955 SourceLocation Loc, bool IsCompare) { 10956 // The canonical way to check for a GNU null is with isNullPointerConstant, 10957 // but we use a bit of a hack here for speed; this is a relatively 10958 // hot path, and isNullPointerConstant is slow. 10959 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 10960 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 10961 10962 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 10963 10964 // Avoid analyzing cases where the result will either be invalid (and 10965 // diagnosed as such) or entirely valid and not something to warn about. 10966 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 10967 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 10968 return; 10969 10970 // Comparison operations would not make sense with a null pointer no matter 10971 // what the other expression is. 10972 if (!IsCompare) { 10973 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 10974 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 10975 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 10976 return; 10977 } 10978 10979 // The rest of the operations only make sense with a null pointer 10980 // if the other expression is a pointer. 10981 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 10982 NonNullType->canDecayToPointerType()) 10983 return; 10984 10985 S.Diag(Loc, diag::warn_null_in_comparison_operation) 10986 << LHSNull /* LHS is NULL */ << NonNullType 10987 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10988 } 10989 10990 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, 10991 SourceLocation Loc) { 10992 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 10993 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 10994 if (!LUE || !RUE) 10995 return; 10996 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 10997 RUE->getKind() != UETT_SizeOf) 10998 return; 10999 11000 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens(); 11001 QualType LHSTy = LHSArg->getType(); 11002 QualType RHSTy; 11003 11004 if (RUE->isArgumentType()) 11005 RHSTy = RUE->getArgumentType().getNonReferenceType(); 11006 else 11007 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 11008 11009 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) { 11010 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy)) 11011 return; 11012 11013 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 11014 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 11015 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 11016 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here) 11017 << LHSArgDecl; 11018 } 11019 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) { 11020 QualType ArrayElemTy = ArrayTy->getElementType(); 11021 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) || 11022 ArrayElemTy->isDependentType() || RHSTy->isDependentType() || 11023 RHSTy->isReferenceType() || ArrayElemTy->isCharType() || 11024 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy)) 11025 return; 11026 S.Diag(Loc, diag::warn_division_sizeof_array) 11027 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy; 11028 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) { 11029 if (const ValueDecl *LHSArgDecl = DRE->getDecl()) 11030 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here) 11031 << LHSArgDecl; 11032 } 11033 11034 S.Diag(Loc, diag::note_precedence_silence) << RHS; 11035 } 11036 } 11037 11038 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 11039 ExprResult &RHS, 11040 SourceLocation Loc, bool IsDiv) { 11041 // Check for division/remainder by zero. 11042 Expr::EvalResult RHSValue; 11043 if (!RHS.get()->isValueDependent() && 11044 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 11045 RHSValue.Val.getInt() == 0) 11046 S.DiagRuntimeBehavior(Loc, RHS.get(), 11047 S.PDiag(diag::warn_remainder_division_by_zero) 11048 << IsDiv << RHS.get()->getSourceRange()); 11049 } 11050 11051 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 11052 SourceLocation Loc, 11053 bool IsCompAssign, bool IsDiv) { 11054 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11055 11056 QualType LHSTy = LHS.get()->getType(); 11057 QualType RHSTy = RHS.get()->getType(); 11058 if (LHSTy->isVectorType() || RHSTy->isVectorType()) 11059 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 11060 /*AllowBothBool*/ getLangOpts().AltiVec, 11061 /*AllowBoolConversions*/ false, 11062 /*AllowBooleanOperation*/ false, 11063 /*ReportInvalid*/ true); 11064 if (LHSTy->isVLSTBuiltinType() || RHSTy->isVLSTBuiltinType()) 11065 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 11066 ACK_Arithmetic); 11067 if (!IsDiv && 11068 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType())) 11069 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign); 11070 // For division, only matrix-by-scalar is supported. Other combinations with 11071 // matrix types are invalid. 11072 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType()) 11073 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 11074 11075 QualType compType = UsualArithmeticConversions( 11076 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 11077 if (LHS.isInvalid() || RHS.isInvalid()) 11078 return QualType(); 11079 11080 11081 if (compType.isNull() || !compType->isArithmeticType()) 11082 return InvalidOperands(Loc, LHS, RHS); 11083 if (IsDiv) { 11084 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 11085 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc); 11086 } 11087 return compType; 11088 } 11089 11090 QualType Sema::CheckRemainderOperands( 11091 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 11092 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11093 11094 if (LHS.get()->getType()->isVectorType() || 11095 RHS.get()->getType()->isVectorType()) { 11096 if (LHS.get()->getType()->hasIntegerRepresentation() && 11097 RHS.get()->getType()->hasIntegerRepresentation()) 11098 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 11099 /*AllowBothBool*/ getLangOpts().AltiVec, 11100 /*AllowBoolConversions*/ false, 11101 /*AllowBooleanOperation*/ false, 11102 /*ReportInvalid*/ true); 11103 return InvalidOperands(Loc, LHS, RHS); 11104 } 11105 11106 if (LHS.get()->getType()->isVLSTBuiltinType() || 11107 RHS.get()->getType()->isVLSTBuiltinType()) { 11108 if (LHS.get()->getType()->hasIntegerRepresentation() && 11109 RHS.get()->getType()->hasIntegerRepresentation()) 11110 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 11111 ACK_Arithmetic); 11112 11113 return InvalidOperands(Loc, LHS, RHS); 11114 } 11115 11116 QualType compType = UsualArithmeticConversions( 11117 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic); 11118 if (LHS.isInvalid() || RHS.isInvalid()) 11119 return QualType(); 11120 11121 if (compType.isNull() || !compType->isIntegerType()) 11122 return InvalidOperands(Loc, LHS, RHS); 11123 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 11124 return compType; 11125 } 11126 11127 /// Diagnose invalid arithmetic on two void pointers. 11128 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 11129 Expr *LHSExpr, Expr *RHSExpr) { 11130 S.Diag(Loc, S.getLangOpts().CPlusPlus 11131 ? diag::err_typecheck_pointer_arith_void_type 11132 : diag::ext_gnu_void_ptr) 11133 << 1 /* two pointers */ << LHSExpr->getSourceRange() 11134 << RHSExpr->getSourceRange(); 11135 } 11136 11137 /// Diagnose invalid arithmetic on a void pointer. 11138 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 11139 Expr *Pointer) { 11140 S.Diag(Loc, S.getLangOpts().CPlusPlus 11141 ? diag::err_typecheck_pointer_arith_void_type 11142 : diag::ext_gnu_void_ptr) 11143 << 0 /* one pointer */ << Pointer->getSourceRange(); 11144 } 11145 11146 /// Diagnose invalid arithmetic on a null pointer. 11147 /// 11148 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 11149 /// idiom, which we recognize as a GNU extension. 11150 /// 11151 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 11152 Expr *Pointer, bool IsGNUIdiom) { 11153 if (IsGNUIdiom) 11154 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 11155 << Pointer->getSourceRange(); 11156 else 11157 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 11158 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 11159 } 11160 11161 /// Diagnose invalid subraction on a null pointer. 11162 /// 11163 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, 11164 Expr *Pointer, bool BothNull) { 11165 // Null - null is valid in C++ [expr.add]p7 11166 if (BothNull && S.getLangOpts().CPlusPlus) 11167 return; 11168 11169 // Is this s a macro from a system header? 11170 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc)) 11171 return; 11172 11173 S.DiagRuntimeBehavior(Loc, Pointer, 11174 S.PDiag(diag::warn_pointer_sub_null_ptr) 11175 << S.getLangOpts().CPlusPlus 11176 << Pointer->getSourceRange()); 11177 } 11178 11179 /// Diagnose invalid arithmetic on two function pointers. 11180 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 11181 Expr *LHS, Expr *RHS) { 11182 assert(LHS->getType()->isAnyPointerType()); 11183 assert(RHS->getType()->isAnyPointerType()); 11184 S.Diag(Loc, S.getLangOpts().CPlusPlus 11185 ? diag::err_typecheck_pointer_arith_function_type 11186 : diag::ext_gnu_ptr_func_arith) 11187 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 11188 // We only show the second type if it differs from the first. 11189 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 11190 RHS->getType()) 11191 << RHS->getType()->getPointeeType() 11192 << LHS->getSourceRange() << RHS->getSourceRange(); 11193 } 11194 11195 /// Diagnose invalid arithmetic on a function pointer. 11196 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 11197 Expr *Pointer) { 11198 assert(Pointer->getType()->isAnyPointerType()); 11199 S.Diag(Loc, S.getLangOpts().CPlusPlus 11200 ? diag::err_typecheck_pointer_arith_function_type 11201 : diag::ext_gnu_ptr_func_arith) 11202 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 11203 << 0 /* one pointer, so only one type */ 11204 << Pointer->getSourceRange(); 11205 } 11206 11207 /// Emit error if Operand is incomplete pointer type 11208 /// 11209 /// \returns True if pointer has incomplete type 11210 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 11211 Expr *Operand) { 11212 QualType ResType = Operand->getType(); 11213 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 11214 ResType = ResAtomicType->getValueType(); 11215 11216 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 11217 QualType PointeeTy = ResType->getPointeeType(); 11218 return S.RequireCompleteSizedType( 11219 Loc, PointeeTy, 11220 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type, 11221 Operand->getSourceRange()); 11222 } 11223 11224 /// Check the validity of an arithmetic pointer operand. 11225 /// 11226 /// If the operand has pointer type, this code will check for pointer types 11227 /// which are invalid in arithmetic operations. These will be diagnosed 11228 /// appropriately, including whether or not the use is supported as an 11229 /// extension. 11230 /// 11231 /// \returns True when the operand is valid to use (even if as an extension). 11232 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 11233 Expr *Operand) { 11234 QualType ResType = Operand->getType(); 11235 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 11236 ResType = ResAtomicType->getValueType(); 11237 11238 if (!ResType->isAnyPointerType()) return true; 11239 11240 QualType PointeeTy = ResType->getPointeeType(); 11241 if (PointeeTy->isVoidType()) { 11242 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 11243 return !S.getLangOpts().CPlusPlus; 11244 } 11245 if (PointeeTy->isFunctionType()) { 11246 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 11247 return !S.getLangOpts().CPlusPlus; 11248 } 11249 11250 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 11251 11252 return true; 11253 } 11254 11255 /// Check the validity of a binary arithmetic operation w.r.t. pointer 11256 /// operands. 11257 /// 11258 /// This routine will diagnose any invalid arithmetic on pointer operands much 11259 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 11260 /// for emitting a single diagnostic even for operations where both LHS and RHS 11261 /// are (potentially problematic) pointers. 11262 /// 11263 /// \returns True when the operand is valid to use (even if as an extension). 11264 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 11265 Expr *LHSExpr, Expr *RHSExpr) { 11266 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 11267 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 11268 if (!isLHSPointer && !isRHSPointer) return true; 11269 11270 QualType LHSPointeeTy, RHSPointeeTy; 11271 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 11272 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 11273 11274 // if both are pointers check if operation is valid wrt address spaces 11275 if (isLHSPointer && isRHSPointer) { 11276 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) { 11277 S.Diag(Loc, 11278 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 11279 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 11280 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 11281 return false; 11282 } 11283 } 11284 11285 // Check for arithmetic on pointers to incomplete types. 11286 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 11287 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 11288 if (isLHSVoidPtr || isRHSVoidPtr) { 11289 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 11290 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 11291 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 11292 11293 return !S.getLangOpts().CPlusPlus; 11294 } 11295 11296 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 11297 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 11298 if (isLHSFuncPtr || isRHSFuncPtr) { 11299 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 11300 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 11301 RHSExpr); 11302 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 11303 11304 return !S.getLangOpts().CPlusPlus; 11305 } 11306 11307 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 11308 return false; 11309 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 11310 return false; 11311 11312 return true; 11313 } 11314 11315 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 11316 /// literal. 11317 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 11318 Expr *LHSExpr, Expr *RHSExpr) { 11319 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 11320 Expr* IndexExpr = RHSExpr; 11321 if (!StrExpr) { 11322 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 11323 IndexExpr = LHSExpr; 11324 } 11325 11326 bool IsStringPlusInt = StrExpr && 11327 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 11328 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 11329 return; 11330 11331 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 11332 Self.Diag(OpLoc, diag::warn_string_plus_int) 11333 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 11334 11335 // Only print a fixit for "str" + int, not for int + "str". 11336 if (IndexExpr == RHSExpr) { 11337 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 11338 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 11339 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 11340 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 11341 << FixItHint::CreateInsertion(EndLoc, "]"); 11342 } else 11343 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 11344 } 11345 11346 /// Emit a warning when adding a char literal to a string. 11347 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 11348 Expr *LHSExpr, Expr *RHSExpr) { 11349 const Expr *StringRefExpr = LHSExpr; 11350 const CharacterLiteral *CharExpr = 11351 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 11352 11353 if (!CharExpr) { 11354 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 11355 StringRefExpr = RHSExpr; 11356 } 11357 11358 if (!CharExpr || !StringRefExpr) 11359 return; 11360 11361 const QualType StringType = StringRefExpr->getType(); 11362 11363 // Return if not a PointerType. 11364 if (!StringType->isAnyPointerType()) 11365 return; 11366 11367 // Return if not a CharacterType. 11368 if (!StringType->getPointeeType()->isAnyCharacterType()) 11369 return; 11370 11371 ASTContext &Ctx = Self.getASTContext(); 11372 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 11373 11374 const QualType CharType = CharExpr->getType(); 11375 if (!CharType->isAnyCharacterType() && 11376 CharType->isIntegerType() && 11377 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 11378 Self.Diag(OpLoc, diag::warn_string_plus_char) 11379 << DiagRange << Ctx.CharTy; 11380 } else { 11381 Self.Diag(OpLoc, diag::warn_string_plus_char) 11382 << DiagRange << CharExpr->getType(); 11383 } 11384 11385 // Only print a fixit for str + char, not for char + str. 11386 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 11387 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 11388 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 11389 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 11390 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 11391 << FixItHint::CreateInsertion(EndLoc, "]"); 11392 } else { 11393 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 11394 } 11395 } 11396 11397 /// Emit error when two pointers are incompatible. 11398 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 11399 Expr *LHSExpr, Expr *RHSExpr) { 11400 assert(LHSExpr->getType()->isAnyPointerType()); 11401 assert(RHSExpr->getType()->isAnyPointerType()); 11402 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 11403 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 11404 << RHSExpr->getSourceRange(); 11405 } 11406 11407 // C99 6.5.6 11408 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 11409 SourceLocation Loc, BinaryOperatorKind Opc, 11410 QualType* CompLHSTy) { 11411 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11412 11413 if (LHS.get()->getType()->isVectorType() || 11414 RHS.get()->getType()->isVectorType()) { 11415 QualType compType = 11416 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy, 11417 /*AllowBothBool*/ getLangOpts().AltiVec, 11418 /*AllowBoolConversions*/ getLangOpts().ZVector, 11419 /*AllowBooleanOperation*/ false, 11420 /*ReportInvalid*/ true); 11421 if (CompLHSTy) *CompLHSTy = compType; 11422 return compType; 11423 } 11424 11425 if (LHS.get()->getType()->isVLSTBuiltinType() || 11426 RHS.get()->getType()->isVLSTBuiltinType()) { 11427 QualType compType = 11428 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic); 11429 if (CompLHSTy) 11430 *CompLHSTy = compType; 11431 return compType; 11432 } 11433 11434 if (LHS.get()->getType()->isConstantMatrixType() || 11435 RHS.get()->getType()->isConstantMatrixType()) { 11436 QualType compType = 11437 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 11438 if (CompLHSTy) 11439 *CompLHSTy = compType; 11440 return compType; 11441 } 11442 11443 QualType compType = UsualArithmeticConversions( 11444 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 11445 if (LHS.isInvalid() || RHS.isInvalid()) 11446 return QualType(); 11447 11448 // Diagnose "string literal" '+' int and string '+' "char literal". 11449 if (Opc == BO_Add) { 11450 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 11451 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 11452 } 11453 11454 // handle the common case first (both operands are arithmetic). 11455 if (!compType.isNull() && compType->isArithmeticType()) { 11456 if (CompLHSTy) *CompLHSTy = compType; 11457 return compType; 11458 } 11459 11460 // Type-checking. Ultimately the pointer's going to be in PExp; 11461 // note that we bias towards the LHS being the pointer. 11462 Expr *PExp = LHS.get(), *IExp = RHS.get(); 11463 11464 bool isObjCPointer; 11465 if (PExp->getType()->isPointerType()) { 11466 isObjCPointer = false; 11467 } else if (PExp->getType()->isObjCObjectPointerType()) { 11468 isObjCPointer = true; 11469 } else { 11470 std::swap(PExp, IExp); 11471 if (PExp->getType()->isPointerType()) { 11472 isObjCPointer = false; 11473 } else if (PExp->getType()->isObjCObjectPointerType()) { 11474 isObjCPointer = true; 11475 } else { 11476 return InvalidOperands(Loc, LHS, RHS); 11477 } 11478 } 11479 assert(PExp->getType()->isAnyPointerType()); 11480 11481 if (!IExp->getType()->isIntegerType()) 11482 return InvalidOperands(Loc, LHS, RHS); 11483 11484 // Adding to a null pointer results in undefined behavior. 11485 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 11486 Context, Expr::NPC_ValueDependentIsNotNull)) { 11487 // In C++ adding zero to a null pointer is defined. 11488 Expr::EvalResult KnownVal; 11489 if (!getLangOpts().CPlusPlus || 11490 (!IExp->isValueDependent() && 11491 (!IExp->EvaluateAsInt(KnownVal, Context) || 11492 KnownVal.Val.getInt() != 0))) { 11493 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 11494 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 11495 Context, BO_Add, PExp, IExp); 11496 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 11497 } 11498 } 11499 11500 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 11501 return QualType(); 11502 11503 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 11504 return QualType(); 11505 11506 // Check array bounds for pointer arithemtic 11507 CheckArrayAccess(PExp, IExp); 11508 11509 if (CompLHSTy) { 11510 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 11511 if (LHSTy.isNull()) { 11512 LHSTy = LHS.get()->getType(); 11513 if (Context.isPromotableIntegerType(LHSTy)) 11514 LHSTy = Context.getPromotedIntegerType(LHSTy); 11515 } 11516 *CompLHSTy = LHSTy; 11517 } 11518 11519 return PExp->getType(); 11520 } 11521 11522 // C99 6.5.6 11523 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 11524 SourceLocation Loc, 11525 QualType* CompLHSTy) { 11526 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11527 11528 if (LHS.get()->getType()->isVectorType() || 11529 RHS.get()->getType()->isVectorType()) { 11530 QualType compType = 11531 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy, 11532 /*AllowBothBool*/ getLangOpts().AltiVec, 11533 /*AllowBoolConversions*/ getLangOpts().ZVector, 11534 /*AllowBooleanOperation*/ false, 11535 /*ReportInvalid*/ true); 11536 if (CompLHSTy) *CompLHSTy = compType; 11537 return compType; 11538 } 11539 11540 if (LHS.get()->getType()->isVLSTBuiltinType() || 11541 RHS.get()->getType()->isVLSTBuiltinType()) { 11542 QualType compType = 11543 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic); 11544 if (CompLHSTy) 11545 *CompLHSTy = compType; 11546 return compType; 11547 } 11548 11549 if (LHS.get()->getType()->isConstantMatrixType() || 11550 RHS.get()->getType()->isConstantMatrixType()) { 11551 QualType compType = 11552 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy); 11553 if (CompLHSTy) 11554 *CompLHSTy = compType; 11555 return compType; 11556 } 11557 11558 QualType compType = UsualArithmeticConversions( 11559 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic); 11560 if (LHS.isInvalid() || RHS.isInvalid()) 11561 return QualType(); 11562 11563 // Enforce type constraints: C99 6.5.6p3. 11564 11565 // Handle the common case first (both operands are arithmetic). 11566 if (!compType.isNull() && compType->isArithmeticType()) { 11567 if (CompLHSTy) *CompLHSTy = compType; 11568 return compType; 11569 } 11570 11571 // Either ptr - int or ptr - ptr. 11572 if (LHS.get()->getType()->isAnyPointerType()) { 11573 QualType lpointee = LHS.get()->getType()->getPointeeType(); 11574 11575 // Diagnose bad cases where we step over interface counts. 11576 if (LHS.get()->getType()->isObjCObjectPointerType() && 11577 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 11578 return QualType(); 11579 11580 // The result type of a pointer-int computation is the pointer type. 11581 if (RHS.get()->getType()->isIntegerType()) { 11582 // Subtracting from a null pointer should produce a warning. 11583 // The last argument to the diagnose call says this doesn't match the 11584 // GNU int-to-pointer idiom. 11585 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 11586 Expr::NPC_ValueDependentIsNotNull)) { 11587 // In C++ adding zero to a null pointer is defined. 11588 Expr::EvalResult KnownVal; 11589 if (!getLangOpts().CPlusPlus || 11590 (!RHS.get()->isValueDependent() && 11591 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 11592 KnownVal.Val.getInt() != 0))) { 11593 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 11594 } 11595 } 11596 11597 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 11598 return QualType(); 11599 11600 // Check array bounds for pointer arithemtic 11601 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 11602 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 11603 11604 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 11605 return LHS.get()->getType(); 11606 } 11607 11608 // Handle pointer-pointer subtractions. 11609 if (const PointerType *RHSPTy 11610 = RHS.get()->getType()->getAs<PointerType>()) { 11611 QualType rpointee = RHSPTy->getPointeeType(); 11612 11613 if (getLangOpts().CPlusPlus) { 11614 // Pointee types must be the same: C++ [expr.add] 11615 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 11616 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 11617 } 11618 } else { 11619 // Pointee types must be compatible C99 6.5.6p3 11620 if (!Context.typesAreCompatible( 11621 Context.getCanonicalType(lpointee).getUnqualifiedType(), 11622 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 11623 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 11624 return QualType(); 11625 } 11626 } 11627 11628 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 11629 LHS.get(), RHS.get())) 11630 return QualType(); 11631 11632 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant( 11633 Context, Expr::NPC_ValueDependentIsNotNull); 11634 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant( 11635 Context, Expr::NPC_ValueDependentIsNotNull); 11636 11637 // Subtracting nullptr or from nullptr is suspect 11638 if (LHSIsNullPtr) 11639 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr); 11640 if (RHSIsNullPtr) 11641 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr); 11642 11643 // The pointee type may have zero size. As an extension, a structure or 11644 // union may have zero size or an array may have zero length. In this 11645 // case subtraction does not make sense. 11646 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 11647 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 11648 if (ElementSize.isZero()) { 11649 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 11650 << rpointee.getUnqualifiedType() 11651 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11652 } 11653 } 11654 11655 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 11656 return Context.getPointerDiffType(); 11657 } 11658 } 11659 11660 return InvalidOperands(Loc, LHS, RHS); 11661 } 11662 11663 static bool isScopedEnumerationType(QualType T) { 11664 if (const EnumType *ET = T->getAs<EnumType>()) 11665 return ET->getDecl()->isScoped(); 11666 return false; 11667 } 11668 11669 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 11670 SourceLocation Loc, BinaryOperatorKind Opc, 11671 QualType LHSType) { 11672 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 11673 // so skip remaining warnings as we don't want to modify values within Sema. 11674 if (S.getLangOpts().OpenCL) 11675 return; 11676 11677 // Check right/shifter operand 11678 Expr::EvalResult RHSResult; 11679 if (RHS.get()->isValueDependent() || 11680 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 11681 return; 11682 llvm::APSInt Right = RHSResult.Val.getInt(); 11683 11684 if (Right.isNegative()) { 11685 S.DiagRuntimeBehavior(Loc, RHS.get(), 11686 S.PDiag(diag::warn_shift_negative) 11687 << RHS.get()->getSourceRange()); 11688 return; 11689 } 11690 11691 QualType LHSExprType = LHS.get()->getType(); 11692 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType); 11693 if (LHSExprType->isBitIntType()) 11694 LeftSize = S.Context.getIntWidth(LHSExprType); 11695 else if (LHSExprType->isFixedPointType()) { 11696 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType); 11697 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding(); 11698 } 11699 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize); 11700 if (Right.uge(LeftBits)) { 11701 S.DiagRuntimeBehavior(Loc, RHS.get(), 11702 S.PDiag(diag::warn_shift_gt_typewidth) 11703 << RHS.get()->getSourceRange()); 11704 return; 11705 } 11706 11707 // FIXME: We probably need to handle fixed point types specially here. 11708 if (Opc != BO_Shl || LHSExprType->isFixedPointType()) 11709 return; 11710 11711 // When left shifting an ICE which is signed, we can check for overflow which 11712 // according to C++ standards prior to C++2a has undefined behavior 11713 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one 11714 // more than the maximum value representable in the result type, so never 11715 // warn for those. (FIXME: Unsigned left-shift overflow in a constant 11716 // expression is still probably a bug.) 11717 Expr::EvalResult LHSResult; 11718 if (LHS.get()->isValueDependent() || 11719 LHSType->hasUnsignedIntegerRepresentation() || 11720 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 11721 return; 11722 llvm::APSInt Left = LHSResult.Val.getInt(); 11723 11724 // Don't warn if signed overflow is defined, then all the rest of the 11725 // diagnostics will not be triggered because the behavior is defined. 11726 // Also don't warn in C++20 mode (and newer), as signed left shifts 11727 // always wrap and never overflow. 11728 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20) 11729 return; 11730 11731 // If LHS does not have a non-negative value then, the 11732 // behavior is undefined before C++2a. Warn about it. 11733 if (Left.isNegative()) { 11734 S.DiagRuntimeBehavior(Loc, LHS.get(), 11735 S.PDiag(diag::warn_shift_lhs_negative) 11736 << LHS.get()->getSourceRange()); 11737 return; 11738 } 11739 11740 llvm::APInt ResultBits = 11741 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 11742 if (LeftBits.uge(ResultBits)) 11743 return; 11744 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 11745 Result = Result.shl(Right); 11746 11747 // Print the bit representation of the signed integer as an unsigned 11748 // hexadecimal number. 11749 SmallString<40> HexResult; 11750 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 11751 11752 // If we are only missing a sign bit, this is less likely to result in actual 11753 // bugs -- if the result is cast back to an unsigned type, it will have the 11754 // expected value. Thus we place this behind a different warning that can be 11755 // turned off separately if needed. 11756 if (LeftBits == ResultBits - 1) { 11757 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 11758 << HexResult << LHSType 11759 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11760 return; 11761 } 11762 11763 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 11764 << HexResult.str() << Result.getMinSignedBits() << LHSType 11765 << Left.getBitWidth() << LHS.get()->getSourceRange() 11766 << RHS.get()->getSourceRange(); 11767 } 11768 11769 /// Return the resulting type when a vector is shifted 11770 /// by a scalar or vector shift amount. 11771 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 11772 SourceLocation Loc, bool IsCompAssign) { 11773 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 11774 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 11775 !LHS.get()->getType()->isVectorType()) { 11776 S.Diag(Loc, diag::err_shift_rhs_only_vector) 11777 << RHS.get()->getType() << LHS.get()->getType() 11778 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11779 return QualType(); 11780 } 11781 11782 if (!IsCompAssign) { 11783 LHS = S.UsualUnaryConversions(LHS.get()); 11784 if (LHS.isInvalid()) return QualType(); 11785 } 11786 11787 RHS = S.UsualUnaryConversions(RHS.get()); 11788 if (RHS.isInvalid()) return QualType(); 11789 11790 QualType LHSType = LHS.get()->getType(); 11791 // Note that LHS might be a scalar because the routine calls not only in 11792 // OpenCL case. 11793 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 11794 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 11795 11796 // Note that RHS might not be a vector. 11797 QualType RHSType = RHS.get()->getType(); 11798 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 11799 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 11800 11801 // Do not allow shifts for boolean vectors. 11802 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) || 11803 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) { 11804 S.Diag(Loc, diag::err_typecheck_invalid_operands) 11805 << LHS.get()->getType() << RHS.get()->getType() 11806 << LHS.get()->getSourceRange(); 11807 return QualType(); 11808 } 11809 11810 // The operands need to be integers. 11811 if (!LHSEleType->isIntegerType()) { 11812 S.Diag(Loc, diag::err_typecheck_expect_int) 11813 << LHS.get()->getType() << LHS.get()->getSourceRange(); 11814 return QualType(); 11815 } 11816 11817 if (!RHSEleType->isIntegerType()) { 11818 S.Diag(Loc, diag::err_typecheck_expect_int) 11819 << RHS.get()->getType() << RHS.get()->getSourceRange(); 11820 return QualType(); 11821 } 11822 11823 if (!LHSVecTy) { 11824 assert(RHSVecTy); 11825 if (IsCompAssign) 11826 return RHSType; 11827 if (LHSEleType != RHSEleType) { 11828 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 11829 LHSEleType = RHSEleType; 11830 } 11831 QualType VecTy = 11832 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 11833 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 11834 LHSType = VecTy; 11835 } else if (RHSVecTy) { 11836 // OpenCL v1.1 s6.3.j says that for vector types, the operators 11837 // are applied component-wise. So if RHS is a vector, then ensure 11838 // that the number of elements is the same as LHS... 11839 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 11840 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11841 << LHS.get()->getType() << RHS.get()->getType() 11842 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11843 return QualType(); 11844 } 11845 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 11846 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 11847 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 11848 if (LHSBT != RHSBT && 11849 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 11850 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 11851 << LHS.get()->getType() << RHS.get()->getType() 11852 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 11853 } 11854 } 11855 } else { 11856 // ...else expand RHS to match the number of elements in LHS. 11857 QualType VecTy = 11858 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 11859 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11860 } 11861 11862 return LHSType; 11863 } 11864 11865 static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, 11866 ExprResult &RHS, SourceLocation Loc, 11867 bool IsCompAssign) { 11868 if (!IsCompAssign) { 11869 LHS = S.UsualUnaryConversions(LHS.get()); 11870 if (LHS.isInvalid()) 11871 return QualType(); 11872 } 11873 11874 RHS = S.UsualUnaryConversions(RHS.get()); 11875 if (RHS.isInvalid()) 11876 return QualType(); 11877 11878 QualType LHSType = LHS.get()->getType(); 11879 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>(); 11880 QualType LHSEleType = LHSType->isVLSTBuiltinType() 11881 ? LHSBuiltinTy->getSveEltType(S.getASTContext()) 11882 : LHSType; 11883 11884 // Note that RHS might not be a vector 11885 QualType RHSType = RHS.get()->getType(); 11886 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>(); 11887 QualType RHSEleType = RHSType->isVLSTBuiltinType() 11888 ? RHSBuiltinTy->getSveEltType(S.getASTContext()) 11889 : RHSType; 11890 11891 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) || 11892 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) { 11893 S.Diag(Loc, diag::err_typecheck_invalid_operands) 11894 << LHSType << RHSType << LHS.get()->getSourceRange(); 11895 return QualType(); 11896 } 11897 11898 if (!LHSEleType->isIntegerType()) { 11899 S.Diag(Loc, diag::err_typecheck_expect_int) 11900 << LHS.get()->getType() << LHS.get()->getSourceRange(); 11901 return QualType(); 11902 } 11903 11904 if (!RHSEleType->isIntegerType()) { 11905 S.Diag(Loc, diag::err_typecheck_expect_int) 11906 << RHS.get()->getType() << RHS.get()->getSourceRange(); 11907 return QualType(); 11908 } 11909 11910 if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() && 11911 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC != 11912 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) { 11913 S.Diag(Loc, diag::err_typecheck_invalid_operands) 11914 << LHSType << RHSType << LHS.get()->getSourceRange() 11915 << RHS.get()->getSourceRange(); 11916 return QualType(); 11917 } 11918 11919 if (!LHSType->isVLSTBuiltinType()) { 11920 assert(RHSType->isVLSTBuiltinType()); 11921 if (IsCompAssign) 11922 return RHSType; 11923 if (LHSEleType != RHSEleType) { 11924 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast); 11925 LHSEleType = RHSEleType; 11926 } 11927 const llvm::ElementCount VecSize = 11928 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC; 11929 QualType VecTy = 11930 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue()); 11931 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat); 11932 LHSType = VecTy; 11933 } else if (RHSBuiltinTy && RHSBuiltinTy->isVLSTBuiltinType()) { 11934 if (S.Context.getTypeSize(RHSBuiltinTy) != 11935 S.Context.getTypeSize(LHSBuiltinTy)) { 11936 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 11937 << LHSType << RHSType << LHS.get()->getSourceRange() 11938 << RHS.get()->getSourceRange(); 11939 return QualType(); 11940 } 11941 } else { 11942 const llvm::ElementCount VecSize = 11943 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC; 11944 if (LHSEleType != RHSEleType) { 11945 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast); 11946 RHSEleType = LHSEleType; 11947 } 11948 QualType VecTy = 11949 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue()); 11950 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 11951 } 11952 11953 return LHSType; 11954 } 11955 11956 // C99 6.5.7 11957 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 11958 SourceLocation Loc, BinaryOperatorKind Opc, 11959 bool IsCompAssign) { 11960 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 11961 11962 // Vector shifts promote their scalar inputs to vector type. 11963 if (LHS.get()->getType()->isVectorType() || 11964 RHS.get()->getType()->isVectorType()) { 11965 if (LangOpts.ZVector) { 11966 // The shift operators for the z vector extensions work basically 11967 // like general shifts, except that neither the LHS nor the RHS is 11968 // allowed to be a "vector bool". 11969 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 11970 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 11971 return InvalidOperands(Loc, LHS, RHS); 11972 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 11973 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 11974 return InvalidOperands(Loc, LHS, RHS); 11975 } 11976 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11977 } 11978 11979 if (LHS.get()->getType()->isVLSTBuiltinType() || 11980 RHS.get()->getType()->isVLSTBuiltinType()) 11981 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 11982 11983 // Shifts don't perform usual arithmetic conversions, they just do integer 11984 // promotions on each operand. C99 6.5.7p3 11985 11986 // For the LHS, do usual unary conversions, but then reset them away 11987 // if this is a compound assignment. 11988 ExprResult OldLHS = LHS; 11989 LHS = UsualUnaryConversions(LHS.get()); 11990 if (LHS.isInvalid()) 11991 return QualType(); 11992 QualType LHSType = LHS.get()->getType(); 11993 if (IsCompAssign) LHS = OldLHS; 11994 11995 // The RHS is simpler. 11996 RHS = UsualUnaryConversions(RHS.get()); 11997 if (RHS.isInvalid()) 11998 return QualType(); 11999 QualType RHSType = RHS.get()->getType(); 12000 12001 // C99 6.5.7p2: Each of the operands shall have integer type. 12002 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point. 12003 if ((!LHSType->isFixedPointOrIntegerType() && 12004 !LHSType->hasIntegerRepresentation()) || 12005 !RHSType->hasIntegerRepresentation()) 12006 return InvalidOperands(Loc, LHS, RHS); 12007 12008 // C++0x: Don't allow scoped enums. FIXME: Use something better than 12009 // hasIntegerRepresentation() above instead of this. 12010 if (isScopedEnumerationType(LHSType) || 12011 isScopedEnumerationType(RHSType)) { 12012 return InvalidOperands(Loc, LHS, RHS); 12013 } 12014 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 12015 12016 // "The type of the result is that of the promoted left operand." 12017 return LHSType; 12018 } 12019 12020 /// Diagnose bad pointer comparisons. 12021 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 12022 ExprResult &LHS, ExprResult &RHS, 12023 bool IsError) { 12024 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 12025 : diag::ext_typecheck_comparison_of_distinct_pointers) 12026 << LHS.get()->getType() << RHS.get()->getType() 12027 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 12028 } 12029 12030 /// Returns false if the pointers are converted to a composite type, 12031 /// true otherwise. 12032 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 12033 ExprResult &LHS, ExprResult &RHS) { 12034 // C++ [expr.rel]p2: 12035 // [...] Pointer conversions (4.10) and qualification 12036 // conversions (4.4) are performed on pointer operands (or on 12037 // a pointer operand and a null pointer constant) to bring 12038 // them to their composite pointer type. [...] 12039 // 12040 // C++ [expr.eq]p1 uses the same notion for (in)equality 12041 // comparisons of pointers. 12042 12043 QualType LHSType = LHS.get()->getType(); 12044 QualType RHSType = RHS.get()->getType(); 12045 assert(LHSType->isPointerType() || RHSType->isPointerType() || 12046 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 12047 12048 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 12049 if (T.isNull()) { 12050 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) && 12051 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType())) 12052 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 12053 else 12054 S.InvalidOperands(Loc, LHS, RHS); 12055 return true; 12056 } 12057 12058 return false; 12059 } 12060 12061 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 12062 ExprResult &LHS, 12063 ExprResult &RHS, 12064 bool IsError) { 12065 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 12066 : diag::ext_typecheck_comparison_of_fptr_to_void) 12067 << LHS.get()->getType() << RHS.get()->getType() 12068 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 12069 } 12070 12071 static bool isObjCObjectLiteral(ExprResult &E) { 12072 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 12073 case Stmt::ObjCArrayLiteralClass: 12074 case Stmt::ObjCDictionaryLiteralClass: 12075 case Stmt::ObjCStringLiteralClass: 12076 case Stmt::ObjCBoxedExprClass: 12077 return true; 12078 default: 12079 // Note that ObjCBoolLiteral is NOT an object literal! 12080 return false; 12081 } 12082 } 12083 12084 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 12085 const ObjCObjectPointerType *Type = 12086 LHS->getType()->getAs<ObjCObjectPointerType>(); 12087 12088 // If this is not actually an Objective-C object, bail out. 12089 if (!Type) 12090 return false; 12091 12092 // Get the LHS object's interface type. 12093 QualType InterfaceType = Type->getPointeeType(); 12094 12095 // If the RHS isn't an Objective-C object, bail out. 12096 if (!RHS->getType()->isObjCObjectPointerType()) 12097 return false; 12098 12099 // Try to find the -isEqual: method. 12100 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 12101 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 12102 InterfaceType, 12103 /*IsInstance=*/true); 12104 if (!Method) { 12105 if (Type->isObjCIdType()) { 12106 // For 'id', just check the global pool. 12107 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 12108 /*receiverId=*/true); 12109 } else { 12110 // Check protocols. 12111 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 12112 /*IsInstance=*/true); 12113 } 12114 } 12115 12116 if (!Method) 12117 return false; 12118 12119 QualType T = Method->parameters()[0]->getType(); 12120 if (!T->isObjCObjectPointerType()) 12121 return false; 12122 12123 QualType R = Method->getReturnType(); 12124 if (!R->isScalarType()) 12125 return false; 12126 12127 return true; 12128 } 12129 12130 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 12131 FromE = FromE->IgnoreParenImpCasts(); 12132 switch (FromE->getStmtClass()) { 12133 default: 12134 break; 12135 case Stmt::ObjCStringLiteralClass: 12136 // "string literal" 12137 return LK_String; 12138 case Stmt::ObjCArrayLiteralClass: 12139 // "array literal" 12140 return LK_Array; 12141 case Stmt::ObjCDictionaryLiteralClass: 12142 // "dictionary literal" 12143 return LK_Dictionary; 12144 case Stmt::BlockExprClass: 12145 return LK_Block; 12146 case Stmt::ObjCBoxedExprClass: { 12147 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 12148 switch (Inner->getStmtClass()) { 12149 case Stmt::IntegerLiteralClass: 12150 case Stmt::FloatingLiteralClass: 12151 case Stmt::CharacterLiteralClass: 12152 case Stmt::ObjCBoolLiteralExprClass: 12153 case Stmt::CXXBoolLiteralExprClass: 12154 // "numeric literal" 12155 return LK_Numeric; 12156 case Stmt::ImplicitCastExprClass: { 12157 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 12158 // Boolean literals can be represented by implicit casts. 12159 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 12160 return LK_Numeric; 12161 break; 12162 } 12163 default: 12164 break; 12165 } 12166 return LK_Boxed; 12167 } 12168 } 12169 return LK_None; 12170 } 12171 12172 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 12173 ExprResult &LHS, ExprResult &RHS, 12174 BinaryOperator::Opcode Opc){ 12175 Expr *Literal; 12176 Expr *Other; 12177 if (isObjCObjectLiteral(LHS)) { 12178 Literal = LHS.get(); 12179 Other = RHS.get(); 12180 } else { 12181 Literal = RHS.get(); 12182 Other = LHS.get(); 12183 } 12184 12185 // Don't warn on comparisons against nil. 12186 Other = Other->IgnoreParenCasts(); 12187 if (Other->isNullPointerConstant(S.getASTContext(), 12188 Expr::NPC_ValueDependentIsNotNull)) 12189 return; 12190 12191 // This should be kept in sync with warn_objc_literal_comparison. 12192 // LK_String should always be after the other literals, since it has its own 12193 // warning flag. 12194 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 12195 assert(LiteralKind != Sema::LK_Block); 12196 if (LiteralKind == Sema::LK_None) { 12197 llvm_unreachable("Unknown Objective-C object literal kind"); 12198 } 12199 12200 if (LiteralKind == Sema::LK_String) 12201 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 12202 << Literal->getSourceRange(); 12203 else 12204 S.Diag(Loc, diag::warn_objc_literal_comparison) 12205 << LiteralKind << Literal->getSourceRange(); 12206 12207 if (BinaryOperator::isEqualityOp(Opc) && 12208 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 12209 SourceLocation Start = LHS.get()->getBeginLoc(); 12210 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 12211 CharSourceRange OpRange = 12212 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 12213 12214 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 12215 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 12216 << FixItHint::CreateReplacement(OpRange, " isEqual:") 12217 << FixItHint::CreateInsertion(End, "]"); 12218 } 12219 } 12220 12221 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 12222 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 12223 ExprResult &RHS, SourceLocation Loc, 12224 BinaryOperatorKind Opc) { 12225 // Check that left hand side is !something. 12226 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 12227 if (!UO || UO->getOpcode() != UO_LNot) return; 12228 12229 // Only check if the right hand side is non-bool arithmetic type. 12230 if (RHS.get()->isKnownToHaveBooleanValue()) return; 12231 12232 // Make sure that the something in !something is not bool. 12233 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 12234 if (SubExpr->isKnownToHaveBooleanValue()) return; 12235 12236 // Emit warning. 12237 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 12238 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 12239 << Loc << IsBitwiseOp; 12240 12241 // First note suggest !(x < y) 12242 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 12243 SourceLocation FirstClose = RHS.get()->getEndLoc(); 12244 FirstClose = S.getLocForEndOfToken(FirstClose); 12245 if (FirstClose.isInvalid()) 12246 FirstOpen = SourceLocation(); 12247 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 12248 << IsBitwiseOp 12249 << FixItHint::CreateInsertion(FirstOpen, "(") 12250 << FixItHint::CreateInsertion(FirstClose, ")"); 12251 12252 // Second note suggests (!x) < y 12253 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 12254 SourceLocation SecondClose = LHS.get()->getEndLoc(); 12255 SecondClose = S.getLocForEndOfToken(SecondClose); 12256 if (SecondClose.isInvalid()) 12257 SecondOpen = SourceLocation(); 12258 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 12259 << FixItHint::CreateInsertion(SecondOpen, "(") 12260 << FixItHint::CreateInsertion(SecondClose, ")"); 12261 } 12262 12263 // Returns true if E refers to a non-weak array. 12264 static bool checkForArray(const Expr *E) { 12265 const ValueDecl *D = nullptr; 12266 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 12267 D = DR->getDecl(); 12268 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 12269 if (Mem->isImplicitAccess()) 12270 D = Mem->getMemberDecl(); 12271 } 12272 if (!D) 12273 return false; 12274 return D->getType()->isArrayType() && !D->isWeak(); 12275 } 12276 12277 /// Diagnose some forms of syntactically-obvious tautological comparison. 12278 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 12279 Expr *LHS, Expr *RHS, 12280 BinaryOperatorKind Opc) { 12281 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 12282 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 12283 12284 QualType LHSType = LHS->getType(); 12285 QualType RHSType = RHS->getType(); 12286 if (LHSType->hasFloatingRepresentation() || 12287 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 12288 S.inTemplateInstantiation()) 12289 return; 12290 12291 // Comparisons between two array types are ill-formed for operator<=>, so 12292 // we shouldn't emit any additional warnings about it. 12293 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 12294 return; 12295 12296 // For non-floating point types, check for self-comparisons of the form 12297 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 12298 // often indicate logic errors in the program. 12299 // 12300 // NOTE: Don't warn about comparison expressions resulting from macro 12301 // expansion. Also don't warn about comparisons which are only self 12302 // comparisons within a template instantiation. The warnings should catch 12303 // obvious cases in the definition of the template anyways. The idea is to 12304 // warn when the typed comparison operator will always evaluate to the same 12305 // result. 12306 12307 // Used for indexing into %select in warn_comparison_always 12308 enum { 12309 AlwaysConstant, 12310 AlwaysTrue, 12311 AlwaysFalse, 12312 AlwaysEqual, // std::strong_ordering::equal from operator<=> 12313 }; 12314 12315 // C++2a [depr.array.comp]: 12316 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two 12317 // operands of array type are deprecated. 12318 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() && 12319 RHSStripped->getType()->isArrayType()) { 12320 S.Diag(Loc, diag::warn_depr_array_comparison) 12321 << LHS->getSourceRange() << RHS->getSourceRange() 12322 << LHSStripped->getType() << RHSStripped->getType(); 12323 // Carry on to produce the tautological comparison warning, if this 12324 // expression is potentially-evaluated, we can resolve the array to a 12325 // non-weak declaration, and so on. 12326 } 12327 12328 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) { 12329 if (Expr::isSameComparisonOperand(LHS, RHS)) { 12330 unsigned Result; 12331 switch (Opc) { 12332 case BO_EQ: 12333 case BO_LE: 12334 case BO_GE: 12335 Result = AlwaysTrue; 12336 break; 12337 case BO_NE: 12338 case BO_LT: 12339 case BO_GT: 12340 Result = AlwaysFalse; 12341 break; 12342 case BO_Cmp: 12343 Result = AlwaysEqual; 12344 break; 12345 default: 12346 Result = AlwaysConstant; 12347 break; 12348 } 12349 S.DiagRuntimeBehavior(Loc, nullptr, 12350 S.PDiag(diag::warn_comparison_always) 12351 << 0 /*self-comparison*/ 12352 << Result); 12353 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) { 12354 // What is it always going to evaluate to? 12355 unsigned Result; 12356 switch (Opc) { 12357 case BO_EQ: // e.g. array1 == array2 12358 Result = AlwaysFalse; 12359 break; 12360 case BO_NE: // e.g. array1 != array2 12361 Result = AlwaysTrue; 12362 break; 12363 default: // e.g. array1 <= array2 12364 // The best we can say is 'a constant' 12365 Result = AlwaysConstant; 12366 break; 12367 } 12368 S.DiagRuntimeBehavior(Loc, nullptr, 12369 S.PDiag(diag::warn_comparison_always) 12370 << 1 /*array comparison*/ 12371 << Result); 12372 } 12373 } 12374 12375 if (isa<CastExpr>(LHSStripped)) 12376 LHSStripped = LHSStripped->IgnoreParenCasts(); 12377 if (isa<CastExpr>(RHSStripped)) 12378 RHSStripped = RHSStripped->IgnoreParenCasts(); 12379 12380 // Warn about comparisons against a string constant (unless the other 12381 // operand is null); the user probably wants string comparison function. 12382 Expr *LiteralString = nullptr; 12383 Expr *LiteralStringStripped = nullptr; 12384 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 12385 !RHSStripped->isNullPointerConstant(S.Context, 12386 Expr::NPC_ValueDependentIsNull)) { 12387 LiteralString = LHS; 12388 LiteralStringStripped = LHSStripped; 12389 } else if ((isa<StringLiteral>(RHSStripped) || 12390 isa<ObjCEncodeExpr>(RHSStripped)) && 12391 !LHSStripped->isNullPointerConstant(S.Context, 12392 Expr::NPC_ValueDependentIsNull)) { 12393 LiteralString = RHS; 12394 LiteralStringStripped = RHSStripped; 12395 } 12396 12397 if (LiteralString) { 12398 S.DiagRuntimeBehavior(Loc, nullptr, 12399 S.PDiag(diag::warn_stringcompare) 12400 << isa<ObjCEncodeExpr>(LiteralStringStripped) 12401 << LiteralString->getSourceRange()); 12402 } 12403 } 12404 12405 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 12406 switch (CK) { 12407 default: { 12408 #ifndef NDEBUG 12409 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 12410 << "\n"; 12411 #endif 12412 llvm_unreachable("unhandled cast kind"); 12413 } 12414 case CK_UserDefinedConversion: 12415 return ICK_Identity; 12416 case CK_LValueToRValue: 12417 return ICK_Lvalue_To_Rvalue; 12418 case CK_ArrayToPointerDecay: 12419 return ICK_Array_To_Pointer; 12420 case CK_FunctionToPointerDecay: 12421 return ICK_Function_To_Pointer; 12422 case CK_IntegralCast: 12423 return ICK_Integral_Conversion; 12424 case CK_FloatingCast: 12425 return ICK_Floating_Conversion; 12426 case CK_IntegralToFloating: 12427 case CK_FloatingToIntegral: 12428 return ICK_Floating_Integral; 12429 case CK_IntegralComplexCast: 12430 case CK_FloatingComplexCast: 12431 case CK_FloatingComplexToIntegralComplex: 12432 case CK_IntegralComplexToFloatingComplex: 12433 return ICK_Complex_Conversion; 12434 case CK_FloatingComplexToReal: 12435 case CK_FloatingRealToComplex: 12436 case CK_IntegralComplexToReal: 12437 case CK_IntegralRealToComplex: 12438 return ICK_Complex_Real; 12439 } 12440 } 12441 12442 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 12443 QualType FromType, 12444 SourceLocation Loc) { 12445 // Check for a narrowing implicit conversion. 12446 StandardConversionSequence SCS; 12447 SCS.setAsIdentityConversion(); 12448 SCS.setToType(0, FromType); 12449 SCS.setToType(1, ToType); 12450 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 12451 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 12452 12453 APValue PreNarrowingValue; 12454 QualType PreNarrowingType; 12455 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 12456 PreNarrowingType, 12457 /*IgnoreFloatToIntegralConversion*/ true)) { 12458 case NK_Dependent_Narrowing: 12459 // Implicit conversion to a narrower type, but the expression is 12460 // value-dependent so we can't tell whether it's actually narrowing. 12461 case NK_Not_Narrowing: 12462 return false; 12463 12464 case NK_Constant_Narrowing: 12465 // Implicit conversion to a narrower type, and the value is not a constant 12466 // expression. 12467 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 12468 << /*Constant*/ 1 12469 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 12470 return true; 12471 12472 case NK_Variable_Narrowing: 12473 // Implicit conversion to a narrower type, and the value is not a constant 12474 // expression. 12475 case NK_Type_Narrowing: 12476 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 12477 << /*Constant*/ 0 << FromType << ToType; 12478 // TODO: It's not a constant expression, but what if the user intended it 12479 // to be? Can we produce notes to help them figure out why it isn't? 12480 return true; 12481 } 12482 llvm_unreachable("unhandled case in switch"); 12483 } 12484 12485 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 12486 ExprResult &LHS, 12487 ExprResult &RHS, 12488 SourceLocation Loc) { 12489 QualType LHSType = LHS.get()->getType(); 12490 QualType RHSType = RHS.get()->getType(); 12491 // Dig out the original argument type and expression before implicit casts 12492 // were applied. These are the types/expressions we need to check the 12493 // [expr.spaceship] requirements against. 12494 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 12495 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 12496 QualType LHSStrippedType = LHSStripped.get()->getType(); 12497 QualType RHSStrippedType = RHSStripped.get()->getType(); 12498 12499 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 12500 // other is not, the program is ill-formed. 12501 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 12502 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 12503 return QualType(); 12504 } 12505 12506 // FIXME: Consider combining this with checkEnumArithmeticConversions. 12507 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 12508 RHSStrippedType->isEnumeralType(); 12509 if (NumEnumArgs == 1) { 12510 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 12511 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 12512 if (OtherTy->hasFloatingRepresentation()) { 12513 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 12514 return QualType(); 12515 } 12516 } 12517 if (NumEnumArgs == 2) { 12518 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 12519 // type E, the operator yields the result of converting the operands 12520 // to the underlying type of E and applying <=> to the converted operands. 12521 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 12522 S.InvalidOperands(Loc, LHS, RHS); 12523 return QualType(); 12524 } 12525 QualType IntType = 12526 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType(); 12527 assert(IntType->isArithmeticType()); 12528 12529 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 12530 // promote the boolean type, and all other promotable integer types, to 12531 // avoid this. 12532 if (S.Context.isPromotableIntegerType(IntType)) 12533 IntType = S.Context.getPromotedIntegerType(IntType); 12534 12535 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 12536 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 12537 LHSType = RHSType = IntType; 12538 } 12539 12540 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 12541 // usual arithmetic conversions are applied to the operands. 12542 QualType Type = 12543 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 12544 if (LHS.isInvalid() || RHS.isInvalid()) 12545 return QualType(); 12546 if (Type.isNull()) 12547 return S.InvalidOperands(Loc, LHS, RHS); 12548 12549 std::optional<ComparisonCategoryType> CCT = 12550 getComparisonCategoryForBuiltinCmp(Type); 12551 if (!CCT) 12552 return S.InvalidOperands(Loc, LHS, RHS); 12553 12554 bool HasNarrowing = checkThreeWayNarrowingConversion( 12555 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 12556 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 12557 RHS.get()->getBeginLoc()); 12558 if (HasNarrowing) 12559 return QualType(); 12560 12561 assert(!Type.isNull() && "composite type for <=> has not been set"); 12562 12563 return S.CheckComparisonCategoryType( 12564 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression); 12565 } 12566 12567 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 12568 ExprResult &RHS, 12569 SourceLocation Loc, 12570 BinaryOperatorKind Opc) { 12571 if (Opc == BO_Cmp) 12572 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 12573 12574 // C99 6.5.8p3 / C99 6.5.9p4 12575 QualType Type = 12576 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison); 12577 if (LHS.isInvalid() || RHS.isInvalid()) 12578 return QualType(); 12579 if (Type.isNull()) 12580 return S.InvalidOperands(Loc, LHS, RHS); 12581 assert(Type->isArithmeticType() || Type->isEnumeralType()); 12582 12583 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 12584 return S.InvalidOperands(Loc, LHS, RHS); 12585 12586 // Check for comparisons of floating point operands using != and ==. 12587 if (Type->hasFloatingRepresentation()) 12588 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc); 12589 12590 // The result of comparisons is 'bool' in C++, 'int' in C. 12591 return S.Context.getLogicalOperationType(); 12592 } 12593 12594 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) { 12595 if (!NullE.get()->getType()->isAnyPointerType()) 12596 return; 12597 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1; 12598 if (!E.get()->getType()->isAnyPointerType() && 12599 E.get()->isNullPointerConstant(Context, 12600 Expr::NPC_ValueDependentIsNotNull) == 12601 Expr::NPCK_ZeroExpression) { 12602 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) { 12603 if (CL->getValue() == 0) 12604 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 12605 << NullValue 12606 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 12607 NullValue ? "NULL" : "(void *)0"); 12608 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) { 12609 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 12610 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType(); 12611 if (T == Context.CharTy) 12612 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare) 12613 << NullValue 12614 << FixItHint::CreateReplacement(E.get()->getExprLoc(), 12615 NullValue ? "NULL" : "(void *)0"); 12616 } 12617 } 12618 } 12619 12620 // C99 6.5.8, C++ [expr.rel] 12621 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 12622 SourceLocation Loc, 12623 BinaryOperatorKind Opc) { 12624 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 12625 bool IsThreeWay = Opc == BO_Cmp; 12626 bool IsOrdered = IsRelational || IsThreeWay; 12627 auto IsAnyPointerType = [](ExprResult E) { 12628 QualType Ty = E.get()->getType(); 12629 return Ty->isPointerType() || Ty->isMemberPointerType(); 12630 }; 12631 12632 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 12633 // type, array-to-pointer, ..., conversions are performed on both operands to 12634 // bring them to their composite type. 12635 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 12636 // any type-related checks. 12637 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 12638 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 12639 if (LHS.isInvalid()) 12640 return QualType(); 12641 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 12642 if (RHS.isInvalid()) 12643 return QualType(); 12644 } else { 12645 LHS = DefaultLvalueConversion(LHS.get()); 12646 if (LHS.isInvalid()) 12647 return QualType(); 12648 RHS = DefaultLvalueConversion(RHS.get()); 12649 if (RHS.isInvalid()) 12650 return QualType(); 12651 } 12652 12653 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true); 12654 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) { 12655 CheckPtrComparisonWithNullChar(LHS, RHS); 12656 CheckPtrComparisonWithNullChar(RHS, LHS); 12657 } 12658 12659 // Handle vector comparisons separately. 12660 if (LHS.get()->getType()->isVectorType() || 12661 RHS.get()->getType()->isVectorType()) 12662 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 12663 12664 if (LHS.get()->getType()->isVLSTBuiltinType() || 12665 RHS.get()->getType()->isVLSTBuiltinType()) 12666 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc); 12667 12668 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 12669 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 12670 12671 QualType LHSType = LHS.get()->getType(); 12672 QualType RHSType = RHS.get()->getType(); 12673 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 12674 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 12675 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 12676 12677 const Expr::NullPointerConstantKind LHSNullKind = 12678 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 12679 const Expr::NullPointerConstantKind RHSNullKind = 12680 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 12681 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 12682 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 12683 12684 auto computeResultTy = [&]() { 12685 if (Opc != BO_Cmp) 12686 return Context.getLogicalOperationType(); 12687 assert(getLangOpts().CPlusPlus); 12688 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 12689 12690 QualType CompositeTy = LHS.get()->getType(); 12691 assert(!CompositeTy->isReferenceType()); 12692 12693 std::optional<ComparisonCategoryType> CCT = 12694 getComparisonCategoryForBuiltinCmp(CompositeTy); 12695 if (!CCT) 12696 return InvalidOperands(Loc, LHS, RHS); 12697 12698 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) { 12699 // P0946R0: Comparisons between a null pointer constant and an object 12700 // pointer result in std::strong_equality, which is ill-formed under 12701 // P1959R0. 12702 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero) 12703 << (LHSIsNull ? LHS.get()->getSourceRange() 12704 : RHS.get()->getSourceRange()); 12705 return QualType(); 12706 } 12707 12708 return CheckComparisonCategoryType( 12709 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression); 12710 }; 12711 12712 if (!IsOrdered && LHSIsNull != RHSIsNull) { 12713 bool IsEquality = Opc == BO_EQ; 12714 if (RHSIsNull) 12715 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 12716 RHS.get()->getSourceRange()); 12717 else 12718 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 12719 LHS.get()->getSourceRange()); 12720 } 12721 12722 if (IsOrdered && LHSType->isFunctionPointerType() && 12723 RHSType->isFunctionPointerType()) { 12724 // Valid unless a relational comparison of function pointers 12725 bool IsError = Opc == BO_Cmp; 12726 auto DiagID = 12727 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers 12728 : getLangOpts().CPlusPlus 12729 ? diag::warn_typecheck_ordered_comparison_of_function_pointers 12730 : diag::ext_typecheck_ordered_comparison_of_function_pointers; 12731 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange() 12732 << RHS.get()->getSourceRange(); 12733 if (IsError) 12734 return QualType(); 12735 } 12736 12737 if ((LHSType->isIntegerType() && !LHSIsNull) || 12738 (RHSType->isIntegerType() && !RHSIsNull)) { 12739 // Skip normal pointer conversion checks in this case; we have better 12740 // diagnostics for this below. 12741 } else if (getLangOpts().CPlusPlus) { 12742 // Equality comparison of a function pointer to a void pointer is invalid, 12743 // but we allow it as an extension. 12744 // FIXME: If we really want to allow this, should it be part of composite 12745 // pointer type computation so it works in conditionals too? 12746 if (!IsOrdered && 12747 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 12748 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 12749 // This is a gcc extension compatibility comparison. 12750 // In a SFINAE context, we treat this as a hard error to maintain 12751 // conformance with the C++ standard. 12752 diagnoseFunctionPointerToVoidComparison( 12753 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 12754 12755 if (isSFINAEContext()) 12756 return QualType(); 12757 12758 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12759 return computeResultTy(); 12760 } 12761 12762 // C++ [expr.eq]p2: 12763 // If at least one operand is a pointer [...] bring them to their 12764 // composite pointer type. 12765 // C++ [expr.spaceship]p6 12766 // If at least one of the operands is of pointer type, [...] bring them 12767 // to their composite pointer type. 12768 // C++ [expr.rel]p2: 12769 // If both operands are pointers, [...] bring them to their composite 12770 // pointer type. 12771 // For <=>, the only valid non-pointer types are arrays and functions, and 12772 // we already decayed those, so this is really the same as the relational 12773 // comparison rule. 12774 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 12775 (IsOrdered ? 2 : 1) && 12776 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 12777 RHSType->isObjCObjectPointerType()))) { 12778 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12779 return QualType(); 12780 return computeResultTy(); 12781 } 12782 } else if (LHSType->isPointerType() && 12783 RHSType->isPointerType()) { // C99 6.5.8p2 12784 // All of the following pointer-related warnings are GCC extensions, except 12785 // when handling null pointer constants. 12786 QualType LCanPointeeTy = 12787 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 12788 QualType RCanPointeeTy = 12789 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 12790 12791 // C99 6.5.9p2 and C99 6.5.8p2 12792 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 12793 RCanPointeeTy.getUnqualifiedType())) { 12794 if (IsRelational) { 12795 // Pointers both need to point to complete or incomplete types 12796 if ((LCanPointeeTy->isIncompleteType() != 12797 RCanPointeeTy->isIncompleteType()) && 12798 !getLangOpts().C11) { 12799 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers) 12800 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange() 12801 << LHSType << RHSType << LCanPointeeTy->isIncompleteType() 12802 << RCanPointeeTy->isIncompleteType(); 12803 } 12804 } 12805 } else if (!IsRelational && 12806 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 12807 // Valid unless comparison between non-null pointer and function pointer 12808 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 12809 && !LHSIsNull && !RHSIsNull) 12810 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 12811 /*isError*/false); 12812 } else { 12813 // Invalid 12814 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 12815 } 12816 if (LCanPointeeTy != RCanPointeeTy) { 12817 // Treat NULL constant as a special case in OpenCL. 12818 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 12819 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) { 12820 Diag(Loc, 12821 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 12822 << LHSType << RHSType << 0 /* comparison */ 12823 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 12824 } 12825 } 12826 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 12827 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 12828 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 12829 : CK_BitCast; 12830 if (LHSIsNull && !RHSIsNull) 12831 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 12832 else 12833 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 12834 } 12835 return computeResultTy(); 12836 } 12837 12838 12839 // C++ [expr.eq]p4: 12840 // Two operands of type std::nullptr_t or one operand of type 12841 // std::nullptr_t and the other a null pointer constant compare 12842 // equal. 12843 // C2x 6.5.9p5: 12844 // If both operands have type nullptr_t or one operand has type nullptr_t 12845 // and the other is a null pointer constant, they compare equal. 12846 if (!IsOrdered && LHSIsNull && RHSIsNull) { 12847 if (LHSType->isNullPtrType()) { 12848 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12849 return computeResultTy(); 12850 } 12851 if (RHSType->isNullPtrType()) { 12852 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12853 return computeResultTy(); 12854 } 12855 } 12856 12857 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) { 12858 // C2x 6.5.9p6: 12859 // Otherwise, at least one operand is a pointer. If one is a pointer and 12860 // the other is a null pointer constant, the null pointer constant is 12861 // converted to the type of the pointer. 12862 if (LHSIsNull && RHSType->isPointerType()) { 12863 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12864 return computeResultTy(); 12865 } 12866 if (RHSIsNull && LHSType->isPointerType()) { 12867 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12868 return computeResultTy(); 12869 } 12870 } 12871 12872 // Comparison of Objective-C pointers and block pointers against nullptr_t. 12873 // These aren't covered by the composite pointer type rules. 12874 if (!IsOrdered && RHSType->isNullPtrType() && 12875 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 12876 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12877 return computeResultTy(); 12878 } 12879 if (!IsOrdered && LHSType->isNullPtrType() && 12880 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 12881 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12882 return computeResultTy(); 12883 } 12884 12885 if (getLangOpts().CPlusPlus) { 12886 if (IsRelational && 12887 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 12888 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 12889 // HACK: Relational comparison of nullptr_t against a pointer type is 12890 // invalid per DR583, but we allow it within std::less<> and friends, 12891 // since otherwise common uses of it break. 12892 // FIXME: Consider removing this hack once LWG fixes std::less<> and 12893 // friends to have std::nullptr_t overload candidates. 12894 DeclContext *DC = CurContext; 12895 if (isa<FunctionDecl>(DC)) 12896 DC = DC->getParent(); 12897 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 12898 if (CTSD->isInStdNamespace() && 12899 llvm::StringSwitch<bool>(CTSD->getName()) 12900 .Cases("less", "less_equal", "greater", "greater_equal", true) 12901 .Default(false)) { 12902 if (RHSType->isNullPtrType()) 12903 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 12904 else 12905 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 12906 return computeResultTy(); 12907 } 12908 } 12909 } 12910 12911 // C++ [expr.eq]p2: 12912 // If at least one operand is a pointer to member, [...] bring them to 12913 // their composite pointer type. 12914 if (!IsOrdered && 12915 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 12916 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 12917 return QualType(); 12918 else 12919 return computeResultTy(); 12920 } 12921 } 12922 12923 // Handle block pointer types. 12924 if (!IsOrdered && LHSType->isBlockPointerType() && 12925 RHSType->isBlockPointerType()) { 12926 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 12927 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 12928 12929 if (!LHSIsNull && !RHSIsNull && 12930 !Context.typesAreCompatible(lpointee, rpointee)) { 12931 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12932 << LHSType << RHSType << LHS.get()->getSourceRange() 12933 << RHS.get()->getSourceRange(); 12934 } 12935 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 12936 return computeResultTy(); 12937 } 12938 12939 // Allow block pointers to be compared with null pointer constants. 12940 if (!IsOrdered 12941 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 12942 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 12943 if (!LHSIsNull && !RHSIsNull) { 12944 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 12945 ->getPointeeType()->isVoidType()) 12946 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 12947 ->getPointeeType()->isVoidType()))) 12948 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 12949 << LHSType << RHSType << LHS.get()->getSourceRange() 12950 << RHS.get()->getSourceRange(); 12951 } 12952 if (LHSIsNull && !RHSIsNull) 12953 LHS = ImpCastExprToType(LHS.get(), RHSType, 12954 RHSType->isPointerType() ? CK_BitCast 12955 : CK_AnyPointerToBlockPointerCast); 12956 else 12957 RHS = ImpCastExprToType(RHS.get(), LHSType, 12958 LHSType->isPointerType() ? CK_BitCast 12959 : CK_AnyPointerToBlockPointerCast); 12960 return computeResultTy(); 12961 } 12962 12963 if (LHSType->isObjCObjectPointerType() || 12964 RHSType->isObjCObjectPointerType()) { 12965 const PointerType *LPT = LHSType->getAs<PointerType>(); 12966 const PointerType *RPT = RHSType->getAs<PointerType>(); 12967 if (LPT || RPT) { 12968 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 12969 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 12970 12971 if (!LPtrToVoid && !RPtrToVoid && 12972 !Context.typesAreCompatible(LHSType, RHSType)) { 12973 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 12974 /*isError*/false); 12975 } 12976 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than 12977 // the RHS, but we have test coverage for this behavior. 12978 // FIXME: Consider using convertPointersToCompositeType in C++. 12979 if (LHSIsNull && !RHSIsNull) { 12980 Expr *E = LHS.get(); 12981 if (getLangOpts().ObjCAutoRefCount) 12982 CheckObjCConversion(SourceRange(), RHSType, E, 12983 CCK_ImplicitConversion); 12984 LHS = ImpCastExprToType(E, RHSType, 12985 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12986 } 12987 else { 12988 Expr *E = RHS.get(); 12989 if (getLangOpts().ObjCAutoRefCount) 12990 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 12991 /*Diagnose=*/true, 12992 /*DiagnoseCFAudited=*/false, Opc); 12993 RHS = ImpCastExprToType(E, LHSType, 12994 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 12995 } 12996 return computeResultTy(); 12997 } 12998 if (LHSType->isObjCObjectPointerType() && 12999 RHSType->isObjCObjectPointerType()) { 13000 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 13001 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 13002 /*isError*/false); 13003 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 13004 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 13005 13006 if (LHSIsNull && !RHSIsNull) 13007 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 13008 else 13009 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 13010 return computeResultTy(); 13011 } 13012 13013 if (!IsOrdered && LHSType->isBlockPointerType() && 13014 RHSType->isBlockCompatibleObjCPointerType(Context)) { 13015 LHS = ImpCastExprToType(LHS.get(), RHSType, 13016 CK_BlockPointerToObjCPointerCast); 13017 return computeResultTy(); 13018 } else if (!IsOrdered && 13019 LHSType->isBlockCompatibleObjCPointerType(Context) && 13020 RHSType->isBlockPointerType()) { 13021 RHS = ImpCastExprToType(RHS.get(), LHSType, 13022 CK_BlockPointerToObjCPointerCast); 13023 return computeResultTy(); 13024 } 13025 } 13026 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 13027 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 13028 unsigned DiagID = 0; 13029 bool isError = false; 13030 if (LangOpts.DebuggerSupport) { 13031 // Under a debugger, allow the comparison of pointers to integers, 13032 // since users tend to want to compare addresses. 13033 } else if ((LHSIsNull && LHSType->isIntegerType()) || 13034 (RHSIsNull && RHSType->isIntegerType())) { 13035 if (IsOrdered) { 13036 isError = getLangOpts().CPlusPlus; 13037 DiagID = 13038 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 13039 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 13040 } 13041 } else if (getLangOpts().CPlusPlus) { 13042 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 13043 isError = true; 13044 } else if (IsOrdered) 13045 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 13046 else 13047 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 13048 13049 if (DiagID) { 13050 Diag(Loc, DiagID) 13051 << LHSType << RHSType << LHS.get()->getSourceRange() 13052 << RHS.get()->getSourceRange(); 13053 if (isError) 13054 return QualType(); 13055 } 13056 13057 if (LHSType->isIntegerType()) 13058 LHS = ImpCastExprToType(LHS.get(), RHSType, 13059 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 13060 else 13061 RHS = ImpCastExprToType(RHS.get(), LHSType, 13062 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 13063 return computeResultTy(); 13064 } 13065 13066 // Handle block pointers. 13067 if (!IsOrdered && RHSIsNull 13068 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 13069 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 13070 return computeResultTy(); 13071 } 13072 if (!IsOrdered && LHSIsNull 13073 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 13074 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 13075 return computeResultTy(); 13076 } 13077 13078 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 13079 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 13080 return computeResultTy(); 13081 } 13082 13083 if (LHSType->isQueueT() && RHSType->isQueueT()) { 13084 return computeResultTy(); 13085 } 13086 13087 if (LHSIsNull && RHSType->isQueueT()) { 13088 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 13089 return computeResultTy(); 13090 } 13091 13092 if (LHSType->isQueueT() && RHSIsNull) { 13093 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 13094 return computeResultTy(); 13095 } 13096 } 13097 13098 return InvalidOperands(Loc, LHS, RHS); 13099 } 13100 13101 // Return a signed ext_vector_type that is of identical size and number of 13102 // elements. For floating point vectors, return an integer type of identical 13103 // size and number of elements. In the non ext_vector_type case, search from 13104 // the largest type to the smallest type to avoid cases where long long == long, 13105 // where long gets picked over long long. 13106 QualType Sema::GetSignedVectorType(QualType V) { 13107 const VectorType *VTy = V->castAs<VectorType>(); 13108 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 13109 13110 if (isa<ExtVectorType>(VTy)) { 13111 if (VTy->isExtVectorBoolType()) 13112 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements()); 13113 if (TypeSize == Context.getTypeSize(Context.CharTy)) 13114 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 13115 if (TypeSize == Context.getTypeSize(Context.ShortTy)) 13116 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 13117 if (TypeSize == Context.getTypeSize(Context.IntTy)) 13118 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 13119 if (TypeSize == Context.getTypeSize(Context.Int128Ty)) 13120 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements()); 13121 if (TypeSize == Context.getTypeSize(Context.LongTy)) 13122 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 13123 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 13124 "Unhandled vector element size in vector compare"); 13125 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 13126 } 13127 13128 if (TypeSize == Context.getTypeSize(Context.Int128Ty)) 13129 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(), 13130 VectorType::GenericVector); 13131 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 13132 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 13133 VectorType::GenericVector); 13134 if (TypeSize == Context.getTypeSize(Context.LongTy)) 13135 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 13136 VectorType::GenericVector); 13137 if (TypeSize == Context.getTypeSize(Context.IntTy)) 13138 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 13139 VectorType::GenericVector); 13140 if (TypeSize == Context.getTypeSize(Context.ShortTy)) 13141 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 13142 VectorType::GenericVector); 13143 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 13144 "Unhandled vector element size in vector compare"); 13145 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 13146 VectorType::GenericVector); 13147 } 13148 13149 QualType Sema::GetSignedSizelessVectorType(QualType V) { 13150 const BuiltinType *VTy = V->castAs<BuiltinType>(); 13151 assert(VTy->isSizelessBuiltinType() && "expected sizeless type"); 13152 13153 const QualType ETy = V->getSveEltType(Context); 13154 const auto TypeSize = Context.getTypeSize(ETy); 13155 13156 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true); 13157 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC; 13158 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue()); 13159 } 13160 13161 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 13162 /// operates on extended vector types. Instead of producing an IntTy result, 13163 /// like a scalar comparison, a vector comparison produces a vector of integer 13164 /// types. 13165 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 13166 SourceLocation Loc, 13167 BinaryOperatorKind Opc) { 13168 if (Opc == BO_Cmp) { 13169 Diag(Loc, diag::err_three_way_vector_comparison); 13170 return QualType(); 13171 } 13172 13173 // Check to make sure we're operating on vectors of the same type and width, 13174 // Allowing one side to be a scalar of element type. 13175 QualType vType = 13176 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false, 13177 /*AllowBothBool*/ true, 13178 /*AllowBoolConversions*/ getLangOpts().ZVector, 13179 /*AllowBooleanOperation*/ true, 13180 /*ReportInvalid*/ true); 13181 if (vType.isNull()) 13182 return vType; 13183 13184 QualType LHSType = LHS.get()->getType(); 13185 13186 // Determine the return type of a vector compare. By default clang will return 13187 // a scalar for all vector compares except vector bool and vector pixel. 13188 // With the gcc compiler we will always return a vector type and with the xl 13189 // compiler we will always return a scalar type. This switch allows choosing 13190 // which behavior is prefered. 13191 if (getLangOpts().AltiVec) { 13192 switch (getLangOpts().getAltivecSrcCompat()) { 13193 case LangOptions::AltivecSrcCompatKind::Mixed: 13194 // If AltiVec, the comparison results in a numeric type, i.e. 13195 // bool for C++, int for C 13196 if (vType->castAs<VectorType>()->getVectorKind() == 13197 VectorType::AltiVecVector) 13198 return Context.getLogicalOperationType(); 13199 else 13200 Diag(Loc, diag::warn_deprecated_altivec_src_compat); 13201 break; 13202 case LangOptions::AltivecSrcCompatKind::GCC: 13203 // For GCC we always return the vector type. 13204 break; 13205 case LangOptions::AltivecSrcCompatKind::XL: 13206 return Context.getLogicalOperationType(); 13207 break; 13208 } 13209 } 13210 13211 // For non-floating point types, check for self-comparisons of the form 13212 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 13213 // often indicate logic errors in the program. 13214 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 13215 13216 // Check for comparisons of floating point operands using != and ==. 13217 if (LHSType->hasFloatingRepresentation()) { 13218 assert(RHS.get()->getType()->hasFloatingRepresentation()); 13219 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc); 13220 } 13221 13222 // Return a signed type for the vector. 13223 return GetSignedVectorType(vType); 13224 } 13225 13226 QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS, 13227 ExprResult &RHS, 13228 SourceLocation Loc, 13229 BinaryOperatorKind Opc) { 13230 if (Opc == BO_Cmp) { 13231 Diag(Loc, diag::err_three_way_vector_comparison); 13232 return QualType(); 13233 } 13234 13235 // Check to make sure we're operating on vectors of the same type and width, 13236 // Allowing one side to be a scalar of element type. 13237 QualType vType = CheckSizelessVectorOperands( 13238 LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison); 13239 13240 if (vType.isNull()) 13241 return vType; 13242 13243 QualType LHSType = LHS.get()->getType(); 13244 13245 // For non-floating point types, check for self-comparisons of the form 13246 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 13247 // often indicate logic errors in the program. 13248 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 13249 13250 // Check for comparisons of floating point operands using != and ==. 13251 if (LHSType->hasFloatingRepresentation()) { 13252 assert(RHS.get()->getType()->hasFloatingRepresentation()); 13253 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc); 13254 } 13255 13256 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>(); 13257 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>(); 13258 13259 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() && 13260 RHSBuiltinTy->isSVEBool()) 13261 return LHSType; 13262 13263 // Return a signed type for the vector. 13264 return GetSignedSizelessVectorType(vType); 13265 } 13266 13267 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, 13268 const ExprResult &XorRHS, 13269 const SourceLocation Loc) { 13270 // Do not diagnose macros. 13271 if (Loc.isMacroID()) 13272 return; 13273 13274 // Do not diagnose if both LHS and RHS are macros. 13275 if (XorLHS.get()->getExprLoc().isMacroID() && 13276 XorRHS.get()->getExprLoc().isMacroID()) 13277 return; 13278 13279 bool Negative = false; 13280 bool ExplicitPlus = false; 13281 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get()); 13282 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get()); 13283 13284 if (!LHSInt) 13285 return; 13286 if (!RHSInt) { 13287 // Check negative literals. 13288 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) { 13289 UnaryOperatorKind Opc = UO->getOpcode(); 13290 if (Opc != UO_Minus && Opc != UO_Plus) 13291 return; 13292 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr()); 13293 if (!RHSInt) 13294 return; 13295 Negative = (Opc == UO_Minus); 13296 ExplicitPlus = !Negative; 13297 } else { 13298 return; 13299 } 13300 } 13301 13302 const llvm::APInt &LeftSideValue = LHSInt->getValue(); 13303 llvm::APInt RightSideValue = RHSInt->getValue(); 13304 if (LeftSideValue != 2 && LeftSideValue != 10) 13305 return; 13306 13307 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth()) 13308 return; 13309 13310 CharSourceRange ExprRange = CharSourceRange::getCharRange( 13311 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation())); 13312 llvm::StringRef ExprStr = 13313 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts()); 13314 13315 CharSourceRange XorRange = 13316 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 13317 llvm::StringRef XorStr = 13318 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts()); 13319 // Do not diagnose if xor keyword/macro is used. 13320 if (XorStr == "xor") 13321 return; 13322 13323 std::string LHSStr = std::string(Lexer::getSourceText( 13324 CharSourceRange::getTokenRange(LHSInt->getSourceRange()), 13325 S.getSourceManager(), S.getLangOpts())); 13326 std::string RHSStr = std::string(Lexer::getSourceText( 13327 CharSourceRange::getTokenRange(RHSInt->getSourceRange()), 13328 S.getSourceManager(), S.getLangOpts())); 13329 13330 if (Negative) { 13331 RightSideValue = -RightSideValue; 13332 RHSStr = "-" + RHSStr; 13333 } else if (ExplicitPlus) { 13334 RHSStr = "+" + RHSStr; 13335 } 13336 13337 StringRef LHSStrRef = LHSStr; 13338 StringRef RHSStrRef = RHSStr; 13339 // Do not diagnose literals with digit separators, binary, hexadecimal, octal 13340 // literals. 13341 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") || 13342 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") || 13343 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") || 13344 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") || 13345 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) || 13346 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) || 13347 LHSStrRef.contains('\'') || RHSStrRef.contains('\'')) 13348 return; 13349 13350 bool SuggestXor = 13351 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor"); 13352 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue; 13353 int64_t RightSideIntValue = RightSideValue.getSExtValue(); 13354 if (LeftSideValue == 2 && RightSideIntValue >= 0) { 13355 std::string SuggestedExpr = "1 << " + RHSStr; 13356 bool Overflow = false; 13357 llvm::APInt One = (LeftSideValue - 1); 13358 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow); 13359 if (Overflow) { 13360 if (RightSideIntValue < 64) 13361 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 13362 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr) 13363 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr); 13364 else if (RightSideIntValue == 64) 13365 S.Diag(Loc, diag::warn_xor_used_as_pow) 13366 << ExprStr << toString(XorValue, 10, true); 13367 else 13368 return; 13369 } else { 13370 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra) 13371 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr 13372 << toString(PowValue, 10, true) 13373 << FixItHint::CreateReplacement( 13374 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr); 13375 } 13376 13377 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 13378 << ("0x2 ^ " + RHSStr) << SuggestXor; 13379 } else if (LeftSideValue == 10) { 13380 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue); 13381 S.Diag(Loc, diag::warn_xor_used_as_pow_base) 13382 << ExprStr << toString(XorValue, 10, true) << SuggestedValue 13383 << FixItHint::CreateReplacement(ExprRange, SuggestedValue); 13384 S.Diag(Loc, diag::note_xor_used_as_pow_silence) 13385 << ("0xA ^ " + RHSStr) << SuggestXor; 13386 } 13387 } 13388 13389 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 13390 SourceLocation Loc) { 13391 // Ensure that either both operands are of the same vector type, or 13392 // one operand is of a vector type and the other is of its element type. 13393 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 13394 /*AllowBothBool*/ true, 13395 /*AllowBoolConversions*/ false, 13396 /*AllowBooleanOperation*/ false, 13397 /*ReportInvalid*/ false); 13398 if (vType.isNull()) 13399 return InvalidOperands(Loc, LHS, RHS); 13400 if (getLangOpts().OpenCL && 13401 getLangOpts().getOpenCLCompatibleVersion() < 120 && 13402 vType->hasFloatingRepresentation()) 13403 return InvalidOperands(Loc, LHS, RHS); 13404 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 13405 // usage of the logical operators && and || with vectors in C. This 13406 // check could be notionally dropped. 13407 if (!getLangOpts().CPlusPlus && 13408 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 13409 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 13410 13411 return GetSignedVectorType(LHS.get()->getType()); 13412 } 13413 13414 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 13415 SourceLocation Loc, 13416 bool IsCompAssign) { 13417 if (!IsCompAssign) { 13418 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 13419 if (LHS.isInvalid()) 13420 return QualType(); 13421 } 13422 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 13423 if (RHS.isInvalid()) 13424 return QualType(); 13425 13426 // For conversion purposes, we ignore any qualifiers. 13427 // For example, "const float" and "float" are equivalent. 13428 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 13429 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 13430 13431 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>(); 13432 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>(); 13433 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 13434 13435 if (Context.hasSameType(LHSType, RHSType)) 13436 return Context.getCommonSugaredType(LHSType, RHSType); 13437 13438 // Type conversion may change LHS/RHS. Keep copies to the original results, in 13439 // case we have to return InvalidOperands. 13440 ExprResult OriginalLHS = LHS; 13441 ExprResult OriginalRHS = RHS; 13442 if (LHSMatType && !RHSMatType) { 13443 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType()); 13444 if (!RHS.isInvalid()) 13445 return LHSType; 13446 13447 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 13448 } 13449 13450 if (!LHSMatType && RHSMatType) { 13451 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType()); 13452 if (!LHS.isInvalid()) 13453 return RHSType; 13454 return InvalidOperands(Loc, OriginalLHS, OriginalRHS); 13455 } 13456 13457 return InvalidOperands(Loc, LHS, RHS); 13458 } 13459 13460 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 13461 SourceLocation Loc, 13462 bool IsCompAssign) { 13463 if (!IsCompAssign) { 13464 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 13465 if (LHS.isInvalid()) 13466 return QualType(); 13467 } 13468 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 13469 if (RHS.isInvalid()) 13470 return QualType(); 13471 13472 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>(); 13473 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>(); 13474 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix"); 13475 13476 if (LHSMatType && RHSMatType) { 13477 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows()) 13478 return InvalidOperands(Loc, LHS, RHS); 13479 13480 if (Context.hasSameType(LHSMatType, RHSMatType)) 13481 return Context.getCommonSugaredType( 13482 LHS.get()->getType().getUnqualifiedType(), 13483 RHS.get()->getType().getUnqualifiedType()); 13484 13485 QualType LHSELTy = LHSMatType->getElementType(), 13486 RHSELTy = RHSMatType->getElementType(); 13487 if (!Context.hasSameType(LHSELTy, RHSELTy)) 13488 return InvalidOperands(Loc, LHS, RHS); 13489 13490 return Context.getConstantMatrixType( 13491 Context.getCommonSugaredType(LHSELTy, RHSELTy), 13492 LHSMatType->getNumRows(), RHSMatType->getNumColumns()); 13493 } 13494 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign); 13495 } 13496 13497 static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) { 13498 switch (Opc) { 13499 default: 13500 return false; 13501 case BO_And: 13502 case BO_AndAssign: 13503 case BO_Or: 13504 case BO_OrAssign: 13505 case BO_Xor: 13506 case BO_XorAssign: 13507 return true; 13508 } 13509 } 13510 13511 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 13512 SourceLocation Loc, 13513 BinaryOperatorKind Opc) { 13514 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false); 13515 13516 bool IsCompAssign = 13517 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 13518 13519 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc); 13520 13521 if (LHS.get()->getType()->isVectorType() || 13522 RHS.get()->getType()->isVectorType()) { 13523 if (LHS.get()->getType()->hasIntegerRepresentation() && 13524 RHS.get()->getType()->hasIntegerRepresentation()) 13525 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 13526 /*AllowBothBool*/ true, 13527 /*AllowBoolConversions*/ getLangOpts().ZVector, 13528 /*AllowBooleanOperation*/ LegalBoolVecOperator, 13529 /*ReportInvalid*/ true); 13530 return InvalidOperands(Loc, LHS, RHS); 13531 } 13532 13533 if (LHS.get()->getType()->isVLSTBuiltinType() || 13534 RHS.get()->getType()->isVLSTBuiltinType()) { 13535 if (LHS.get()->getType()->hasIntegerRepresentation() && 13536 RHS.get()->getType()->hasIntegerRepresentation()) 13537 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 13538 ACK_BitwiseOp); 13539 return InvalidOperands(Loc, LHS, RHS); 13540 } 13541 13542 if (LHS.get()->getType()->isVLSTBuiltinType() || 13543 RHS.get()->getType()->isVLSTBuiltinType()) { 13544 if (LHS.get()->getType()->hasIntegerRepresentation() && 13545 RHS.get()->getType()->hasIntegerRepresentation()) 13546 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign, 13547 ACK_BitwiseOp); 13548 return InvalidOperands(Loc, LHS, RHS); 13549 } 13550 13551 if (Opc == BO_And) 13552 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 13553 13554 if (LHS.get()->getType()->hasFloatingRepresentation() || 13555 RHS.get()->getType()->hasFloatingRepresentation()) 13556 return InvalidOperands(Loc, LHS, RHS); 13557 13558 ExprResult LHSResult = LHS, RHSResult = RHS; 13559 QualType compType = UsualArithmeticConversions( 13560 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp); 13561 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 13562 return QualType(); 13563 LHS = LHSResult.get(); 13564 RHS = RHSResult.get(); 13565 13566 if (Opc == BO_Xor) 13567 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc); 13568 13569 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 13570 return compType; 13571 return InvalidOperands(Loc, LHS, RHS); 13572 } 13573 13574 // C99 6.5.[13,14] 13575 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 13576 SourceLocation Loc, 13577 BinaryOperatorKind Opc) { 13578 // Check vector operands differently. 13579 if (LHS.get()->getType()->isVectorType() || 13580 RHS.get()->getType()->isVectorType()) 13581 return CheckVectorLogicalOperands(LHS, RHS, Loc); 13582 13583 bool EnumConstantInBoolContext = false; 13584 for (const ExprResult &HS : {LHS, RHS}) { 13585 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) { 13586 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl()); 13587 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1) 13588 EnumConstantInBoolContext = true; 13589 } 13590 } 13591 13592 if (EnumConstantInBoolContext) 13593 Diag(Loc, diag::warn_enum_constant_in_bool_context); 13594 13595 // Diagnose cases where the user write a logical and/or but probably meant a 13596 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 13597 // is a constant. 13598 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() && 13599 !LHS.get()->getType()->isBooleanType() && 13600 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 13601 // Don't warn in macros or template instantiations. 13602 !Loc.isMacroID() && !inTemplateInstantiation()) { 13603 // If the RHS can be constant folded, and if it constant folds to something 13604 // that isn't 0 or 1 (which indicate a potential logical operation that 13605 // happened to fold to true/false) then warn. 13606 // Parens on the RHS are ignored. 13607 Expr::EvalResult EVResult; 13608 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 13609 llvm::APSInt Result = EVResult.Val.getInt(); 13610 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 13611 !RHS.get()->getExprLoc().isMacroID()) || 13612 (Result != 0 && Result != 1)) { 13613 Diag(Loc, diag::warn_logical_instead_of_bitwise) 13614 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||"); 13615 // Suggest replacing the logical operator with the bitwise version 13616 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 13617 << (Opc == BO_LAnd ? "&" : "|") 13618 << FixItHint::CreateReplacement( 13619 SourceRange(Loc, getLocForEndOfToken(Loc)), 13620 Opc == BO_LAnd ? "&" : "|"); 13621 if (Opc == BO_LAnd) 13622 // Suggest replacing "Foo() && kNonZero" with "Foo()" 13623 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 13624 << FixItHint::CreateRemoval( 13625 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 13626 RHS.get()->getEndLoc())); 13627 } 13628 } 13629 } 13630 13631 if (!Context.getLangOpts().CPlusPlus) { 13632 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 13633 // not operate on the built-in scalar and vector float types. 13634 if (Context.getLangOpts().OpenCL && 13635 Context.getLangOpts().OpenCLVersion < 120) { 13636 if (LHS.get()->getType()->isFloatingType() || 13637 RHS.get()->getType()->isFloatingType()) 13638 return InvalidOperands(Loc, LHS, RHS); 13639 } 13640 13641 LHS = UsualUnaryConversions(LHS.get()); 13642 if (LHS.isInvalid()) 13643 return QualType(); 13644 13645 RHS = UsualUnaryConversions(RHS.get()); 13646 if (RHS.isInvalid()) 13647 return QualType(); 13648 13649 if (!LHS.get()->getType()->isScalarType() || 13650 !RHS.get()->getType()->isScalarType()) 13651 return InvalidOperands(Loc, LHS, RHS); 13652 13653 return Context.IntTy; 13654 } 13655 13656 // The following is safe because we only use this method for 13657 // non-overloadable operands. 13658 13659 // C++ [expr.log.and]p1 13660 // C++ [expr.log.or]p1 13661 // The operands are both contextually converted to type bool. 13662 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 13663 if (LHSRes.isInvalid()) 13664 return InvalidOperands(Loc, LHS, RHS); 13665 LHS = LHSRes; 13666 13667 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 13668 if (RHSRes.isInvalid()) 13669 return InvalidOperands(Loc, LHS, RHS); 13670 RHS = RHSRes; 13671 13672 // C++ [expr.log.and]p2 13673 // C++ [expr.log.or]p2 13674 // The result is a bool. 13675 return Context.BoolTy; 13676 } 13677 13678 static bool IsReadonlyMessage(Expr *E, Sema &S) { 13679 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 13680 if (!ME) return false; 13681 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 13682 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 13683 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 13684 if (!Base) return false; 13685 return Base->getMethodDecl() != nullptr; 13686 } 13687 13688 /// Is the given expression (which must be 'const') a reference to a 13689 /// variable which was originally non-const, but which has become 13690 /// 'const' due to being captured within a block? 13691 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 13692 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 13693 assert(E->isLValue() && E->getType().isConstQualified()); 13694 E = E->IgnoreParens(); 13695 13696 // Must be a reference to a declaration from an enclosing scope. 13697 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 13698 if (!DRE) return NCCK_None; 13699 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 13700 13701 // The declaration must be a variable which is not declared 'const'. 13702 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 13703 if (!var) return NCCK_None; 13704 if (var->getType().isConstQualified()) return NCCK_None; 13705 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 13706 13707 // Decide whether the first capture was for a block or a lambda. 13708 DeclContext *DC = S.CurContext, *Prev = nullptr; 13709 // Decide whether the first capture was for a block or a lambda. 13710 while (DC) { 13711 // For init-capture, it is possible that the variable belongs to the 13712 // template pattern of the current context. 13713 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 13714 if (var->isInitCapture() && 13715 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 13716 break; 13717 if (DC == var->getDeclContext()) 13718 break; 13719 Prev = DC; 13720 DC = DC->getParent(); 13721 } 13722 // Unless we have an init-capture, we've gone one step too far. 13723 if (!var->isInitCapture()) 13724 DC = Prev; 13725 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 13726 } 13727 13728 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 13729 Ty = Ty.getNonReferenceType(); 13730 if (IsDereference && Ty->isPointerType()) 13731 Ty = Ty->getPointeeType(); 13732 return !Ty.isConstQualified(); 13733 } 13734 13735 // Update err_typecheck_assign_const and note_typecheck_assign_const 13736 // when this enum is changed. 13737 enum { 13738 ConstFunction, 13739 ConstVariable, 13740 ConstMember, 13741 ConstMethod, 13742 NestedConstMember, 13743 ConstUnknown, // Keep as last element 13744 }; 13745 13746 /// Emit the "read-only variable not assignable" error and print notes to give 13747 /// more information about why the variable is not assignable, such as pointing 13748 /// to the declaration of a const variable, showing that a method is const, or 13749 /// that the function is returning a const reference. 13750 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 13751 SourceLocation Loc) { 13752 SourceRange ExprRange = E->getSourceRange(); 13753 13754 // Only emit one error on the first const found. All other consts will emit 13755 // a note to the error. 13756 bool DiagnosticEmitted = false; 13757 13758 // Track if the current expression is the result of a dereference, and if the 13759 // next checked expression is the result of a dereference. 13760 bool IsDereference = false; 13761 bool NextIsDereference = false; 13762 13763 // Loop to process MemberExpr chains. 13764 while (true) { 13765 IsDereference = NextIsDereference; 13766 13767 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 13768 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13769 NextIsDereference = ME->isArrow(); 13770 const ValueDecl *VD = ME->getMemberDecl(); 13771 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 13772 // Mutable fields can be modified even if the class is const. 13773 if (Field->isMutable()) { 13774 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 13775 break; 13776 } 13777 13778 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 13779 if (!DiagnosticEmitted) { 13780 S.Diag(Loc, diag::err_typecheck_assign_const) 13781 << ExprRange << ConstMember << false /*static*/ << Field 13782 << Field->getType(); 13783 DiagnosticEmitted = true; 13784 } 13785 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 13786 << ConstMember << false /*static*/ << Field << Field->getType() 13787 << Field->getSourceRange(); 13788 } 13789 E = ME->getBase(); 13790 continue; 13791 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 13792 if (VDecl->getType().isConstQualified()) { 13793 if (!DiagnosticEmitted) { 13794 S.Diag(Loc, diag::err_typecheck_assign_const) 13795 << ExprRange << ConstMember << true /*static*/ << VDecl 13796 << VDecl->getType(); 13797 DiagnosticEmitted = true; 13798 } 13799 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 13800 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 13801 << VDecl->getSourceRange(); 13802 } 13803 // Static fields do not inherit constness from parents. 13804 break; 13805 } 13806 break; // End MemberExpr 13807 } else if (const ArraySubscriptExpr *ASE = 13808 dyn_cast<ArraySubscriptExpr>(E)) { 13809 E = ASE->getBase()->IgnoreParenImpCasts(); 13810 continue; 13811 } else if (const ExtVectorElementExpr *EVE = 13812 dyn_cast<ExtVectorElementExpr>(E)) { 13813 E = EVE->getBase()->IgnoreParenImpCasts(); 13814 continue; 13815 } 13816 break; 13817 } 13818 13819 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 13820 // Function calls 13821 const FunctionDecl *FD = CE->getDirectCallee(); 13822 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 13823 if (!DiagnosticEmitted) { 13824 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 13825 << ConstFunction << FD; 13826 DiagnosticEmitted = true; 13827 } 13828 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 13829 diag::note_typecheck_assign_const) 13830 << ConstFunction << FD << FD->getReturnType() 13831 << FD->getReturnTypeSourceRange(); 13832 } 13833 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13834 // Point to variable declaration. 13835 if (const ValueDecl *VD = DRE->getDecl()) { 13836 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 13837 if (!DiagnosticEmitted) { 13838 S.Diag(Loc, diag::err_typecheck_assign_const) 13839 << ExprRange << ConstVariable << VD << VD->getType(); 13840 DiagnosticEmitted = true; 13841 } 13842 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 13843 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 13844 } 13845 } 13846 } else if (isa<CXXThisExpr>(E)) { 13847 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 13848 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 13849 if (MD->isConst()) { 13850 if (!DiagnosticEmitted) { 13851 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 13852 << ConstMethod << MD; 13853 DiagnosticEmitted = true; 13854 } 13855 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 13856 << ConstMethod << MD << MD->getSourceRange(); 13857 } 13858 } 13859 } 13860 } 13861 13862 if (DiagnosticEmitted) 13863 return; 13864 13865 // Can't determine a more specific message, so display the generic error. 13866 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 13867 } 13868 13869 enum OriginalExprKind { 13870 OEK_Variable, 13871 OEK_Member, 13872 OEK_LValue 13873 }; 13874 13875 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 13876 const RecordType *Ty, 13877 SourceLocation Loc, SourceRange Range, 13878 OriginalExprKind OEK, 13879 bool &DiagnosticEmitted) { 13880 std::vector<const RecordType *> RecordTypeList; 13881 RecordTypeList.push_back(Ty); 13882 unsigned NextToCheckIndex = 0; 13883 // We walk the record hierarchy breadth-first to ensure that we print 13884 // diagnostics in field nesting order. 13885 while (RecordTypeList.size() > NextToCheckIndex) { 13886 bool IsNested = NextToCheckIndex > 0; 13887 for (const FieldDecl *Field : 13888 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) { 13889 // First, check every field for constness. 13890 QualType FieldTy = Field->getType(); 13891 if (FieldTy.isConstQualified()) { 13892 if (!DiagnosticEmitted) { 13893 S.Diag(Loc, diag::err_typecheck_assign_const) 13894 << Range << NestedConstMember << OEK << VD 13895 << IsNested << Field; 13896 DiagnosticEmitted = true; 13897 } 13898 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 13899 << NestedConstMember << IsNested << Field 13900 << FieldTy << Field->getSourceRange(); 13901 } 13902 13903 // Then we append it to the list to check next in order. 13904 FieldTy = FieldTy.getCanonicalType(); 13905 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) { 13906 if (!llvm::is_contained(RecordTypeList, FieldRecTy)) 13907 RecordTypeList.push_back(FieldRecTy); 13908 } 13909 } 13910 ++NextToCheckIndex; 13911 } 13912 } 13913 13914 /// Emit an error for the case where a record we are trying to assign to has a 13915 /// const-qualified field somewhere in its hierarchy. 13916 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 13917 SourceLocation Loc) { 13918 QualType Ty = E->getType(); 13919 assert(Ty->isRecordType() && "lvalue was not record?"); 13920 SourceRange Range = E->getSourceRange(); 13921 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 13922 bool DiagEmitted = false; 13923 13924 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 13925 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 13926 Range, OEK_Member, DiagEmitted); 13927 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13928 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 13929 Range, OEK_Variable, DiagEmitted); 13930 else 13931 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 13932 Range, OEK_LValue, DiagEmitted); 13933 if (!DiagEmitted) 13934 DiagnoseConstAssignment(S, E, Loc); 13935 } 13936 13937 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 13938 /// emit an error and return true. If so, return false. 13939 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 13940 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 13941 13942 S.CheckShadowingDeclModification(E, Loc); 13943 13944 SourceLocation OrigLoc = Loc; 13945 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 13946 &Loc); 13947 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 13948 IsLV = Expr::MLV_InvalidMessageExpression; 13949 if (IsLV == Expr::MLV_Valid) 13950 return false; 13951 13952 unsigned DiagID = 0; 13953 bool NeedType = false; 13954 switch (IsLV) { // C99 6.5.16p2 13955 case Expr::MLV_ConstQualified: 13956 // Use a specialized diagnostic when we're assigning to an object 13957 // from an enclosing function or block. 13958 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 13959 if (NCCK == NCCK_Block) 13960 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 13961 else 13962 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 13963 break; 13964 } 13965 13966 // In ARC, use some specialized diagnostics for occasions where we 13967 // infer 'const'. These are always pseudo-strong variables. 13968 if (S.getLangOpts().ObjCAutoRefCount) { 13969 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 13970 if (declRef && isa<VarDecl>(declRef->getDecl())) { 13971 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 13972 13973 // Use the normal diagnostic if it's pseudo-__strong but the 13974 // user actually wrote 'const'. 13975 if (var->isARCPseudoStrong() && 13976 (!var->getTypeSourceInfo() || 13977 !var->getTypeSourceInfo()->getType().isConstQualified())) { 13978 // There are three pseudo-strong cases: 13979 // - self 13980 ObjCMethodDecl *method = S.getCurMethodDecl(); 13981 if (method && var == method->getSelfDecl()) { 13982 DiagID = method->isClassMethod() 13983 ? diag::err_typecheck_arc_assign_self_class_method 13984 : diag::err_typecheck_arc_assign_self; 13985 13986 // - Objective-C externally_retained attribute. 13987 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() || 13988 isa<ParmVarDecl>(var)) { 13989 DiagID = diag::err_typecheck_arc_assign_externally_retained; 13990 13991 // - fast enumeration variables 13992 } else { 13993 DiagID = diag::err_typecheck_arr_assign_enumeration; 13994 } 13995 13996 SourceRange Assign; 13997 if (Loc != OrigLoc) 13998 Assign = SourceRange(OrigLoc, OrigLoc); 13999 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 14000 // We need to preserve the AST regardless, so migration tool 14001 // can do its job. 14002 return false; 14003 } 14004 } 14005 } 14006 14007 // If none of the special cases above are triggered, then this is a 14008 // simple const assignment. 14009 if (DiagID == 0) { 14010 DiagnoseConstAssignment(S, E, Loc); 14011 return true; 14012 } 14013 14014 break; 14015 case Expr::MLV_ConstAddrSpace: 14016 DiagnoseConstAssignment(S, E, Loc); 14017 return true; 14018 case Expr::MLV_ConstQualifiedField: 14019 DiagnoseRecursiveConstFields(S, E, Loc); 14020 return true; 14021 case Expr::MLV_ArrayType: 14022 case Expr::MLV_ArrayTemporary: 14023 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 14024 NeedType = true; 14025 break; 14026 case Expr::MLV_NotObjectType: 14027 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 14028 NeedType = true; 14029 break; 14030 case Expr::MLV_LValueCast: 14031 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 14032 break; 14033 case Expr::MLV_Valid: 14034 llvm_unreachable("did not take early return for MLV_Valid"); 14035 case Expr::MLV_InvalidExpression: 14036 case Expr::MLV_MemberFunction: 14037 case Expr::MLV_ClassTemporary: 14038 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 14039 break; 14040 case Expr::MLV_IncompleteType: 14041 case Expr::MLV_IncompleteVoidType: 14042 return S.RequireCompleteType(Loc, E->getType(), 14043 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 14044 case Expr::MLV_DuplicateVectorComponents: 14045 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 14046 break; 14047 case Expr::MLV_NoSetterProperty: 14048 llvm_unreachable("readonly properties should be processed differently"); 14049 case Expr::MLV_InvalidMessageExpression: 14050 DiagID = diag::err_readonly_message_assignment; 14051 break; 14052 case Expr::MLV_SubObjCPropertySetting: 14053 DiagID = diag::err_no_subobject_property_setting; 14054 break; 14055 } 14056 14057 SourceRange Assign; 14058 if (Loc != OrigLoc) 14059 Assign = SourceRange(OrigLoc, OrigLoc); 14060 if (NeedType) 14061 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 14062 else 14063 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 14064 return true; 14065 } 14066 14067 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 14068 SourceLocation Loc, 14069 Sema &Sema) { 14070 if (Sema.inTemplateInstantiation()) 14071 return; 14072 if (Sema.isUnevaluatedContext()) 14073 return; 14074 if (Loc.isInvalid() || Loc.isMacroID()) 14075 return; 14076 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 14077 return; 14078 14079 // C / C++ fields 14080 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 14081 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 14082 if (ML && MR) { 14083 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 14084 return; 14085 const ValueDecl *LHSDecl = 14086 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 14087 const ValueDecl *RHSDecl = 14088 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 14089 if (LHSDecl != RHSDecl) 14090 return; 14091 if (LHSDecl->getType().isVolatileQualified()) 14092 return; 14093 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 14094 if (RefTy->getPointeeType().isVolatileQualified()) 14095 return; 14096 14097 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 14098 } 14099 14100 // Objective-C instance variables 14101 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 14102 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 14103 if (OL && OR && OL->getDecl() == OR->getDecl()) { 14104 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 14105 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 14106 if (RL && RR && RL->getDecl() == RR->getDecl()) 14107 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 14108 } 14109 } 14110 14111 // C99 6.5.16.1 14112 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 14113 SourceLocation Loc, 14114 QualType CompoundType, 14115 BinaryOperatorKind Opc) { 14116 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 14117 14118 // Verify that LHS is a modifiable lvalue, and emit error if not. 14119 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 14120 return QualType(); 14121 14122 QualType LHSType = LHSExpr->getType(); 14123 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 14124 CompoundType; 14125 // OpenCL v1.2 s6.1.1.1 p2: 14126 // The half data type can only be used to declare a pointer to a buffer that 14127 // contains half values 14128 if (getLangOpts().OpenCL && 14129 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) && 14130 LHSType->isHalfType()) { 14131 Diag(Loc, diag::err_opencl_half_load_store) << 1 14132 << LHSType.getUnqualifiedType(); 14133 return QualType(); 14134 } 14135 14136 AssignConvertType ConvTy; 14137 if (CompoundType.isNull()) { 14138 Expr *RHSCheck = RHS.get(); 14139 14140 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 14141 14142 QualType LHSTy(LHSType); 14143 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 14144 if (RHS.isInvalid()) 14145 return QualType(); 14146 // Special case of NSObject attributes on c-style pointer types. 14147 if (ConvTy == IncompatiblePointer && 14148 ((Context.isObjCNSObjectType(LHSType) && 14149 RHSType->isObjCObjectPointerType()) || 14150 (Context.isObjCNSObjectType(RHSType) && 14151 LHSType->isObjCObjectPointerType()))) 14152 ConvTy = Compatible; 14153 14154 if (ConvTy == Compatible && 14155 LHSType->isObjCObjectType()) 14156 Diag(Loc, diag::err_objc_object_assignment) 14157 << LHSType; 14158 14159 // If the RHS is a unary plus or minus, check to see if they = and + are 14160 // right next to each other. If so, the user may have typo'd "x =+ 4" 14161 // instead of "x += 4". 14162 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 14163 RHSCheck = ICE->getSubExpr(); 14164 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 14165 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 14166 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 14167 // Only if the two operators are exactly adjacent. 14168 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 14169 // And there is a space or other character before the subexpr of the 14170 // unary +/-. We don't want to warn on "x=-1". 14171 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 14172 UO->getSubExpr()->getBeginLoc().isFileID()) { 14173 Diag(Loc, diag::warn_not_compound_assign) 14174 << (UO->getOpcode() == UO_Plus ? "+" : "-") 14175 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 14176 } 14177 } 14178 14179 if (ConvTy == Compatible) { 14180 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 14181 // Warn about retain cycles where a block captures the LHS, but 14182 // not if the LHS is a simple variable into which the block is 14183 // being stored...unless that variable can be captured by reference! 14184 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 14185 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 14186 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 14187 checkRetainCycles(LHSExpr, RHS.get()); 14188 } 14189 14190 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 14191 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 14192 // It is safe to assign a weak reference into a strong variable. 14193 // Although this code can still have problems: 14194 // id x = self.weakProp; 14195 // id y = self.weakProp; 14196 // we do not warn to warn spuriously when 'x' and 'y' are on separate 14197 // paths through the function. This should be revisited if 14198 // -Wrepeated-use-of-weak is made flow-sensitive. 14199 // For ObjCWeak only, we do not warn if the assign is to a non-weak 14200 // variable, which will be valid for the current autorelease scope. 14201 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 14202 RHS.get()->getBeginLoc())) 14203 getCurFunction()->markSafeWeakUse(RHS.get()); 14204 14205 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 14206 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 14207 } 14208 } 14209 } else { 14210 // Compound assignment "x += y" 14211 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 14212 } 14213 14214 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 14215 RHS.get(), AA_Assigning)) 14216 return QualType(); 14217 14218 CheckForNullPointerDereference(*this, LHSExpr); 14219 14220 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) { 14221 if (CompoundType.isNull()) { 14222 // C++2a [expr.ass]p5: 14223 // A simple-assignment whose left operand is of a volatile-qualified 14224 // type is deprecated unless the assignment is either a discarded-value 14225 // expression or an unevaluated operand 14226 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr); 14227 } 14228 } 14229 14230 // C11 6.5.16p3: The type of an assignment expression is the type of the 14231 // left operand would have after lvalue conversion. 14232 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has 14233 // qualified type, the value has the unqualified version of the type of the 14234 // lvalue; additionally, if the lvalue has atomic type, the value has the 14235 // non-atomic version of the type of the lvalue. 14236 // C++ 5.17p1: the type of the assignment expression is that of its left 14237 // operand. 14238 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType(); 14239 } 14240 14241 // Scenarios to ignore if expression E is: 14242 // 1. an explicit cast expression into void 14243 // 2. a function call expression that returns void 14244 static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) { 14245 E = E->IgnoreParens(); 14246 14247 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 14248 if (CE->getCastKind() == CK_ToVoid) { 14249 return true; 14250 } 14251 14252 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 14253 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 14254 CE->getSubExpr()->getType()->isDependentType()) { 14255 return true; 14256 } 14257 } 14258 14259 if (const auto *CE = dyn_cast<CallExpr>(E)) 14260 return CE->getCallReturnType(Context)->isVoidType(); 14261 return false; 14262 } 14263 14264 // Look for instances where it is likely the comma operator is confused with 14265 // another operator. There is an explicit list of acceptable expressions for 14266 // the left hand side of the comma operator, otherwise emit a warning. 14267 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 14268 // No warnings in macros 14269 if (Loc.isMacroID()) 14270 return; 14271 14272 // Don't warn in template instantiations. 14273 if (inTemplateInstantiation()) 14274 return; 14275 14276 // Scope isn't fine-grained enough to explicitly list the specific cases, so 14277 // instead, skip more than needed, then call back into here with the 14278 // CommaVisitor in SemaStmt.cpp. 14279 // The listed locations are the initialization and increment portions 14280 // of a for loop. The additional checks are on the condition of 14281 // if statements, do/while loops, and for loops. 14282 // Differences in scope flags for C89 mode requires the extra logic. 14283 const unsigned ForIncrementFlags = 14284 getLangOpts().C99 || getLangOpts().CPlusPlus 14285 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 14286 : Scope::ContinueScope | Scope::BreakScope; 14287 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 14288 const unsigned ScopeFlags = getCurScope()->getFlags(); 14289 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 14290 (ScopeFlags & ForInitFlags) == ForInitFlags) 14291 return; 14292 14293 // If there are multiple comma operators used together, get the RHS of the 14294 // of the comma operator as the LHS. 14295 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 14296 if (BO->getOpcode() != BO_Comma) 14297 break; 14298 LHS = BO->getRHS(); 14299 } 14300 14301 // Only allow some expressions on LHS to not warn. 14302 if (IgnoreCommaOperand(LHS, Context)) 14303 return; 14304 14305 Diag(Loc, diag::warn_comma_operator); 14306 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 14307 << LHS->getSourceRange() 14308 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 14309 LangOpts.CPlusPlus ? "static_cast<void>(" 14310 : "(void)(") 14311 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 14312 ")"); 14313 } 14314 14315 // C99 6.5.17 14316 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 14317 SourceLocation Loc) { 14318 LHS = S.CheckPlaceholderExpr(LHS.get()); 14319 RHS = S.CheckPlaceholderExpr(RHS.get()); 14320 if (LHS.isInvalid() || RHS.isInvalid()) 14321 return QualType(); 14322 14323 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 14324 // operands, but not unary promotions. 14325 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 14326 14327 // So we treat the LHS as a ignored value, and in C++ we allow the 14328 // containing site to determine what should be done with the RHS. 14329 LHS = S.IgnoredValueConversions(LHS.get()); 14330 if (LHS.isInvalid()) 14331 return QualType(); 14332 14333 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand); 14334 14335 if (!S.getLangOpts().CPlusPlus) { 14336 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 14337 if (RHS.isInvalid()) 14338 return QualType(); 14339 if (!RHS.get()->getType()->isVoidType()) 14340 S.RequireCompleteType(Loc, RHS.get()->getType(), 14341 diag::err_incomplete_type); 14342 } 14343 14344 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 14345 S.DiagnoseCommaOperator(LHS.get(), Loc); 14346 14347 return RHS.get()->getType(); 14348 } 14349 14350 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 14351 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 14352 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 14353 ExprValueKind &VK, 14354 ExprObjectKind &OK, 14355 SourceLocation OpLoc, 14356 bool IsInc, bool IsPrefix) { 14357 if (Op->isTypeDependent()) 14358 return S.Context.DependentTy; 14359 14360 QualType ResType = Op->getType(); 14361 // Atomic types can be used for increment / decrement where the non-atomic 14362 // versions can, so ignore the _Atomic() specifier for the purpose of 14363 // checking. 14364 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 14365 ResType = ResAtomicType->getValueType(); 14366 14367 assert(!ResType.isNull() && "no type for increment/decrement expression"); 14368 14369 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 14370 // Decrement of bool is not allowed. 14371 if (!IsInc) { 14372 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 14373 return QualType(); 14374 } 14375 // Increment of bool sets it to true, but is deprecated. 14376 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 14377 : diag::warn_increment_bool) 14378 << Op->getSourceRange(); 14379 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 14380 // Error on enum increments and decrements in C++ mode 14381 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 14382 return QualType(); 14383 } else if (ResType->isRealType()) { 14384 // OK! 14385 } else if (ResType->isPointerType()) { 14386 // C99 6.5.2.4p2, 6.5.6p2 14387 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 14388 return QualType(); 14389 } else if (ResType->isObjCObjectPointerType()) { 14390 // On modern runtimes, ObjC pointer arithmetic is forbidden. 14391 // Otherwise, we just need a complete type. 14392 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 14393 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 14394 return QualType(); 14395 } else if (ResType->isAnyComplexType()) { 14396 // C99 does not support ++/-- on complex types, we allow as an extension. 14397 S.Diag(OpLoc, diag::ext_integer_increment_complex) 14398 << ResType << Op->getSourceRange(); 14399 } else if (ResType->isPlaceholderType()) { 14400 ExprResult PR = S.CheckPlaceholderExpr(Op); 14401 if (PR.isInvalid()) return QualType(); 14402 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 14403 IsInc, IsPrefix); 14404 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 14405 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 14406 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 14407 (ResType->castAs<VectorType>()->getVectorKind() != 14408 VectorType::AltiVecBool)) { 14409 // The z vector extensions allow ++ and -- for non-bool vectors. 14410 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 14411 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) { 14412 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 14413 } else { 14414 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 14415 << ResType << int(IsInc) << Op->getSourceRange(); 14416 return QualType(); 14417 } 14418 // At this point, we know we have a real, complex or pointer type. 14419 // Now make sure the operand is a modifiable lvalue. 14420 if (CheckForModifiableLvalue(Op, OpLoc, S)) 14421 return QualType(); 14422 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) { 14423 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1: 14424 // An operand with volatile-qualified type is deprecated 14425 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile) 14426 << IsInc << ResType; 14427 } 14428 // In C++, a prefix increment is the same type as the operand. Otherwise 14429 // (in C or with postfix), the increment is the unqualified type of the 14430 // operand. 14431 if (IsPrefix && S.getLangOpts().CPlusPlus) { 14432 VK = VK_LValue; 14433 OK = Op->getObjectKind(); 14434 return ResType; 14435 } else { 14436 VK = VK_PRValue; 14437 return ResType.getUnqualifiedType(); 14438 } 14439 } 14440 14441 14442 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 14443 /// This routine allows us to typecheck complex/recursive expressions 14444 /// where the declaration is needed for type checking. We only need to 14445 /// handle cases when the expression references a function designator 14446 /// or is an lvalue. Here are some examples: 14447 /// - &(x) => x 14448 /// - &*****f => f for f a function designator. 14449 /// - &s.xx => s 14450 /// - &s.zz[1].yy -> s, if zz is an array 14451 /// - *(x + 1) -> x, if x is an array 14452 /// - &"123"[2] -> 0 14453 /// - & __real__ x -> x 14454 /// 14455 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to 14456 /// members. 14457 static ValueDecl *getPrimaryDecl(Expr *E) { 14458 switch (E->getStmtClass()) { 14459 case Stmt::DeclRefExprClass: 14460 return cast<DeclRefExpr>(E)->getDecl(); 14461 case Stmt::MemberExprClass: 14462 // If this is an arrow operator, the address is an offset from 14463 // the base's value, so the object the base refers to is 14464 // irrelevant. 14465 if (cast<MemberExpr>(E)->isArrow()) 14466 return nullptr; 14467 // Otherwise, the expression refers to a part of the base 14468 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 14469 case Stmt::ArraySubscriptExprClass: { 14470 // FIXME: This code shouldn't be necessary! We should catch the implicit 14471 // promotion of register arrays earlier. 14472 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 14473 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 14474 if (ICE->getSubExpr()->getType()->isArrayType()) 14475 return getPrimaryDecl(ICE->getSubExpr()); 14476 } 14477 return nullptr; 14478 } 14479 case Stmt::UnaryOperatorClass: { 14480 UnaryOperator *UO = cast<UnaryOperator>(E); 14481 14482 switch(UO->getOpcode()) { 14483 case UO_Real: 14484 case UO_Imag: 14485 case UO_Extension: 14486 return getPrimaryDecl(UO->getSubExpr()); 14487 default: 14488 return nullptr; 14489 } 14490 } 14491 case Stmt::ParenExprClass: 14492 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 14493 case Stmt::ImplicitCastExprClass: 14494 // If the result of an implicit cast is an l-value, we care about 14495 // the sub-expression; otherwise, the result here doesn't matter. 14496 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 14497 case Stmt::CXXUuidofExprClass: 14498 return cast<CXXUuidofExpr>(E)->getGuidDecl(); 14499 default: 14500 return nullptr; 14501 } 14502 } 14503 14504 namespace { 14505 enum { 14506 AO_Bit_Field = 0, 14507 AO_Vector_Element = 1, 14508 AO_Property_Expansion = 2, 14509 AO_Register_Variable = 3, 14510 AO_Matrix_Element = 4, 14511 AO_No_Error = 5 14512 }; 14513 } 14514 /// Diagnose invalid operand for address of operations. 14515 /// 14516 /// \param Type The type of operand which cannot have its address taken. 14517 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 14518 Expr *E, unsigned Type) { 14519 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 14520 } 14521 14522 /// CheckAddressOfOperand - The operand of & must be either a function 14523 /// designator or an lvalue designating an object. If it is an lvalue, the 14524 /// object cannot be declared with storage class register or be a bit field. 14525 /// Note: The usual conversions are *not* applied to the operand of the & 14526 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 14527 /// In C++, the operand might be an overloaded function name, in which case 14528 /// we allow the '&' but retain the overloaded-function type. 14529 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 14530 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 14531 if (PTy->getKind() == BuiltinType::Overload) { 14532 Expr *E = OrigOp.get()->IgnoreParens(); 14533 if (!isa<OverloadExpr>(E)) { 14534 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 14535 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 14536 << OrigOp.get()->getSourceRange(); 14537 return QualType(); 14538 } 14539 14540 OverloadExpr *Ovl = cast<OverloadExpr>(E); 14541 if (isa<UnresolvedMemberExpr>(Ovl)) 14542 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 14543 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 14544 << OrigOp.get()->getSourceRange(); 14545 return QualType(); 14546 } 14547 14548 return Context.OverloadTy; 14549 } 14550 14551 if (PTy->getKind() == BuiltinType::UnknownAny) 14552 return Context.UnknownAnyTy; 14553 14554 if (PTy->getKind() == BuiltinType::BoundMember) { 14555 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 14556 << OrigOp.get()->getSourceRange(); 14557 return QualType(); 14558 } 14559 14560 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 14561 if (OrigOp.isInvalid()) return QualType(); 14562 } 14563 14564 if (OrigOp.get()->isTypeDependent()) 14565 return Context.DependentTy; 14566 14567 assert(!OrigOp.get()->hasPlaceholderType()); 14568 14569 // Make sure to ignore parentheses in subsequent checks 14570 Expr *op = OrigOp.get()->IgnoreParens(); 14571 14572 // In OpenCL captures for blocks called as lambda functions 14573 // are located in the private address space. Blocks used in 14574 // enqueue_kernel can be located in a different address space 14575 // depending on a vendor implementation. Thus preventing 14576 // taking an address of the capture to avoid invalid AS casts. 14577 if (LangOpts.OpenCL) { 14578 auto* VarRef = dyn_cast<DeclRefExpr>(op); 14579 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 14580 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 14581 return QualType(); 14582 } 14583 } 14584 14585 if (getLangOpts().C99) { 14586 // Implement C99-only parts of addressof rules. 14587 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 14588 if (uOp->getOpcode() == UO_Deref) 14589 // Per C99 6.5.3.2, the address of a deref always returns a valid result 14590 // (assuming the deref expression is valid). 14591 return uOp->getSubExpr()->getType(); 14592 } 14593 // Technically, there should be a check for array subscript 14594 // expressions here, but the result of one is always an lvalue anyway. 14595 } 14596 ValueDecl *dcl = getPrimaryDecl(op); 14597 14598 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 14599 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 14600 op->getBeginLoc())) 14601 return QualType(); 14602 14603 Expr::LValueClassification lval = op->ClassifyLValue(Context); 14604 unsigned AddressOfError = AO_No_Error; 14605 14606 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 14607 bool sfinae = (bool)isSFINAEContext(); 14608 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 14609 : diag::ext_typecheck_addrof_temporary) 14610 << op->getType() << op->getSourceRange(); 14611 if (sfinae) 14612 return QualType(); 14613 // Materialize the temporary as an lvalue so that we can take its address. 14614 OrigOp = op = 14615 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 14616 } else if (isa<ObjCSelectorExpr>(op)) { 14617 return Context.getPointerType(op->getType()); 14618 } else if (lval == Expr::LV_MemberFunction) { 14619 // If it's an instance method, make a member pointer. 14620 // The expression must have exactly the form &A::foo. 14621 14622 // If the underlying expression isn't a decl ref, give up. 14623 if (!isa<DeclRefExpr>(op)) { 14624 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 14625 << OrigOp.get()->getSourceRange(); 14626 return QualType(); 14627 } 14628 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 14629 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 14630 14631 // The id-expression was parenthesized. 14632 if (OrigOp.get() != DRE) { 14633 Diag(OpLoc, diag::err_parens_pointer_member_function) 14634 << OrigOp.get()->getSourceRange(); 14635 14636 // The method was named without a qualifier. 14637 } else if (!DRE->getQualifier()) { 14638 if (MD->getParent()->getName().empty()) 14639 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 14640 << op->getSourceRange(); 14641 else { 14642 SmallString<32> Str; 14643 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 14644 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 14645 << op->getSourceRange() 14646 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 14647 } 14648 } 14649 14650 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 14651 if (isa<CXXDestructorDecl>(MD)) 14652 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 14653 14654 QualType MPTy = Context.getMemberPointerType( 14655 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 14656 // Under the MS ABI, lock down the inheritance model now. 14657 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 14658 (void)isCompleteType(OpLoc, MPTy); 14659 return MPTy; 14660 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 14661 // C99 6.5.3.2p1 14662 // The operand must be either an l-value or a function designator 14663 if (!op->getType()->isFunctionType()) { 14664 // Use a special diagnostic for loads from property references. 14665 if (isa<PseudoObjectExpr>(op)) { 14666 AddressOfError = AO_Property_Expansion; 14667 } else { 14668 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 14669 << op->getType() << op->getSourceRange(); 14670 return QualType(); 14671 } 14672 } 14673 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 14674 // The operand cannot be a bit-field 14675 AddressOfError = AO_Bit_Field; 14676 } else if (op->getObjectKind() == OK_VectorComponent) { 14677 // The operand cannot be an element of a vector 14678 AddressOfError = AO_Vector_Element; 14679 } else if (op->getObjectKind() == OK_MatrixComponent) { 14680 // The operand cannot be an element of a matrix. 14681 AddressOfError = AO_Matrix_Element; 14682 } else if (dcl) { // C99 6.5.3.2p1 14683 // We have an lvalue with a decl. Make sure the decl is not declared 14684 // with the register storage-class specifier. 14685 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 14686 // in C++ it is not error to take address of a register 14687 // variable (c++03 7.1.1P3) 14688 if (vd->getStorageClass() == SC_Register && 14689 !getLangOpts().CPlusPlus) { 14690 AddressOfError = AO_Register_Variable; 14691 } 14692 } else if (isa<MSPropertyDecl>(dcl)) { 14693 AddressOfError = AO_Property_Expansion; 14694 } else if (isa<FunctionTemplateDecl>(dcl)) { 14695 return Context.OverloadTy; 14696 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 14697 // Okay: we can take the address of a field. 14698 // Could be a pointer to member, though, if there is an explicit 14699 // scope qualifier for the class. 14700 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 14701 DeclContext *Ctx = dcl->getDeclContext(); 14702 if (Ctx && Ctx->isRecord()) { 14703 if (dcl->getType()->isReferenceType()) { 14704 Diag(OpLoc, 14705 diag::err_cannot_form_pointer_to_member_of_reference_type) 14706 << dcl->getDeclName() << dcl->getType(); 14707 return QualType(); 14708 } 14709 14710 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 14711 Ctx = Ctx->getParent(); 14712 14713 QualType MPTy = Context.getMemberPointerType( 14714 op->getType(), 14715 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 14716 // Under the MS ABI, lock down the inheritance model now. 14717 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 14718 (void)isCompleteType(OpLoc, MPTy); 14719 return MPTy; 14720 } 14721 } 14722 } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl, 14723 MSGuidDecl, UnnamedGlobalConstantDecl>(dcl)) 14724 llvm_unreachable("Unknown/unexpected decl type"); 14725 } 14726 14727 if (AddressOfError != AO_No_Error) { 14728 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 14729 return QualType(); 14730 } 14731 14732 if (lval == Expr::LV_IncompleteVoidType) { 14733 // Taking the address of a void variable is technically illegal, but we 14734 // allow it in cases which are otherwise valid. 14735 // Example: "extern void x; void* y = &x;". 14736 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 14737 } 14738 14739 // If the operand has type "type", the result has type "pointer to type". 14740 if (op->getType()->isObjCObjectType()) 14741 return Context.getObjCObjectPointerType(op->getType()); 14742 14743 CheckAddressOfPackedMember(op); 14744 14745 return Context.getPointerType(op->getType()); 14746 } 14747 14748 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 14749 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 14750 if (!DRE) 14751 return; 14752 const Decl *D = DRE->getDecl(); 14753 if (!D) 14754 return; 14755 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 14756 if (!Param) 14757 return; 14758 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 14759 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 14760 return; 14761 if (FunctionScopeInfo *FD = S.getCurFunction()) 14762 FD->ModifiedNonNullParams.insert(Param); 14763 } 14764 14765 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 14766 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 14767 SourceLocation OpLoc, 14768 bool IsAfterAmp = false) { 14769 if (Op->isTypeDependent()) 14770 return S.Context.DependentTy; 14771 14772 ExprResult ConvResult = S.UsualUnaryConversions(Op); 14773 if (ConvResult.isInvalid()) 14774 return QualType(); 14775 Op = ConvResult.get(); 14776 QualType OpTy = Op->getType(); 14777 QualType Result; 14778 14779 if (isa<CXXReinterpretCastExpr>(Op)) { 14780 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 14781 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 14782 Op->getSourceRange()); 14783 } 14784 14785 if (const PointerType *PT = OpTy->getAs<PointerType>()) 14786 { 14787 Result = PT->getPointeeType(); 14788 } 14789 else if (const ObjCObjectPointerType *OPT = 14790 OpTy->getAs<ObjCObjectPointerType>()) 14791 Result = OPT->getPointeeType(); 14792 else { 14793 ExprResult PR = S.CheckPlaceholderExpr(Op); 14794 if (PR.isInvalid()) return QualType(); 14795 if (PR.get() != Op) 14796 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 14797 } 14798 14799 if (Result.isNull()) { 14800 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 14801 << OpTy << Op->getSourceRange(); 14802 return QualType(); 14803 } 14804 14805 if (Result->isVoidType()) { 14806 // C++ [expr.unary.op]p1: 14807 // [...] the expression to which [the unary * operator] is applied shall 14808 // be a pointer to an object type, or a pointer to a function type 14809 LangOptions LO = S.getLangOpts(); 14810 if (LO.CPlusPlus) 14811 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer_cpp) 14812 << OpTy << Op->getSourceRange(); 14813 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext()) 14814 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 14815 << OpTy << Op->getSourceRange(); 14816 } 14817 14818 // Dereferences are usually l-values... 14819 VK = VK_LValue; 14820 14821 // ...except that certain expressions are never l-values in C. 14822 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 14823 VK = VK_PRValue; 14824 14825 return Result; 14826 } 14827 14828 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 14829 BinaryOperatorKind Opc; 14830 switch (Kind) { 14831 default: llvm_unreachable("Unknown binop!"); 14832 case tok::periodstar: Opc = BO_PtrMemD; break; 14833 case tok::arrowstar: Opc = BO_PtrMemI; break; 14834 case tok::star: Opc = BO_Mul; break; 14835 case tok::slash: Opc = BO_Div; break; 14836 case tok::percent: Opc = BO_Rem; break; 14837 case tok::plus: Opc = BO_Add; break; 14838 case tok::minus: Opc = BO_Sub; break; 14839 case tok::lessless: Opc = BO_Shl; break; 14840 case tok::greatergreater: Opc = BO_Shr; break; 14841 case tok::lessequal: Opc = BO_LE; break; 14842 case tok::less: Opc = BO_LT; break; 14843 case tok::greaterequal: Opc = BO_GE; break; 14844 case tok::greater: Opc = BO_GT; break; 14845 case tok::exclaimequal: Opc = BO_NE; break; 14846 case tok::equalequal: Opc = BO_EQ; break; 14847 case tok::spaceship: Opc = BO_Cmp; break; 14848 case tok::amp: Opc = BO_And; break; 14849 case tok::caret: Opc = BO_Xor; break; 14850 case tok::pipe: Opc = BO_Or; break; 14851 case tok::ampamp: Opc = BO_LAnd; break; 14852 case tok::pipepipe: Opc = BO_LOr; break; 14853 case tok::equal: Opc = BO_Assign; break; 14854 case tok::starequal: Opc = BO_MulAssign; break; 14855 case tok::slashequal: Opc = BO_DivAssign; break; 14856 case tok::percentequal: Opc = BO_RemAssign; break; 14857 case tok::plusequal: Opc = BO_AddAssign; break; 14858 case tok::minusequal: Opc = BO_SubAssign; break; 14859 case tok::lesslessequal: Opc = BO_ShlAssign; break; 14860 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 14861 case tok::ampequal: Opc = BO_AndAssign; break; 14862 case tok::caretequal: Opc = BO_XorAssign; break; 14863 case tok::pipeequal: Opc = BO_OrAssign; break; 14864 case tok::comma: Opc = BO_Comma; break; 14865 } 14866 return Opc; 14867 } 14868 14869 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 14870 tok::TokenKind Kind) { 14871 UnaryOperatorKind Opc; 14872 switch (Kind) { 14873 default: llvm_unreachable("Unknown unary op!"); 14874 case tok::plusplus: Opc = UO_PreInc; break; 14875 case tok::minusminus: Opc = UO_PreDec; break; 14876 case tok::amp: Opc = UO_AddrOf; break; 14877 case tok::star: Opc = UO_Deref; break; 14878 case tok::plus: Opc = UO_Plus; break; 14879 case tok::minus: Opc = UO_Minus; break; 14880 case tok::tilde: Opc = UO_Not; break; 14881 case tok::exclaim: Opc = UO_LNot; break; 14882 case tok::kw___real: Opc = UO_Real; break; 14883 case tok::kw___imag: Opc = UO_Imag; break; 14884 case tok::kw___extension__: Opc = UO_Extension; break; 14885 } 14886 return Opc; 14887 } 14888 14889 const FieldDecl * 14890 Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) { 14891 // Explore the case for adding 'this->' to the LHS of a self assignment, very 14892 // common for setters. 14893 // struct A { 14894 // int X; 14895 // -void setX(int X) { X = X; } 14896 // +void setX(int X) { this->X = X; } 14897 // }; 14898 14899 // Only consider parameters for self assignment fixes. 14900 if (!isa<ParmVarDecl>(SelfAssigned)) 14901 return nullptr; 14902 const auto *Method = 14903 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true)); 14904 if (!Method) 14905 return nullptr; 14906 14907 const CXXRecordDecl *Parent = Method->getParent(); 14908 // In theory this is fixable if the lambda explicitly captures this, but 14909 // that's added complexity that's rarely going to be used. 14910 if (Parent->isLambda()) 14911 return nullptr; 14912 14913 // FIXME: Use an actual Lookup operation instead of just traversing fields 14914 // in order to get base class fields. 14915 auto Field = 14916 llvm::find_if(Parent->fields(), 14917 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) { 14918 return F->getDeclName() == Name; 14919 }); 14920 return (Field != Parent->field_end()) ? *Field : nullptr; 14921 } 14922 14923 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 14924 /// This warning suppressed in the event of macro expansions. 14925 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 14926 SourceLocation OpLoc, bool IsBuiltin) { 14927 if (S.inTemplateInstantiation()) 14928 return; 14929 if (S.isUnevaluatedContext()) 14930 return; 14931 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 14932 return; 14933 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 14934 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 14935 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 14936 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 14937 if (!LHSDeclRef || !RHSDeclRef || 14938 LHSDeclRef->getLocation().isMacroID() || 14939 RHSDeclRef->getLocation().isMacroID()) 14940 return; 14941 const ValueDecl *LHSDecl = 14942 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 14943 const ValueDecl *RHSDecl = 14944 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 14945 if (LHSDecl != RHSDecl) 14946 return; 14947 if (LHSDecl->getType().isVolatileQualified()) 14948 return; 14949 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 14950 if (RefTy->getPointeeType().isVolatileQualified()) 14951 return; 14952 14953 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 14954 : diag::warn_self_assignment_overloaded) 14955 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 14956 << RHSExpr->getSourceRange(); 14957 if (const FieldDecl *SelfAssignField = 14958 S.getSelfAssignmentClassMemberCandidate(RHSDecl)) 14959 Diag << 1 << SelfAssignField 14960 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->"); 14961 else 14962 Diag << 0; 14963 } 14964 14965 /// Check if a bitwise-& is performed on an Objective-C pointer. This 14966 /// is usually indicative of introspection within the Objective-C pointer. 14967 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 14968 SourceLocation OpLoc) { 14969 if (!S.getLangOpts().ObjC) 14970 return; 14971 14972 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 14973 const Expr *LHS = L.get(); 14974 const Expr *RHS = R.get(); 14975 14976 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 14977 ObjCPointerExpr = LHS; 14978 OtherExpr = RHS; 14979 } 14980 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 14981 ObjCPointerExpr = RHS; 14982 OtherExpr = LHS; 14983 } 14984 14985 // This warning is deliberately made very specific to reduce false 14986 // positives with logic that uses '&' for hashing. This logic mainly 14987 // looks for code trying to introspect into tagged pointers, which 14988 // code should generally never do. 14989 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 14990 unsigned Diag = diag::warn_objc_pointer_masking; 14991 // Determine if we are introspecting the result of performSelectorXXX. 14992 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 14993 // Special case messages to -performSelector and friends, which 14994 // can return non-pointer values boxed in a pointer value. 14995 // Some clients may wish to silence warnings in this subcase. 14996 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 14997 Selector S = ME->getSelector(); 14998 StringRef SelArg0 = S.getNameForSlot(0); 14999 if (SelArg0.startswith("performSelector")) 15000 Diag = diag::warn_objc_pointer_masking_performSelector; 15001 } 15002 15003 S.Diag(OpLoc, Diag) 15004 << ObjCPointerExpr->getSourceRange(); 15005 } 15006 } 15007 15008 static NamedDecl *getDeclFromExpr(Expr *E) { 15009 if (!E) 15010 return nullptr; 15011 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 15012 return DRE->getDecl(); 15013 if (auto *ME = dyn_cast<MemberExpr>(E)) 15014 return ME->getMemberDecl(); 15015 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 15016 return IRE->getDecl(); 15017 return nullptr; 15018 } 15019 15020 // This helper function promotes a binary operator's operands (which are of a 15021 // half vector type) to a vector of floats and then truncates the result to 15022 // a vector of either half or short. 15023 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 15024 BinaryOperatorKind Opc, QualType ResultTy, 15025 ExprValueKind VK, ExprObjectKind OK, 15026 bool IsCompAssign, SourceLocation OpLoc, 15027 FPOptionsOverride FPFeatures) { 15028 auto &Context = S.getASTContext(); 15029 assert((isVector(ResultTy, Context.HalfTy) || 15030 isVector(ResultTy, Context.ShortTy)) && 15031 "Result must be a vector of half or short"); 15032 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 15033 isVector(RHS.get()->getType(), Context.HalfTy) && 15034 "both operands expected to be a half vector"); 15035 15036 RHS = convertVector(RHS.get(), Context.FloatTy, S); 15037 QualType BinOpResTy = RHS.get()->getType(); 15038 15039 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 15040 // change BinOpResTy to a vector of ints. 15041 if (isVector(ResultTy, Context.ShortTy)) 15042 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 15043 15044 if (IsCompAssign) 15045 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc, 15046 ResultTy, VK, OK, OpLoc, FPFeatures, 15047 BinOpResTy, BinOpResTy); 15048 15049 LHS = convertVector(LHS.get(), Context.FloatTy, S); 15050 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, 15051 BinOpResTy, VK, OK, OpLoc, FPFeatures); 15052 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S); 15053 } 15054 15055 static std::pair<ExprResult, ExprResult> 15056 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 15057 Expr *RHSExpr) { 15058 ExprResult LHS = LHSExpr, RHS = RHSExpr; 15059 if (!S.Context.isDependenceAllowed()) { 15060 // C cannot handle TypoExpr nodes on either side of a binop because it 15061 // doesn't handle dependent types properly, so make sure any TypoExprs have 15062 // been dealt with before checking the operands. 15063 LHS = S.CorrectDelayedTyposInExpr(LHS); 15064 RHS = S.CorrectDelayedTyposInExpr( 15065 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 15066 [Opc, LHS](Expr *E) { 15067 if (Opc != BO_Assign) 15068 return ExprResult(E); 15069 // Avoid correcting the RHS to the same Expr as the LHS. 15070 Decl *D = getDeclFromExpr(E); 15071 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 15072 }); 15073 } 15074 return std::make_pair(LHS, RHS); 15075 } 15076 15077 /// Returns true if conversion between vectors of halfs and vectors of floats 15078 /// is needed. 15079 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 15080 Expr *E0, Expr *E1 = nullptr) { 15081 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType || 15082 Ctx.getTargetInfo().useFP16ConversionIntrinsics()) 15083 return false; 15084 15085 auto HasVectorOfHalfType = [&Ctx](Expr *E) { 15086 QualType Ty = E->IgnoreImplicit()->getType(); 15087 15088 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h 15089 // to vectors of floats. Although the element type of the vectors is __fp16, 15090 // the vectors shouldn't be treated as storage-only types. See the 15091 // discussion here: https://reviews.llvm.org/rG825235c140e7 15092 if (const VectorType *VT = Ty->getAs<VectorType>()) { 15093 if (VT->getVectorKind() == VectorType::NeonVector) 15094 return false; 15095 return VT->getElementType().getCanonicalType() == Ctx.HalfTy; 15096 } 15097 return false; 15098 }; 15099 15100 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1)); 15101 } 15102 15103 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 15104 /// operator @p Opc at location @c TokLoc. This routine only supports 15105 /// built-in operations; ActOnBinOp handles overloaded operators. 15106 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 15107 BinaryOperatorKind Opc, 15108 Expr *LHSExpr, Expr *RHSExpr) { 15109 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 15110 // The syntax only allows initializer lists on the RHS of assignment, 15111 // so we don't need to worry about accepting invalid code for 15112 // non-assignment operators. 15113 // C++11 5.17p9: 15114 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 15115 // of x = {} is x = T(). 15116 InitializationKind Kind = InitializationKind::CreateDirectList( 15117 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 15118 InitializedEntity Entity = 15119 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 15120 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 15121 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 15122 if (Init.isInvalid()) 15123 return Init; 15124 RHSExpr = Init.get(); 15125 } 15126 15127 ExprResult LHS = LHSExpr, RHS = RHSExpr; 15128 QualType ResultTy; // Result type of the binary operator. 15129 // The following two variables are used for compound assignment operators 15130 QualType CompLHSTy; // Type of LHS after promotions for computation 15131 QualType CompResultTy; // Type of computation result 15132 ExprValueKind VK = VK_PRValue; 15133 ExprObjectKind OK = OK_Ordinary; 15134 bool ConvertHalfVec = false; 15135 15136 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 15137 if (!LHS.isUsable() || !RHS.isUsable()) 15138 return ExprError(); 15139 15140 if (getLangOpts().OpenCL) { 15141 QualType LHSTy = LHSExpr->getType(); 15142 QualType RHSTy = RHSExpr->getType(); 15143 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 15144 // the ATOMIC_VAR_INIT macro. 15145 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 15146 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 15147 if (BO_Assign == Opc) 15148 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 15149 else 15150 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 15151 return ExprError(); 15152 } 15153 15154 // OpenCL special types - image, sampler, pipe, and blocks are to be used 15155 // only with a builtin functions and therefore should be disallowed here. 15156 if (LHSTy->isImageType() || RHSTy->isImageType() || 15157 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 15158 LHSTy->isPipeType() || RHSTy->isPipeType() || 15159 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 15160 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 15161 return ExprError(); 15162 } 15163 } 15164 15165 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 15166 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr); 15167 15168 switch (Opc) { 15169 case BO_Assign: 15170 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc); 15171 if (getLangOpts().CPlusPlus && 15172 LHS.get()->getObjectKind() != OK_ObjCProperty) { 15173 VK = LHS.get()->getValueKind(); 15174 OK = LHS.get()->getObjectKind(); 15175 } 15176 if (!ResultTy.isNull()) { 15177 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 15178 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 15179 15180 // Avoid copying a block to the heap if the block is assigned to a local 15181 // auto variable that is declared in the same scope as the block. This 15182 // optimization is unsafe if the local variable is declared in an outer 15183 // scope. For example: 15184 // 15185 // BlockTy b; 15186 // { 15187 // b = ^{...}; 15188 // } 15189 // // It is unsafe to invoke the block here if it wasn't copied to the 15190 // // heap. 15191 // b(); 15192 15193 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens())) 15194 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens())) 15195 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 15196 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD)) 15197 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 15198 15199 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion()) 15200 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(), 15201 NTCUC_Assignment, NTCUK_Copy); 15202 } 15203 RecordModifiableNonNullParam(*this, LHS.get()); 15204 break; 15205 case BO_PtrMemD: 15206 case BO_PtrMemI: 15207 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 15208 Opc == BO_PtrMemI); 15209 break; 15210 case BO_Mul: 15211 case BO_Div: 15212 ConvertHalfVec = true; 15213 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 15214 Opc == BO_Div); 15215 break; 15216 case BO_Rem: 15217 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 15218 break; 15219 case BO_Add: 15220 ConvertHalfVec = true; 15221 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 15222 break; 15223 case BO_Sub: 15224 ConvertHalfVec = true; 15225 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 15226 break; 15227 case BO_Shl: 15228 case BO_Shr: 15229 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 15230 break; 15231 case BO_LE: 15232 case BO_LT: 15233 case BO_GE: 15234 case BO_GT: 15235 ConvertHalfVec = true; 15236 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 15237 break; 15238 case BO_EQ: 15239 case BO_NE: 15240 ConvertHalfVec = true; 15241 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 15242 break; 15243 case BO_Cmp: 15244 ConvertHalfVec = true; 15245 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 15246 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 15247 break; 15248 case BO_And: 15249 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 15250 [[fallthrough]]; 15251 case BO_Xor: 15252 case BO_Or: 15253 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 15254 break; 15255 case BO_LAnd: 15256 case BO_LOr: 15257 ConvertHalfVec = true; 15258 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 15259 break; 15260 case BO_MulAssign: 15261 case BO_DivAssign: 15262 ConvertHalfVec = true; 15263 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 15264 Opc == BO_DivAssign); 15265 CompLHSTy = CompResultTy; 15266 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 15267 ResultTy = 15268 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc); 15269 break; 15270 case BO_RemAssign: 15271 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 15272 CompLHSTy = CompResultTy; 15273 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 15274 ResultTy = 15275 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc); 15276 break; 15277 case BO_AddAssign: 15278 ConvertHalfVec = true; 15279 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 15280 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 15281 ResultTy = 15282 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc); 15283 break; 15284 case BO_SubAssign: 15285 ConvertHalfVec = true; 15286 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 15287 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 15288 ResultTy = 15289 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc); 15290 break; 15291 case BO_ShlAssign: 15292 case BO_ShrAssign: 15293 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 15294 CompLHSTy = CompResultTy; 15295 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 15296 ResultTy = 15297 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc); 15298 break; 15299 case BO_AndAssign: 15300 case BO_OrAssign: // fallthrough 15301 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 15302 [[fallthrough]]; 15303 case BO_XorAssign: 15304 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 15305 CompLHSTy = CompResultTy; 15306 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 15307 ResultTy = 15308 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc); 15309 break; 15310 case BO_Comma: 15311 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 15312 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 15313 VK = RHS.get()->getValueKind(); 15314 OK = RHS.get()->getObjectKind(); 15315 } 15316 break; 15317 } 15318 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 15319 return ExprError(); 15320 15321 // Some of the binary operations require promoting operands of half vector to 15322 // float vectors and truncating the result back to half vector. For now, we do 15323 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 15324 // arm64). 15325 assert( 15326 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) == 15327 isVector(LHS.get()->getType(), Context.HalfTy)) && 15328 "both sides are half vectors or neither sides are"); 15329 ConvertHalfVec = 15330 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get()); 15331 15332 // Check for array bounds violations for both sides of the BinaryOperator 15333 CheckArrayAccess(LHS.get()); 15334 CheckArrayAccess(RHS.get()); 15335 15336 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 15337 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 15338 &Context.Idents.get("object_setClass"), 15339 SourceLocation(), LookupOrdinaryName); 15340 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 15341 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 15342 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 15343 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 15344 "object_setClass(") 15345 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 15346 ",") 15347 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 15348 } 15349 else 15350 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 15351 } 15352 else if (const ObjCIvarRefExpr *OIRE = 15353 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 15354 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 15355 15356 // Opc is not a compound assignment if CompResultTy is null. 15357 if (CompResultTy.isNull()) { 15358 if (ConvertHalfVec) 15359 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 15360 OpLoc, CurFPFeatureOverrides()); 15361 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy, 15362 VK, OK, OpLoc, CurFPFeatureOverrides()); 15363 } 15364 15365 // Handle compound assignments. 15366 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 15367 OK_ObjCProperty) { 15368 VK = VK_LValue; 15369 OK = LHS.get()->getObjectKind(); 15370 } 15371 15372 // The LHS is not converted to the result type for fixed-point compound 15373 // assignment as the common type is computed on demand. Reset the CompLHSTy 15374 // to the LHS type we would have gotten after unary conversions. 15375 if (CompResultTy->isFixedPointType()) 15376 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType(); 15377 15378 if (ConvertHalfVec) 15379 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 15380 OpLoc, CurFPFeatureOverrides()); 15381 15382 return CompoundAssignOperator::Create( 15383 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc, 15384 CurFPFeatureOverrides(), CompLHSTy, CompResultTy); 15385 } 15386 15387 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 15388 /// operators are mixed in a way that suggests that the programmer forgot that 15389 /// comparison operators have higher precedence. The most typical example of 15390 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 15391 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 15392 SourceLocation OpLoc, Expr *LHSExpr, 15393 Expr *RHSExpr) { 15394 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 15395 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 15396 15397 // Check that one of the sides is a comparison operator and the other isn't. 15398 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 15399 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 15400 if (isLeftComp == isRightComp) 15401 return; 15402 15403 // Bitwise operations are sometimes used as eager logical ops. 15404 // Don't diagnose this. 15405 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 15406 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 15407 if (isLeftBitwise || isRightBitwise) 15408 return; 15409 15410 SourceRange DiagRange = isLeftComp 15411 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 15412 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 15413 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 15414 SourceRange ParensRange = 15415 isLeftComp 15416 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 15417 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 15418 15419 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 15420 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 15421 SuggestParentheses(Self, OpLoc, 15422 Self.PDiag(diag::note_precedence_silence) << OpStr, 15423 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 15424 SuggestParentheses(Self, OpLoc, 15425 Self.PDiag(diag::note_precedence_bitwise_first) 15426 << BinaryOperator::getOpcodeStr(Opc), 15427 ParensRange); 15428 } 15429 15430 /// It accepts a '&&' expr that is inside a '||' one. 15431 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 15432 /// in parentheses. 15433 static void 15434 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 15435 BinaryOperator *Bop) { 15436 assert(Bop->getOpcode() == BO_LAnd); 15437 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 15438 << Bop->getSourceRange() << OpLoc; 15439 SuggestParentheses(Self, Bop->getOperatorLoc(), 15440 Self.PDiag(diag::note_precedence_silence) 15441 << Bop->getOpcodeStr(), 15442 Bop->getSourceRange()); 15443 } 15444 15445 /// Look for '&&' in the left hand of a '||' expr. 15446 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 15447 Expr *LHSExpr, Expr *RHSExpr) { 15448 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 15449 if (Bop->getOpcode() == BO_LAnd) { 15450 // If it's "string_literal && a || b" don't warn since the precedence 15451 // doesn't matter. 15452 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts())) 15453 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 15454 } else if (Bop->getOpcode() == BO_LOr) { 15455 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 15456 // If it's "a || b && string_literal || c" we didn't warn earlier for 15457 // "a || b && string_literal", but warn now. 15458 if (RBop->getOpcode() == BO_LAnd && 15459 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts())) 15460 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 15461 } 15462 } 15463 } 15464 } 15465 15466 /// Look for '&&' in the right hand of a '||' expr. 15467 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 15468 Expr *LHSExpr, Expr *RHSExpr) { 15469 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 15470 if (Bop->getOpcode() == BO_LAnd) { 15471 // If it's "a || b && string_literal" don't warn since the precedence 15472 // doesn't matter. 15473 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts())) 15474 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 15475 } 15476 } 15477 } 15478 15479 /// Look for bitwise op in the left or right hand of a bitwise op with 15480 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 15481 /// the '&' expression in parentheses. 15482 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 15483 SourceLocation OpLoc, Expr *SubExpr) { 15484 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 15485 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 15486 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 15487 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 15488 << Bop->getSourceRange() << OpLoc; 15489 SuggestParentheses(S, Bop->getOperatorLoc(), 15490 S.PDiag(diag::note_precedence_silence) 15491 << Bop->getOpcodeStr(), 15492 Bop->getSourceRange()); 15493 } 15494 } 15495 } 15496 15497 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 15498 Expr *SubExpr, StringRef Shift) { 15499 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 15500 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 15501 StringRef Op = Bop->getOpcodeStr(); 15502 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 15503 << Bop->getSourceRange() << OpLoc << Shift << Op; 15504 SuggestParentheses(S, Bop->getOperatorLoc(), 15505 S.PDiag(diag::note_precedence_silence) << Op, 15506 Bop->getSourceRange()); 15507 } 15508 } 15509 } 15510 15511 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 15512 Expr *LHSExpr, Expr *RHSExpr) { 15513 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 15514 if (!OCE) 15515 return; 15516 15517 FunctionDecl *FD = OCE->getDirectCallee(); 15518 if (!FD || !FD->isOverloadedOperator()) 15519 return; 15520 15521 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 15522 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 15523 return; 15524 15525 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 15526 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 15527 << (Kind == OO_LessLess); 15528 SuggestParentheses(S, OCE->getOperatorLoc(), 15529 S.PDiag(diag::note_precedence_silence) 15530 << (Kind == OO_LessLess ? "<<" : ">>"), 15531 OCE->getSourceRange()); 15532 SuggestParentheses( 15533 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 15534 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 15535 } 15536 15537 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 15538 /// precedence. 15539 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 15540 SourceLocation OpLoc, Expr *LHSExpr, 15541 Expr *RHSExpr){ 15542 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 15543 if (BinaryOperator::isBitwiseOp(Opc)) 15544 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 15545 15546 // Diagnose "arg1 & arg2 | arg3" 15547 if ((Opc == BO_Or || Opc == BO_Xor) && 15548 !OpLoc.isMacroID()/* Don't warn in macros. */) { 15549 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 15550 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 15551 } 15552 15553 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 15554 // We don't warn for 'assert(a || b && "bad")' since this is safe. 15555 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 15556 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 15557 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 15558 } 15559 15560 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 15561 || Opc == BO_Shr) { 15562 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 15563 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 15564 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 15565 } 15566 15567 // Warn on overloaded shift operators and comparisons, such as: 15568 // cout << 5 == 4; 15569 if (BinaryOperator::isComparisonOp(Opc)) 15570 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 15571 } 15572 15573 // Binary Operators. 'Tok' is the token for the operator. 15574 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 15575 tok::TokenKind Kind, 15576 Expr *LHSExpr, Expr *RHSExpr) { 15577 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 15578 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 15579 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 15580 15581 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 15582 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 15583 15584 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 15585 } 15586 15587 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, 15588 UnresolvedSetImpl &Functions) { 15589 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc); 15590 if (OverOp != OO_None && OverOp != OO_Equal) 15591 LookupOverloadedOperatorName(OverOp, S, Functions); 15592 15593 // In C++20 onwards, we may have a second operator to look up. 15594 if (getLangOpts().CPlusPlus20) { 15595 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp)) 15596 LookupOverloadedOperatorName(ExtraOp, S, Functions); 15597 } 15598 } 15599 15600 /// Build an overloaded binary operator expression in the given scope. 15601 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 15602 BinaryOperatorKind Opc, 15603 Expr *LHS, Expr *RHS) { 15604 switch (Opc) { 15605 case BO_Assign: 15606 case BO_DivAssign: 15607 case BO_RemAssign: 15608 case BO_SubAssign: 15609 case BO_AndAssign: 15610 case BO_OrAssign: 15611 case BO_XorAssign: 15612 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 15613 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 15614 break; 15615 default: 15616 break; 15617 } 15618 15619 // Find all of the overloaded operators visible from this point. 15620 UnresolvedSet<16> Functions; 15621 S.LookupBinOp(Sc, OpLoc, Opc, Functions); 15622 15623 // Build the (potentially-overloaded, potentially-dependent) 15624 // binary operation. 15625 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 15626 } 15627 15628 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 15629 BinaryOperatorKind Opc, 15630 Expr *LHSExpr, Expr *RHSExpr) { 15631 ExprResult LHS, RHS; 15632 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 15633 if (!LHS.isUsable() || !RHS.isUsable()) 15634 return ExprError(); 15635 LHSExpr = LHS.get(); 15636 RHSExpr = RHS.get(); 15637 15638 // We want to end up calling one of checkPseudoObjectAssignment 15639 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 15640 // both expressions are overloadable or either is type-dependent), 15641 // or CreateBuiltinBinOp (in any other case). We also want to get 15642 // any placeholder types out of the way. 15643 15644 // Handle pseudo-objects in the LHS. 15645 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 15646 // Assignments with a pseudo-object l-value need special analysis. 15647 if (pty->getKind() == BuiltinType::PseudoObject && 15648 BinaryOperator::isAssignmentOp(Opc)) 15649 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 15650 15651 // Don't resolve overloads if the other type is overloadable. 15652 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 15653 // We can't actually test that if we still have a placeholder, 15654 // though. Fortunately, none of the exceptions we see in that 15655 // code below are valid when the LHS is an overload set. Note 15656 // that an overload set can be dependently-typed, but it never 15657 // instantiates to having an overloadable type. 15658 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 15659 if (resolvedRHS.isInvalid()) return ExprError(); 15660 RHSExpr = resolvedRHS.get(); 15661 15662 if (RHSExpr->isTypeDependent() || 15663 RHSExpr->getType()->isOverloadableType()) 15664 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15665 } 15666 15667 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 15668 // template, diagnose the missing 'template' keyword instead of diagnosing 15669 // an invalid use of a bound member function. 15670 // 15671 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 15672 // to C++1z [over.over]/1.4, but we already checked for that case above. 15673 if (Opc == BO_LT && inTemplateInstantiation() && 15674 (pty->getKind() == BuiltinType::BoundMember || 15675 pty->getKind() == BuiltinType::Overload)) { 15676 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 15677 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 15678 llvm::any_of(OE->decls(), [](NamedDecl *ND) { 15679 return isa<FunctionTemplateDecl>(ND); 15680 })) { 15681 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 15682 : OE->getNameLoc(), 15683 diag::err_template_kw_missing) 15684 << OE->getName().getAsString() << ""; 15685 return ExprError(); 15686 } 15687 } 15688 15689 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 15690 if (LHS.isInvalid()) return ExprError(); 15691 LHSExpr = LHS.get(); 15692 } 15693 15694 // Handle pseudo-objects in the RHS. 15695 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 15696 // An overload in the RHS can potentially be resolved by the type 15697 // being assigned to. 15698 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 15699 if (getLangOpts().CPlusPlus && 15700 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 15701 LHSExpr->getType()->isOverloadableType())) 15702 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15703 15704 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 15705 } 15706 15707 // Don't resolve overloads if the other type is overloadable. 15708 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 15709 LHSExpr->getType()->isOverloadableType()) 15710 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15711 15712 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 15713 if (!resolvedRHS.isUsable()) return ExprError(); 15714 RHSExpr = resolvedRHS.get(); 15715 } 15716 15717 if (getLangOpts().CPlusPlus) { 15718 // If either expression is type-dependent, always build an 15719 // overloaded op. 15720 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 15721 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15722 15723 // Otherwise, build an overloaded op if either expression has an 15724 // overloadable type. 15725 if (LHSExpr->getType()->isOverloadableType() || 15726 RHSExpr->getType()->isOverloadableType()) 15727 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 15728 } 15729 15730 if (getLangOpts().RecoveryAST && 15731 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) { 15732 assert(!getLangOpts().CPlusPlus); 15733 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) && 15734 "Should only occur in error-recovery path."); 15735 if (BinaryOperator::isCompoundAssignmentOp(Opc)) 15736 // C [6.15.16] p3: 15737 // An assignment expression has the value of the left operand after the 15738 // assignment, but is not an lvalue. 15739 return CompoundAssignOperator::Create( 15740 Context, LHSExpr, RHSExpr, Opc, 15741 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary, 15742 OpLoc, CurFPFeatureOverrides()); 15743 QualType ResultType; 15744 switch (Opc) { 15745 case BO_Assign: 15746 ResultType = LHSExpr->getType().getUnqualifiedType(); 15747 break; 15748 case BO_LT: 15749 case BO_GT: 15750 case BO_LE: 15751 case BO_GE: 15752 case BO_EQ: 15753 case BO_NE: 15754 case BO_LAnd: 15755 case BO_LOr: 15756 // These operators have a fixed result type regardless of operands. 15757 ResultType = Context.IntTy; 15758 break; 15759 case BO_Comma: 15760 ResultType = RHSExpr->getType(); 15761 break; 15762 default: 15763 ResultType = Context.DependentTy; 15764 break; 15765 } 15766 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType, 15767 VK_PRValue, OK_Ordinary, OpLoc, 15768 CurFPFeatureOverrides()); 15769 } 15770 15771 // Build a built-in binary operation. 15772 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 15773 } 15774 15775 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 15776 if (T.isNull() || T->isDependentType()) 15777 return false; 15778 15779 if (!Ctx.isPromotableIntegerType(T)) 15780 return true; 15781 15782 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 15783 } 15784 15785 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 15786 UnaryOperatorKind Opc, Expr *InputExpr, 15787 bool IsAfterAmp) { 15788 ExprResult Input = InputExpr; 15789 ExprValueKind VK = VK_PRValue; 15790 ExprObjectKind OK = OK_Ordinary; 15791 QualType resultType; 15792 bool CanOverflow = false; 15793 15794 bool ConvertHalfVec = false; 15795 if (getLangOpts().OpenCL) { 15796 QualType Ty = InputExpr->getType(); 15797 // The only legal unary operation for atomics is '&'. 15798 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 15799 // OpenCL special types - image, sampler, pipe, and blocks are to be used 15800 // only with a builtin functions and therefore should be disallowed here. 15801 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 15802 || Ty->isBlockPointerType())) { 15803 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15804 << InputExpr->getType() 15805 << Input.get()->getSourceRange()); 15806 } 15807 } 15808 15809 if (getLangOpts().HLSL && OpLoc.isValid()) { 15810 if (Opc == UO_AddrOf) 15811 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0); 15812 if (Opc == UO_Deref) 15813 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1); 15814 } 15815 15816 switch (Opc) { 15817 case UO_PreInc: 15818 case UO_PreDec: 15819 case UO_PostInc: 15820 case UO_PostDec: 15821 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 15822 OpLoc, 15823 Opc == UO_PreInc || 15824 Opc == UO_PostInc, 15825 Opc == UO_PreInc || 15826 Opc == UO_PreDec); 15827 CanOverflow = isOverflowingIntegerType(Context, resultType); 15828 break; 15829 case UO_AddrOf: 15830 resultType = CheckAddressOfOperand(Input, OpLoc); 15831 CheckAddressOfNoDeref(InputExpr); 15832 RecordModifiableNonNullParam(*this, InputExpr); 15833 break; 15834 case UO_Deref: { 15835 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 15836 if (Input.isInvalid()) return ExprError(); 15837 resultType = 15838 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp); 15839 break; 15840 } 15841 case UO_Plus: 15842 case UO_Minus: 15843 CanOverflow = Opc == UO_Minus && 15844 isOverflowingIntegerType(Context, Input.get()->getType()); 15845 Input = UsualUnaryConversions(Input.get()); 15846 if (Input.isInvalid()) return ExprError(); 15847 // Unary plus and minus require promoting an operand of half vector to a 15848 // float vector and truncating the result back to a half vector. For now, we 15849 // do this only when HalfArgsAndReturns is set (that is, when the target is 15850 // arm or arm64). 15851 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get()); 15852 15853 // If the operand is a half vector, promote it to a float vector. 15854 if (ConvertHalfVec) 15855 Input = convertVector(Input.get(), Context.FloatTy, *this); 15856 resultType = Input.get()->getType(); 15857 if (resultType->isDependentType()) 15858 break; 15859 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 15860 break; 15861 else if (resultType->isVectorType() && 15862 // The z vector extensions don't allow + or - with bool vectors. 15863 (!Context.getLangOpts().ZVector || 15864 resultType->castAs<VectorType>()->getVectorKind() != 15865 VectorType::AltiVecBool)) 15866 break; 15867 else if (resultType->isVLSTBuiltinType()) // SVE vectors allow + and - 15868 break; 15869 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 15870 Opc == UO_Plus && 15871 resultType->isPointerType()) 15872 break; 15873 15874 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15875 << resultType << Input.get()->getSourceRange()); 15876 15877 case UO_Not: // bitwise complement 15878 Input = UsualUnaryConversions(Input.get()); 15879 if (Input.isInvalid()) 15880 return ExprError(); 15881 resultType = Input.get()->getType(); 15882 if (resultType->isDependentType()) 15883 break; 15884 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 15885 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 15886 // C99 does not support '~' for complex conjugation. 15887 Diag(OpLoc, diag::ext_integer_complement_complex) 15888 << resultType << Input.get()->getSourceRange(); 15889 else if (resultType->hasIntegerRepresentation()) 15890 break; 15891 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 15892 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 15893 // on vector float types. 15894 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 15895 if (!T->isIntegerType()) 15896 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15897 << resultType << Input.get()->getSourceRange()); 15898 } else { 15899 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15900 << resultType << Input.get()->getSourceRange()); 15901 } 15902 break; 15903 15904 case UO_LNot: // logical negation 15905 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 15906 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 15907 if (Input.isInvalid()) return ExprError(); 15908 resultType = Input.get()->getType(); 15909 15910 // Though we still have to promote half FP to float... 15911 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 15912 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 15913 resultType = Context.FloatTy; 15914 } 15915 15916 if (resultType->isDependentType()) 15917 break; 15918 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 15919 // C99 6.5.3.3p1: ok, fallthrough; 15920 if (Context.getLangOpts().CPlusPlus) { 15921 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 15922 // operand contextually converted to bool. 15923 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 15924 ScalarTypeToBooleanCastKind(resultType)); 15925 } else if (Context.getLangOpts().OpenCL && 15926 Context.getLangOpts().OpenCLVersion < 120) { 15927 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 15928 // operate on scalar float types. 15929 if (!resultType->isIntegerType() && !resultType->isPointerType()) 15930 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15931 << resultType << Input.get()->getSourceRange()); 15932 } 15933 } else if (resultType->isExtVectorType()) { 15934 if (Context.getLangOpts().OpenCL && 15935 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) { 15936 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 15937 // operate on vector float types. 15938 QualType T = resultType->castAs<ExtVectorType>()->getElementType(); 15939 if (!T->isIntegerType()) 15940 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15941 << resultType << Input.get()->getSourceRange()); 15942 } 15943 // Vector logical not returns the signed variant of the operand type. 15944 resultType = GetSignedVectorType(resultType); 15945 break; 15946 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) { 15947 const VectorType *VTy = resultType->castAs<VectorType>(); 15948 if (VTy->getVectorKind() != VectorType::GenericVector) 15949 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15950 << resultType << Input.get()->getSourceRange()); 15951 15952 // Vector logical not returns the signed variant of the operand type. 15953 resultType = GetSignedVectorType(resultType); 15954 break; 15955 } else { 15956 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 15957 << resultType << Input.get()->getSourceRange()); 15958 } 15959 15960 // LNot always has type int. C99 6.5.3.3p5. 15961 // In C++, it's bool. C++ 5.3.1p8 15962 resultType = Context.getLogicalOperationType(); 15963 break; 15964 case UO_Real: 15965 case UO_Imag: 15966 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 15967 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 15968 // complex l-values to ordinary l-values and all other values to r-values. 15969 if (Input.isInvalid()) return ExprError(); 15970 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 15971 if (Input.get()->isGLValue() && 15972 Input.get()->getObjectKind() == OK_Ordinary) 15973 VK = Input.get()->getValueKind(); 15974 } else if (!getLangOpts().CPlusPlus) { 15975 // In C, a volatile scalar is read by __imag. In C++, it is not. 15976 Input = DefaultLvalueConversion(Input.get()); 15977 } 15978 break; 15979 case UO_Extension: 15980 resultType = Input.get()->getType(); 15981 VK = Input.get()->getValueKind(); 15982 OK = Input.get()->getObjectKind(); 15983 break; 15984 case UO_Coawait: 15985 // It's unnecessary to represent the pass-through operator co_await in the 15986 // AST; just return the input expression instead. 15987 assert(!Input.get()->getType()->isDependentType() && 15988 "the co_await expression must be non-dependant before " 15989 "building operator co_await"); 15990 return Input; 15991 } 15992 if (resultType.isNull() || Input.isInvalid()) 15993 return ExprError(); 15994 15995 // Check for array bounds violations in the operand of the UnaryOperator, 15996 // except for the '*' and '&' operators that have to be handled specially 15997 // by CheckArrayAccess (as there are special cases like &array[arraysize] 15998 // that are explicitly defined as valid by the standard). 15999 if (Opc != UO_AddrOf && Opc != UO_Deref) 16000 CheckArrayAccess(Input.get()); 16001 16002 auto *UO = 16003 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK, 16004 OpLoc, CanOverflow, CurFPFeatureOverrides()); 16005 16006 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) && 16007 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) && 16008 !isUnevaluatedContext()) 16009 ExprEvalContexts.back().PossibleDerefs.insert(UO); 16010 16011 // Convert the result back to a half vector. 16012 if (ConvertHalfVec) 16013 return convertVector(UO, Context.HalfTy, *this); 16014 return UO; 16015 } 16016 16017 /// Determine whether the given expression is a qualified member 16018 /// access expression, of a form that could be turned into a pointer to member 16019 /// with the address-of operator. 16020 bool Sema::isQualifiedMemberAccess(Expr *E) { 16021 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 16022 if (!DRE->getQualifier()) 16023 return false; 16024 16025 ValueDecl *VD = DRE->getDecl(); 16026 if (!VD->isCXXClassMember()) 16027 return false; 16028 16029 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 16030 return true; 16031 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 16032 return Method->isInstance(); 16033 16034 return false; 16035 } 16036 16037 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 16038 if (!ULE->getQualifier()) 16039 return false; 16040 16041 for (NamedDecl *D : ULE->decls()) { 16042 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 16043 if (Method->isInstance()) 16044 return true; 16045 } else { 16046 // Overload set does not contain methods. 16047 break; 16048 } 16049 } 16050 16051 return false; 16052 } 16053 16054 return false; 16055 } 16056 16057 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 16058 UnaryOperatorKind Opc, Expr *Input, 16059 bool IsAfterAmp) { 16060 // First things first: handle placeholders so that the 16061 // overloaded-operator check considers the right type. 16062 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 16063 // Increment and decrement of pseudo-object references. 16064 if (pty->getKind() == BuiltinType::PseudoObject && 16065 UnaryOperator::isIncrementDecrementOp(Opc)) 16066 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 16067 16068 // extension is always a builtin operator. 16069 if (Opc == UO_Extension) 16070 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 16071 16072 // & gets special logic for several kinds of placeholder. 16073 // The builtin code knows what to do. 16074 if (Opc == UO_AddrOf && 16075 (pty->getKind() == BuiltinType::Overload || 16076 pty->getKind() == BuiltinType::UnknownAny || 16077 pty->getKind() == BuiltinType::BoundMember)) 16078 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 16079 16080 // Anything else needs to be handled now. 16081 ExprResult Result = CheckPlaceholderExpr(Input); 16082 if (Result.isInvalid()) return ExprError(); 16083 Input = Result.get(); 16084 } 16085 16086 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 16087 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 16088 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 16089 // Find all of the overloaded operators visible from this point. 16090 UnresolvedSet<16> Functions; 16091 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 16092 if (S && OverOp != OO_None) 16093 LookupOverloadedOperatorName(OverOp, S, Functions); 16094 16095 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 16096 } 16097 16098 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp); 16099 } 16100 16101 // Unary Operators. 'Tok' is the token for the operator. 16102 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, 16103 Expr *Input, bool IsAfterAmp) { 16104 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input, 16105 IsAfterAmp); 16106 } 16107 16108 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 16109 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 16110 LabelDecl *TheDecl) { 16111 TheDecl->markUsed(Context); 16112 // Create the AST node. The address of a label always has type 'void*'. 16113 auto *Res = new (Context) AddrLabelExpr( 16114 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy)); 16115 16116 if (getCurFunction()) 16117 getCurFunction()->AddrLabels.push_back(Res); 16118 16119 return Res; 16120 } 16121 16122 void Sema::ActOnStartStmtExpr() { 16123 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 16124 } 16125 16126 void Sema::ActOnStmtExprError() { 16127 // Note that function is also called by TreeTransform when leaving a 16128 // StmtExpr scope without rebuilding anything. 16129 16130 DiscardCleanupsInEvaluationContext(); 16131 PopExpressionEvaluationContext(); 16132 } 16133 16134 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 16135 SourceLocation RPLoc) { 16136 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S)); 16137 } 16138 16139 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 16140 SourceLocation RPLoc, unsigned TemplateDepth) { 16141 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 16142 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 16143 16144 if (hasAnyUnrecoverableErrorsInThisFunction()) 16145 DiscardCleanupsInEvaluationContext(); 16146 assert(!Cleanup.exprNeedsCleanups() && 16147 "cleanups within StmtExpr not correctly bound!"); 16148 PopExpressionEvaluationContext(); 16149 16150 // FIXME: there are a variety of strange constraints to enforce here, for 16151 // example, it is not possible to goto into a stmt expression apparently. 16152 // More semantic analysis is needed. 16153 16154 // If there are sub-stmts in the compound stmt, take the type of the last one 16155 // as the type of the stmtexpr. 16156 QualType Ty = Context.VoidTy; 16157 bool StmtExprMayBindToTemp = false; 16158 if (!Compound->body_empty()) { 16159 // For GCC compatibility we get the last Stmt excluding trailing NullStmts. 16160 if (const auto *LastStmt = 16161 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) { 16162 if (const Expr *Value = LastStmt->getExprStmt()) { 16163 StmtExprMayBindToTemp = true; 16164 Ty = Value->getType(); 16165 } 16166 } 16167 } 16168 16169 // FIXME: Check that expression type is complete/non-abstract; statement 16170 // expressions are not lvalues. 16171 Expr *ResStmtExpr = 16172 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth); 16173 if (StmtExprMayBindToTemp) 16174 return MaybeBindToTemporary(ResStmtExpr); 16175 return ResStmtExpr; 16176 } 16177 16178 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { 16179 if (ER.isInvalid()) 16180 return ExprError(); 16181 16182 // Do function/array conversion on the last expression, but not 16183 // lvalue-to-rvalue. However, initialize an unqualified type. 16184 ER = DefaultFunctionArrayConversion(ER.get()); 16185 if (ER.isInvalid()) 16186 return ExprError(); 16187 Expr *E = ER.get(); 16188 16189 if (E->isTypeDependent()) 16190 return E; 16191 16192 // In ARC, if the final expression ends in a consume, splice 16193 // the consume out and bind it later. In the alternate case 16194 // (when dealing with a retainable type), the result 16195 // initialization will create a produce. In both cases the 16196 // result will be +1, and we'll need to balance that out with 16197 // a bind. 16198 auto *Cast = dyn_cast<ImplicitCastExpr>(E); 16199 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) 16200 return Cast->getSubExpr(); 16201 16202 // FIXME: Provide a better location for the initialization. 16203 return PerformCopyInitialization( 16204 InitializedEntity::InitializeStmtExprResult( 16205 E->getBeginLoc(), E->getType().getUnqualifiedType()), 16206 SourceLocation(), E); 16207 } 16208 16209 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 16210 TypeSourceInfo *TInfo, 16211 ArrayRef<OffsetOfComponent> Components, 16212 SourceLocation RParenLoc) { 16213 QualType ArgTy = TInfo->getType(); 16214 bool Dependent = ArgTy->isDependentType(); 16215 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 16216 16217 // We must have at least one component that refers to the type, and the first 16218 // one is known to be a field designator. Verify that the ArgTy represents 16219 // a struct/union/class. 16220 if (!Dependent && !ArgTy->isRecordType()) 16221 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 16222 << ArgTy << TypeRange); 16223 16224 // Type must be complete per C99 7.17p3 because a declaring a variable 16225 // with an incomplete type would be ill-formed. 16226 if (!Dependent 16227 && RequireCompleteType(BuiltinLoc, ArgTy, 16228 diag::err_offsetof_incomplete_type, TypeRange)) 16229 return ExprError(); 16230 16231 bool DidWarnAboutNonPOD = false; 16232 QualType CurrentType = ArgTy; 16233 SmallVector<OffsetOfNode, 4> Comps; 16234 SmallVector<Expr*, 4> Exprs; 16235 for (const OffsetOfComponent &OC : Components) { 16236 if (OC.isBrackets) { 16237 // Offset of an array sub-field. TODO: Should we allow vector elements? 16238 if (!CurrentType->isDependentType()) { 16239 const ArrayType *AT = Context.getAsArrayType(CurrentType); 16240 if(!AT) 16241 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 16242 << CurrentType); 16243 CurrentType = AT->getElementType(); 16244 } else 16245 CurrentType = Context.DependentTy; 16246 16247 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 16248 if (IdxRval.isInvalid()) 16249 return ExprError(); 16250 Expr *Idx = IdxRval.get(); 16251 16252 // The expression must be an integral expression. 16253 // FIXME: An integral constant expression? 16254 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 16255 !Idx->getType()->isIntegerType()) 16256 return ExprError( 16257 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 16258 << Idx->getSourceRange()); 16259 16260 // Record this array index. 16261 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 16262 Exprs.push_back(Idx); 16263 continue; 16264 } 16265 16266 // Offset of a field. 16267 if (CurrentType->isDependentType()) { 16268 // We have the offset of a field, but we can't look into the dependent 16269 // type. Just record the identifier of the field. 16270 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 16271 CurrentType = Context.DependentTy; 16272 continue; 16273 } 16274 16275 // We need to have a complete type to look into. 16276 if (RequireCompleteType(OC.LocStart, CurrentType, 16277 diag::err_offsetof_incomplete_type)) 16278 return ExprError(); 16279 16280 // Look for the designated field. 16281 const RecordType *RC = CurrentType->getAs<RecordType>(); 16282 if (!RC) 16283 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 16284 << CurrentType); 16285 RecordDecl *RD = RC->getDecl(); 16286 16287 // C++ [lib.support.types]p5: 16288 // The macro offsetof accepts a restricted set of type arguments in this 16289 // International Standard. type shall be a POD structure or a POD union 16290 // (clause 9). 16291 // C++11 [support.types]p4: 16292 // If type is not a standard-layout class (Clause 9), the results are 16293 // undefined. 16294 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 16295 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 16296 unsigned DiagID = 16297 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 16298 : diag::ext_offsetof_non_pod_type; 16299 16300 if (!IsSafe && !DidWarnAboutNonPOD && 16301 DiagRuntimeBehavior(BuiltinLoc, nullptr, 16302 PDiag(DiagID) 16303 << SourceRange(Components[0].LocStart, OC.LocEnd) 16304 << CurrentType)) 16305 DidWarnAboutNonPOD = true; 16306 } 16307 16308 // Look for the field. 16309 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 16310 LookupQualifiedName(R, RD); 16311 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 16312 IndirectFieldDecl *IndirectMemberDecl = nullptr; 16313 if (!MemberDecl) { 16314 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 16315 MemberDecl = IndirectMemberDecl->getAnonField(); 16316 } 16317 16318 if (!MemberDecl) 16319 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 16320 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 16321 OC.LocEnd)); 16322 16323 // C99 7.17p3: 16324 // (If the specified member is a bit-field, the behavior is undefined.) 16325 // 16326 // We diagnose this as an error. 16327 if (MemberDecl->isBitField()) { 16328 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 16329 << MemberDecl->getDeclName() 16330 << SourceRange(BuiltinLoc, RParenLoc); 16331 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 16332 return ExprError(); 16333 } 16334 16335 RecordDecl *Parent = MemberDecl->getParent(); 16336 if (IndirectMemberDecl) 16337 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 16338 16339 // If the member was found in a base class, introduce OffsetOfNodes for 16340 // the base class indirections. 16341 CXXBasePaths Paths; 16342 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 16343 Paths)) { 16344 if (Paths.getDetectedVirtual()) { 16345 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 16346 << MemberDecl->getDeclName() 16347 << SourceRange(BuiltinLoc, RParenLoc); 16348 return ExprError(); 16349 } 16350 16351 CXXBasePath &Path = Paths.front(); 16352 for (const CXXBasePathElement &B : Path) 16353 Comps.push_back(OffsetOfNode(B.Base)); 16354 } 16355 16356 if (IndirectMemberDecl) { 16357 for (auto *FI : IndirectMemberDecl->chain()) { 16358 assert(isa<FieldDecl>(FI)); 16359 Comps.push_back(OffsetOfNode(OC.LocStart, 16360 cast<FieldDecl>(FI), OC.LocEnd)); 16361 } 16362 } else 16363 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 16364 16365 CurrentType = MemberDecl->getType().getNonReferenceType(); 16366 } 16367 16368 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 16369 Comps, Exprs, RParenLoc); 16370 } 16371 16372 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 16373 SourceLocation BuiltinLoc, 16374 SourceLocation TypeLoc, 16375 ParsedType ParsedArgTy, 16376 ArrayRef<OffsetOfComponent> Components, 16377 SourceLocation RParenLoc) { 16378 16379 TypeSourceInfo *ArgTInfo; 16380 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 16381 if (ArgTy.isNull()) 16382 return ExprError(); 16383 16384 if (!ArgTInfo) 16385 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 16386 16387 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 16388 } 16389 16390 16391 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 16392 Expr *CondExpr, 16393 Expr *LHSExpr, Expr *RHSExpr, 16394 SourceLocation RPLoc) { 16395 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 16396 16397 ExprValueKind VK = VK_PRValue; 16398 ExprObjectKind OK = OK_Ordinary; 16399 QualType resType; 16400 bool CondIsTrue = false; 16401 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 16402 resType = Context.DependentTy; 16403 } else { 16404 // The conditional expression is required to be a constant expression. 16405 llvm::APSInt condEval(32); 16406 ExprResult CondICE = VerifyIntegerConstantExpression( 16407 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant); 16408 if (CondICE.isInvalid()) 16409 return ExprError(); 16410 CondExpr = CondICE.get(); 16411 CondIsTrue = condEval.getZExtValue(); 16412 16413 // If the condition is > zero, then the AST type is the same as the LHSExpr. 16414 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 16415 16416 resType = ActiveExpr->getType(); 16417 VK = ActiveExpr->getValueKind(); 16418 OK = ActiveExpr->getObjectKind(); 16419 } 16420 16421 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, 16422 resType, VK, OK, RPLoc, CondIsTrue); 16423 } 16424 16425 //===----------------------------------------------------------------------===// 16426 // Clang Extensions. 16427 //===----------------------------------------------------------------------===// 16428 16429 /// ActOnBlockStart - This callback is invoked when a block literal is started. 16430 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 16431 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 16432 16433 if (LangOpts.CPlusPlus) { 16434 MangleNumberingContext *MCtx; 16435 Decl *ManglingContextDecl; 16436 std::tie(MCtx, ManglingContextDecl) = 16437 getCurrentMangleNumberContext(Block->getDeclContext()); 16438 if (MCtx) { 16439 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 16440 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 16441 } 16442 } 16443 16444 PushBlockScope(CurScope, Block); 16445 CurContext->addDecl(Block); 16446 if (CurScope) 16447 PushDeclContext(CurScope, Block); 16448 else 16449 CurContext = Block; 16450 16451 getCurBlock()->HasImplicitReturnType = true; 16452 16453 // Enter a new evaluation context to insulate the block from any 16454 // cleanups from the enclosing full-expression. 16455 PushExpressionEvaluationContext( 16456 ExpressionEvaluationContext::PotentiallyEvaluated); 16457 } 16458 16459 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 16460 Scope *CurScope) { 16461 assert(ParamInfo.getIdentifier() == nullptr && 16462 "block-id should have no identifier!"); 16463 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral); 16464 BlockScopeInfo *CurBlock = getCurBlock(); 16465 16466 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 16467 QualType T = Sig->getType(); 16468 16469 // FIXME: We should allow unexpanded parameter packs here, but that would, 16470 // in turn, make the block expression contain unexpanded parameter packs. 16471 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 16472 // Drop the parameters. 16473 FunctionProtoType::ExtProtoInfo EPI; 16474 EPI.HasTrailingReturn = false; 16475 EPI.TypeQuals.addConst(); 16476 T = Context.getFunctionType(Context.DependentTy, std::nullopt, EPI); 16477 Sig = Context.getTrivialTypeSourceInfo(T); 16478 } 16479 16480 // GetTypeForDeclarator always produces a function type for a block 16481 // literal signature. Furthermore, it is always a FunctionProtoType 16482 // unless the function was written with a typedef. 16483 assert(T->isFunctionType() && 16484 "GetTypeForDeclarator made a non-function block signature"); 16485 16486 // Look for an explicit signature in that function type. 16487 FunctionProtoTypeLoc ExplicitSignature; 16488 16489 if ((ExplicitSignature = Sig->getTypeLoc() 16490 .getAsAdjusted<FunctionProtoTypeLoc>())) { 16491 16492 // Check whether that explicit signature was synthesized by 16493 // GetTypeForDeclarator. If so, don't save that as part of the 16494 // written signature. 16495 if (ExplicitSignature.getLocalRangeBegin() == 16496 ExplicitSignature.getLocalRangeEnd()) { 16497 // This would be much cheaper if we stored TypeLocs instead of 16498 // TypeSourceInfos. 16499 TypeLoc Result = ExplicitSignature.getReturnLoc(); 16500 unsigned Size = Result.getFullDataSize(); 16501 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 16502 Sig->getTypeLoc().initializeFullCopy(Result, Size); 16503 16504 ExplicitSignature = FunctionProtoTypeLoc(); 16505 } 16506 } 16507 16508 CurBlock->TheDecl->setSignatureAsWritten(Sig); 16509 CurBlock->FunctionType = T; 16510 16511 const auto *Fn = T->castAs<FunctionType>(); 16512 QualType RetTy = Fn->getReturnType(); 16513 bool isVariadic = 16514 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 16515 16516 CurBlock->TheDecl->setIsVariadic(isVariadic); 16517 16518 // Context.DependentTy is used as a placeholder for a missing block 16519 // return type. TODO: what should we do with declarators like: 16520 // ^ * { ... } 16521 // If the answer is "apply template argument deduction".... 16522 if (RetTy != Context.DependentTy) { 16523 CurBlock->ReturnType = RetTy; 16524 CurBlock->TheDecl->setBlockMissingReturnType(false); 16525 CurBlock->HasImplicitReturnType = false; 16526 } 16527 16528 // Push block parameters from the declarator if we had them. 16529 SmallVector<ParmVarDecl*, 8> Params; 16530 if (ExplicitSignature) { 16531 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 16532 ParmVarDecl *Param = ExplicitSignature.getParam(I); 16533 if (Param->getIdentifier() == nullptr && !Param->isImplicit() && 16534 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) { 16535 // Diagnose this as an extension in C17 and earlier. 16536 if (!getLangOpts().C2x) 16537 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 16538 } 16539 Params.push_back(Param); 16540 } 16541 16542 // Fake up parameter variables if we have a typedef, like 16543 // ^ fntype { ... } 16544 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 16545 for (const auto &I : Fn->param_types()) { 16546 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 16547 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 16548 Params.push_back(Param); 16549 } 16550 } 16551 16552 // Set the parameters on the block decl. 16553 if (!Params.empty()) { 16554 CurBlock->TheDecl->setParams(Params); 16555 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 16556 /*CheckParameterNames=*/false); 16557 } 16558 16559 // Finally we can process decl attributes. 16560 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 16561 16562 // Put the parameter variables in scope. 16563 for (auto *AI : CurBlock->TheDecl->parameters()) { 16564 AI->setOwningFunction(CurBlock->TheDecl); 16565 16566 // If this has an identifier, add it to the scope stack. 16567 if (AI->getIdentifier()) { 16568 CheckShadow(CurBlock->TheScope, AI); 16569 16570 PushOnScopeChains(AI, CurBlock->TheScope); 16571 } 16572 } 16573 } 16574 16575 /// ActOnBlockError - If there is an error parsing a block, this callback 16576 /// is invoked to pop the information about the block from the action impl. 16577 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 16578 // Leave the expression-evaluation context. 16579 DiscardCleanupsInEvaluationContext(); 16580 PopExpressionEvaluationContext(); 16581 16582 // Pop off CurBlock, handle nested blocks. 16583 PopDeclContext(); 16584 PopFunctionScopeInfo(); 16585 } 16586 16587 /// ActOnBlockStmtExpr - This is called when the body of a block statement 16588 /// literal was successfully completed. ^(int x){...} 16589 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 16590 Stmt *Body, Scope *CurScope) { 16591 // If blocks are disabled, emit an error. 16592 if (!LangOpts.Blocks) 16593 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 16594 16595 // Leave the expression-evaluation context. 16596 if (hasAnyUnrecoverableErrorsInThisFunction()) 16597 DiscardCleanupsInEvaluationContext(); 16598 assert(!Cleanup.exprNeedsCleanups() && 16599 "cleanups within block not correctly bound!"); 16600 PopExpressionEvaluationContext(); 16601 16602 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 16603 BlockDecl *BD = BSI->TheDecl; 16604 16605 if (BSI->HasImplicitReturnType) 16606 deduceClosureReturnType(*BSI); 16607 16608 QualType RetTy = Context.VoidTy; 16609 if (!BSI->ReturnType.isNull()) 16610 RetTy = BSI->ReturnType; 16611 16612 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 16613 QualType BlockTy; 16614 16615 // If the user wrote a function type in some form, try to use that. 16616 if (!BSI->FunctionType.isNull()) { 16617 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>(); 16618 16619 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 16620 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 16621 16622 // Turn protoless block types into nullary block types. 16623 if (isa<FunctionNoProtoType>(FTy)) { 16624 FunctionProtoType::ExtProtoInfo EPI; 16625 EPI.ExtInfo = Ext; 16626 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI); 16627 16628 // Otherwise, if we don't need to change anything about the function type, 16629 // preserve its sugar structure. 16630 } else if (FTy->getReturnType() == RetTy && 16631 (!NoReturn || FTy->getNoReturnAttr())) { 16632 BlockTy = BSI->FunctionType; 16633 16634 // Otherwise, make the minimal modifications to the function type. 16635 } else { 16636 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 16637 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 16638 EPI.TypeQuals = Qualifiers(); 16639 EPI.ExtInfo = Ext; 16640 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 16641 } 16642 16643 // If we don't have a function type, just build one from nothing. 16644 } else { 16645 FunctionProtoType::ExtProtoInfo EPI; 16646 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 16647 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI); 16648 } 16649 16650 DiagnoseUnusedParameters(BD->parameters()); 16651 BlockTy = Context.getBlockPointerType(BlockTy); 16652 16653 // If needed, diagnose invalid gotos and switches in the block. 16654 if (getCurFunction()->NeedsScopeChecking() && 16655 !PP.isCodeCompletionEnabled()) 16656 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 16657 16658 BD->setBody(cast<CompoundStmt>(Body)); 16659 16660 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 16661 DiagnoseUnguardedAvailabilityViolations(BD); 16662 16663 // Try to apply the named return value optimization. We have to check again 16664 // if we can do this, though, because blocks keep return statements around 16665 // to deduce an implicit return type. 16666 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 16667 !BD->isDependentContext()) 16668 computeNRVO(Body, BSI); 16669 16670 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() || 16671 RetTy.hasNonTrivialToPrimitiveCopyCUnion()) 16672 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn, 16673 NTCUK_Destruct|NTCUK_Copy); 16674 16675 PopDeclContext(); 16676 16677 // Set the captured variables on the block. 16678 SmallVector<BlockDecl::Capture, 4> Captures; 16679 for (Capture &Cap : BSI->Captures) { 16680 if (Cap.isInvalid() || Cap.isThisCapture()) 16681 continue; 16682 // Cap.getVariable() is always a VarDecl because 16683 // blocks cannot capture structured bindings or other ValueDecl kinds. 16684 auto *Var = cast<VarDecl>(Cap.getVariable()); 16685 Expr *CopyExpr = nullptr; 16686 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) { 16687 if (const RecordType *Record = 16688 Cap.getCaptureType()->getAs<RecordType>()) { 16689 // The capture logic needs the destructor, so make sure we mark it. 16690 // Usually this is unnecessary because most local variables have 16691 // their destructors marked at declaration time, but parameters are 16692 // an exception because it's technically only the call site that 16693 // actually requires the destructor. 16694 if (isa<ParmVarDecl>(Var)) 16695 FinalizeVarWithDestructor(Var, Record); 16696 16697 // Enter a separate potentially-evaluated context while building block 16698 // initializers to isolate their cleanups from those of the block 16699 // itself. 16700 // FIXME: Is this appropriate even when the block itself occurs in an 16701 // unevaluated operand? 16702 EnterExpressionEvaluationContext EvalContext( 16703 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 16704 16705 SourceLocation Loc = Cap.getLocation(); 16706 16707 ExprResult Result = BuildDeclarationNameExpr( 16708 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); 16709 16710 // According to the blocks spec, the capture of a variable from 16711 // the stack requires a const copy constructor. This is not true 16712 // of the copy/move done to move a __block variable to the heap. 16713 if (!Result.isInvalid() && 16714 !Result.get()->getType().isConstQualified()) { 16715 Result = ImpCastExprToType(Result.get(), 16716 Result.get()->getType().withConst(), 16717 CK_NoOp, VK_LValue); 16718 } 16719 16720 if (!Result.isInvalid()) { 16721 Result = PerformCopyInitialization( 16722 InitializedEntity::InitializeBlock(Var->getLocation(), 16723 Cap.getCaptureType()), 16724 Loc, Result.get()); 16725 } 16726 16727 // Build a full-expression copy expression if initialization 16728 // succeeded and used a non-trivial constructor. Recover from 16729 // errors by pretending that the copy isn't necessary. 16730 if (!Result.isInvalid() && 16731 !cast<CXXConstructExpr>(Result.get())->getConstructor() 16732 ->isTrivial()) { 16733 Result = MaybeCreateExprWithCleanups(Result); 16734 CopyExpr = Result.get(); 16735 } 16736 } 16737 } 16738 16739 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(), 16740 CopyExpr); 16741 Captures.push_back(NewCap); 16742 } 16743 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 16744 16745 // Pop the block scope now but keep it alive to the end of this function. 16746 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 16747 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy); 16748 16749 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 16750 16751 // If the block isn't obviously global, i.e. it captures anything at 16752 // all, then we need to do a few things in the surrounding context: 16753 if (Result->getBlockDecl()->hasCaptures()) { 16754 // First, this expression has a new cleanup object. 16755 ExprCleanupObjects.push_back(Result->getBlockDecl()); 16756 Cleanup.setExprNeedsCleanups(true); 16757 16758 // It also gets a branch-protected scope if any of the captured 16759 // variables needs destruction. 16760 for (const auto &CI : Result->getBlockDecl()->captures()) { 16761 const VarDecl *var = CI.getVariable(); 16762 if (var->getType().isDestructedType() != QualType::DK_none) { 16763 setFunctionHasBranchProtectedScope(); 16764 break; 16765 } 16766 } 16767 } 16768 16769 if (getCurFunction()) 16770 getCurFunction()->addBlock(BD); 16771 16772 return Result; 16773 } 16774 16775 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 16776 SourceLocation RPLoc) { 16777 TypeSourceInfo *TInfo; 16778 GetTypeFromParser(Ty, &TInfo); 16779 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 16780 } 16781 16782 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 16783 Expr *E, TypeSourceInfo *TInfo, 16784 SourceLocation RPLoc) { 16785 Expr *OrigExpr = E; 16786 bool IsMS = false; 16787 16788 // CUDA device code does not support varargs. 16789 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 16790 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 16791 CUDAFunctionTarget T = IdentifyCUDATarget(F); 16792 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 16793 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 16794 } 16795 } 16796 16797 // NVPTX does not support va_arg expression. 16798 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 16799 Context.getTargetInfo().getTriple().isNVPTX()) 16800 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device); 16801 16802 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 16803 // as Microsoft ABI on an actual Microsoft platform, where 16804 // __builtin_ms_va_list and __builtin_va_list are the same.) 16805 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 16806 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 16807 QualType MSVaListType = Context.getBuiltinMSVaListType(); 16808 if (Context.hasSameType(MSVaListType, E->getType())) { 16809 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 16810 return ExprError(); 16811 IsMS = true; 16812 } 16813 } 16814 16815 // Get the va_list type 16816 QualType VaListType = Context.getBuiltinVaListType(); 16817 if (!IsMS) { 16818 if (VaListType->isArrayType()) { 16819 // Deal with implicit array decay; for example, on x86-64, 16820 // va_list is an array, but it's supposed to decay to 16821 // a pointer for va_arg. 16822 VaListType = Context.getArrayDecayedType(VaListType); 16823 // Make sure the input expression also decays appropriately. 16824 ExprResult Result = UsualUnaryConversions(E); 16825 if (Result.isInvalid()) 16826 return ExprError(); 16827 E = Result.get(); 16828 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 16829 // If va_list is a record type and we are compiling in C++ mode, 16830 // check the argument using reference binding. 16831 InitializedEntity Entity = InitializedEntity::InitializeParameter( 16832 Context, Context.getLValueReferenceType(VaListType), false); 16833 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 16834 if (Init.isInvalid()) 16835 return ExprError(); 16836 E = Init.getAs<Expr>(); 16837 } else { 16838 // Otherwise, the va_list argument must be an l-value because 16839 // it is modified by va_arg. 16840 if (!E->isTypeDependent() && 16841 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 16842 return ExprError(); 16843 } 16844 } 16845 16846 if (!IsMS && !E->isTypeDependent() && 16847 !Context.hasSameType(VaListType, E->getType())) 16848 return ExprError( 16849 Diag(E->getBeginLoc(), 16850 diag::err_first_argument_to_va_arg_not_of_type_va_list) 16851 << OrigExpr->getType() << E->getSourceRange()); 16852 16853 if (!TInfo->getType()->isDependentType()) { 16854 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 16855 diag::err_second_parameter_to_va_arg_incomplete, 16856 TInfo->getTypeLoc())) 16857 return ExprError(); 16858 16859 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 16860 TInfo->getType(), 16861 diag::err_second_parameter_to_va_arg_abstract, 16862 TInfo->getTypeLoc())) 16863 return ExprError(); 16864 16865 if (!TInfo->getType().isPODType(Context)) { 16866 Diag(TInfo->getTypeLoc().getBeginLoc(), 16867 TInfo->getType()->isObjCLifetimeType() 16868 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 16869 : diag::warn_second_parameter_to_va_arg_not_pod) 16870 << TInfo->getType() 16871 << TInfo->getTypeLoc().getSourceRange(); 16872 } 16873 16874 // Check for va_arg where arguments of the given type will be promoted 16875 // (i.e. this va_arg is guaranteed to have undefined behavior). 16876 QualType PromoteType; 16877 if (Context.isPromotableIntegerType(TInfo->getType())) { 16878 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 16879 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says, 16880 // and C2x 7.16.1.1p2 says, in part: 16881 // If type is not compatible with the type of the actual next argument 16882 // (as promoted according to the default argument promotions), the 16883 // behavior is undefined, except for the following cases: 16884 // - both types are pointers to qualified or unqualified versions of 16885 // compatible types; 16886 // - one type is a signed integer type, the other type is the 16887 // corresponding unsigned integer type, and the value is 16888 // representable in both types; 16889 // - one type is pointer to qualified or unqualified void and the 16890 // other is a pointer to a qualified or unqualified character type. 16891 // Given that type compatibility is the primary requirement (ignoring 16892 // qualifications), you would think we could call typesAreCompatible() 16893 // directly to test this. However, in C++, that checks for *same type*, 16894 // which causes false positives when passing an enumeration type to 16895 // va_arg. Instead, get the underlying type of the enumeration and pass 16896 // that. 16897 QualType UnderlyingType = TInfo->getType(); 16898 if (const auto *ET = UnderlyingType->getAs<EnumType>()) 16899 UnderlyingType = ET->getDecl()->getIntegerType(); 16900 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 16901 /*CompareUnqualified*/ true)) 16902 PromoteType = QualType(); 16903 16904 // If the types are still not compatible, we need to test whether the 16905 // promoted type and the underlying type are the same except for 16906 // signedness. Ask the AST for the correctly corresponding type and see 16907 // if that's compatible. 16908 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() && 16909 PromoteType->isUnsignedIntegerType() != 16910 UnderlyingType->isUnsignedIntegerType()) { 16911 UnderlyingType = 16912 UnderlyingType->isUnsignedIntegerType() 16913 ? Context.getCorrespondingSignedType(UnderlyingType) 16914 : Context.getCorrespondingUnsignedType(UnderlyingType); 16915 if (Context.typesAreCompatible(PromoteType, UnderlyingType, 16916 /*CompareUnqualified*/ true)) 16917 PromoteType = QualType(); 16918 } 16919 } 16920 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 16921 PromoteType = Context.DoubleTy; 16922 if (!PromoteType.isNull()) 16923 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 16924 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 16925 << TInfo->getType() 16926 << PromoteType 16927 << TInfo->getTypeLoc().getSourceRange()); 16928 } 16929 16930 QualType T = TInfo->getType().getNonLValueExprType(Context); 16931 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 16932 } 16933 16934 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 16935 // The type of __null will be int or long, depending on the size of 16936 // pointers on the target. 16937 QualType Ty; 16938 unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default); 16939 if (pw == Context.getTargetInfo().getIntWidth()) 16940 Ty = Context.IntTy; 16941 else if (pw == Context.getTargetInfo().getLongWidth()) 16942 Ty = Context.LongTy; 16943 else if (pw == Context.getTargetInfo().getLongLongWidth()) 16944 Ty = Context.LongLongTy; 16945 else { 16946 llvm_unreachable("I don't know size of pointer!"); 16947 } 16948 16949 return new (Context) GNUNullExpr(Ty, TokenLoc); 16950 } 16951 16952 static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) { 16953 CXXRecordDecl *ImplDecl = nullptr; 16954 16955 // Fetch the std::source_location::__impl decl. 16956 if (NamespaceDecl *Std = S.getStdNamespace()) { 16957 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"), 16958 Loc, Sema::LookupOrdinaryName); 16959 if (S.LookupQualifiedName(ResultSL, Std)) { 16960 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) { 16961 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"), 16962 Loc, Sema::LookupOrdinaryName); 16963 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) && 16964 S.LookupQualifiedName(ResultImpl, SLDecl)) { 16965 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>(); 16966 } 16967 } 16968 } 16969 } 16970 16971 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) { 16972 S.Diag(Loc, diag::err_std_source_location_impl_not_found); 16973 return nullptr; 16974 } 16975 16976 // Verify that __impl is a trivial struct type, with no base classes, and with 16977 // only the four expected fields. 16978 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() || 16979 ImplDecl->getNumBases() != 0) { 16980 S.Diag(Loc, diag::err_std_source_location_impl_malformed); 16981 return nullptr; 16982 } 16983 16984 unsigned Count = 0; 16985 for (FieldDecl *F : ImplDecl->fields()) { 16986 StringRef Name = F->getName(); 16987 16988 if (Name == "_M_file_name") { 16989 if (F->getType() != 16990 S.Context.getPointerType(S.Context.CharTy.withConst())) 16991 break; 16992 Count++; 16993 } else if (Name == "_M_function_name") { 16994 if (F->getType() != 16995 S.Context.getPointerType(S.Context.CharTy.withConst())) 16996 break; 16997 Count++; 16998 } else if (Name == "_M_line") { 16999 if (!F->getType()->isIntegerType()) 17000 break; 17001 Count++; 17002 } else if (Name == "_M_column") { 17003 if (!F->getType()->isIntegerType()) 17004 break; 17005 Count++; 17006 } else { 17007 Count = 100; // invalid 17008 break; 17009 } 17010 } 17011 if (Count != 4) { 17012 S.Diag(Loc, diag::err_std_source_location_impl_malformed); 17013 return nullptr; 17014 } 17015 17016 return ImplDecl; 17017 } 17018 17019 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 17020 SourceLocation BuiltinLoc, 17021 SourceLocation RPLoc) { 17022 QualType ResultTy; 17023 switch (Kind) { 17024 case SourceLocExpr::File: 17025 case SourceLocExpr::Function: { 17026 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0); 17027 ResultTy = 17028 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType()); 17029 break; 17030 } 17031 case SourceLocExpr::Line: 17032 case SourceLocExpr::Column: 17033 ResultTy = Context.UnsignedIntTy; 17034 break; 17035 case SourceLocExpr::SourceLocStruct: 17036 if (!StdSourceLocationImplDecl) { 17037 StdSourceLocationImplDecl = 17038 LookupStdSourceLocationImpl(*this, BuiltinLoc); 17039 if (!StdSourceLocationImplDecl) 17040 return ExprError(); 17041 } 17042 ResultTy = Context.getPointerType( 17043 Context.getRecordType(StdSourceLocationImplDecl).withConst()); 17044 break; 17045 } 17046 17047 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext); 17048 } 17049 17050 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 17051 QualType ResultTy, 17052 SourceLocation BuiltinLoc, 17053 SourceLocation RPLoc, 17054 DeclContext *ParentContext) { 17055 return new (Context) 17056 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext); 17057 } 17058 17059 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp, 17060 bool Diagnose) { 17061 if (!getLangOpts().ObjC) 17062 return false; 17063 17064 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 17065 if (!PT) 17066 return false; 17067 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 17068 17069 // Ignore any parens, implicit casts (should only be 17070 // array-to-pointer decays), and not-so-opaque values. The last is 17071 // important for making this trigger for property assignments. 17072 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 17073 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 17074 if (OV->getSourceExpr()) 17075 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 17076 17077 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) { 17078 if (!PT->isObjCIdType() && 17079 !(ID && ID->getIdentifier()->isStr("NSString"))) 17080 return false; 17081 if (!SL->isOrdinary()) 17082 return false; 17083 17084 if (Diagnose) { 17085 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 17086 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 17087 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 17088 } 17089 return true; 17090 } 17091 17092 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) || 17093 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) || 17094 isa<CXXBoolLiteralExpr>(SrcExpr)) && 17095 !SrcExpr->isNullPointerConstant( 17096 getASTContext(), Expr::NPC_NeverValueDependent)) { 17097 if (!ID || !ID->getIdentifier()->isStr("NSNumber")) 17098 return false; 17099 if (Diagnose) { 17100 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix) 17101 << /*number*/1 17102 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@"); 17103 Expr *NumLit = 17104 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get(); 17105 if (NumLit) 17106 Exp = NumLit; 17107 } 17108 return true; 17109 } 17110 17111 return false; 17112 } 17113 17114 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 17115 const Expr *SrcExpr) { 17116 if (!DstType->isFunctionPointerType() || 17117 !SrcExpr->getType()->isFunctionType()) 17118 return false; 17119 17120 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 17121 if (!DRE) 17122 return false; 17123 17124 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 17125 if (!FD) 17126 return false; 17127 17128 return !S.checkAddressOfFunctionIsAvailable(FD, 17129 /*Complain=*/true, 17130 SrcExpr->getBeginLoc()); 17131 } 17132 17133 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 17134 SourceLocation Loc, 17135 QualType DstType, QualType SrcType, 17136 Expr *SrcExpr, AssignmentAction Action, 17137 bool *Complained) { 17138 if (Complained) 17139 *Complained = false; 17140 17141 // Decode the result (notice that AST's are still created for extensions). 17142 bool CheckInferredResultType = false; 17143 bool isInvalid = false; 17144 unsigned DiagKind = 0; 17145 ConversionFixItGenerator ConvHints; 17146 bool MayHaveConvFixit = false; 17147 bool MayHaveFunctionDiff = false; 17148 const ObjCInterfaceDecl *IFace = nullptr; 17149 const ObjCProtocolDecl *PDecl = nullptr; 17150 17151 switch (ConvTy) { 17152 case Compatible: 17153 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 17154 return false; 17155 17156 case PointerToInt: 17157 if (getLangOpts().CPlusPlus) { 17158 DiagKind = diag::err_typecheck_convert_pointer_int; 17159 isInvalid = true; 17160 } else { 17161 DiagKind = diag::ext_typecheck_convert_pointer_int; 17162 } 17163 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 17164 MayHaveConvFixit = true; 17165 break; 17166 case IntToPointer: 17167 if (getLangOpts().CPlusPlus) { 17168 DiagKind = diag::err_typecheck_convert_int_pointer; 17169 isInvalid = true; 17170 } else { 17171 DiagKind = diag::ext_typecheck_convert_int_pointer; 17172 } 17173 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 17174 MayHaveConvFixit = true; 17175 break; 17176 case IncompatibleFunctionPointerStrict: 17177 DiagKind = 17178 diag::warn_typecheck_convert_incompatible_function_pointer_strict; 17179 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 17180 MayHaveConvFixit = true; 17181 break; 17182 case IncompatibleFunctionPointer: 17183 if (getLangOpts().CPlusPlus) { 17184 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer; 17185 isInvalid = true; 17186 } else { 17187 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 17188 } 17189 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 17190 MayHaveConvFixit = true; 17191 break; 17192 case IncompatiblePointer: 17193 if (Action == AA_Passing_CFAudited) { 17194 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 17195 } else if (getLangOpts().CPlusPlus) { 17196 DiagKind = diag::err_typecheck_convert_incompatible_pointer; 17197 isInvalid = true; 17198 } else { 17199 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 17200 } 17201 CheckInferredResultType = DstType->isObjCObjectPointerType() && 17202 SrcType->isObjCObjectPointerType(); 17203 if (!CheckInferredResultType) { 17204 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 17205 } else if (CheckInferredResultType) { 17206 SrcType = SrcType.getUnqualifiedType(); 17207 DstType = DstType.getUnqualifiedType(); 17208 } 17209 MayHaveConvFixit = true; 17210 break; 17211 case IncompatiblePointerSign: 17212 if (getLangOpts().CPlusPlus) { 17213 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign; 17214 isInvalid = true; 17215 } else { 17216 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 17217 } 17218 break; 17219 case FunctionVoidPointer: 17220 if (getLangOpts().CPlusPlus) { 17221 DiagKind = diag::err_typecheck_convert_pointer_void_func; 17222 isInvalid = true; 17223 } else { 17224 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 17225 } 17226 break; 17227 case IncompatiblePointerDiscardsQualifiers: { 17228 // Perform array-to-pointer decay if necessary. 17229 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 17230 17231 isInvalid = true; 17232 17233 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 17234 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 17235 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 17236 DiagKind = diag::err_typecheck_incompatible_address_space; 17237 break; 17238 17239 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 17240 DiagKind = diag::err_typecheck_incompatible_ownership; 17241 break; 17242 } 17243 17244 llvm_unreachable("unknown error case for discarding qualifiers!"); 17245 // fallthrough 17246 } 17247 case CompatiblePointerDiscardsQualifiers: 17248 // If the qualifiers lost were because we were applying the 17249 // (deprecated) C++ conversion from a string literal to a char* 17250 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 17251 // Ideally, this check would be performed in 17252 // checkPointerTypesForAssignment. However, that would require a 17253 // bit of refactoring (so that the second argument is an 17254 // expression, rather than a type), which should be done as part 17255 // of a larger effort to fix checkPointerTypesForAssignment for 17256 // C++ semantics. 17257 if (getLangOpts().CPlusPlus && 17258 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 17259 return false; 17260 if (getLangOpts().CPlusPlus) { 17261 DiagKind = diag::err_typecheck_convert_discards_qualifiers; 17262 isInvalid = true; 17263 } else { 17264 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 17265 } 17266 17267 break; 17268 case IncompatibleNestedPointerQualifiers: 17269 if (getLangOpts().CPlusPlus) { 17270 isInvalid = true; 17271 DiagKind = diag::err_nested_pointer_qualifier_mismatch; 17272 } else { 17273 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 17274 } 17275 break; 17276 case IncompatibleNestedPointerAddressSpaceMismatch: 17277 DiagKind = diag::err_typecheck_incompatible_nested_address_space; 17278 isInvalid = true; 17279 break; 17280 case IntToBlockPointer: 17281 DiagKind = diag::err_int_to_block_pointer; 17282 isInvalid = true; 17283 break; 17284 case IncompatibleBlockPointer: 17285 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 17286 isInvalid = true; 17287 break; 17288 case IncompatibleObjCQualifiedId: { 17289 if (SrcType->isObjCQualifiedIdType()) { 17290 const ObjCObjectPointerType *srcOPT = 17291 SrcType->castAs<ObjCObjectPointerType>(); 17292 for (auto *srcProto : srcOPT->quals()) { 17293 PDecl = srcProto; 17294 break; 17295 } 17296 if (const ObjCInterfaceType *IFaceT = 17297 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 17298 IFace = IFaceT->getDecl(); 17299 } 17300 else if (DstType->isObjCQualifiedIdType()) { 17301 const ObjCObjectPointerType *dstOPT = 17302 DstType->castAs<ObjCObjectPointerType>(); 17303 for (auto *dstProto : dstOPT->quals()) { 17304 PDecl = dstProto; 17305 break; 17306 } 17307 if (const ObjCInterfaceType *IFaceT = 17308 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType()) 17309 IFace = IFaceT->getDecl(); 17310 } 17311 if (getLangOpts().CPlusPlus) { 17312 DiagKind = diag::err_incompatible_qualified_id; 17313 isInvalid = true; 17314 } else { 17315 DiagKind = diag::warn_incompatible_qualified_id; 17316 } 17317 break; 17318 } 17319 case IncompatibleVectors: 17320 if (getLangOpts().CPlusPlus) { 17321 DiagKind = diag::err_incompatible_vectors; 17322 isInvalid = true; 17323 } else { 17324 DiagKind = diag::warn_incompatible_vectors; 17325 } 17326 break; 17327 case IncompatibleObjCWeakRef: 17328 DiagKind = diag::err_arc_weak_unavailable_assign; 17329 isInvalid = true; 17330 break; 17331 case Incompatible: 17332 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 17333 if (Complained) 17334 *Complained = true; 17335 return true; 17336 } 17337 17338 DiagKind = diag::err_typecheck_convert_incompatible; 17339 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 17340 MayHaveConvFixit = true; 17341 isInvalid = true; 17342 MayHaveFunctionDiff = true; 17343 break; 17344 } 17345 17346 QualType FirstType, SecondType; 17347 switch (Action) { 17348 case AA_Assigning: 17349 case AA_Initializing: 17350 // The destination type comes first. 17351 FirstType = DstType; 17352 SecondType = SrcType; 17353 break; 17354 17355 case AA_Returning: 17356 case AA_Passing: 17357 case AA_Passing_CFAudited: 17358 case AA_Converting: 17359 case AA_Sending: 17360 case AA_Casting: 17361 // The source type comes first. 17362 FirstType = SrcType; 17363 SecondType = DstType; 17364 break; 17365 } 17366 17367 PartialDiagnostic FDiag = PDiag(DiagKind); 17368 AssignmentAction ActionForDiag = Action; 17369 if (Action == AA_Passing_CFAudited) 17370 ActionForDiag = AA_Passing; 17371 17372 FDiag << FirstType << SecondType << ActionForDiag 17373 << SrcExpr->getSourceRange(); 17374 17375 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign || 17376 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) { 17377 auto isPlainChar = [](const clang::Type *Type) { 17378 return Type->isSpecificBuiltinType(BuiltinType::Char_S) || 17379 Type->isSpecificBuiltinType(BuiltinType::Char_U); 17380 }; 17381 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) || 17382 isPlainChar(SecondType->getPointeeOrArrayElementType())); 17383 } 17384 17385 // If we can fix the conversion, suggest the FixIts. 17386 if (!ConvHints.isNull()) { 17387 for (FixItHint &H : ConvHints.Hints) 17388 FDiag << H; 17389 } 17390 17391 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 17392 17393 if (MayHaveFunctionDiff) 17394 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 17395 17396 Diag(Loc, FDiag); 17397 if ((DiagKind == diag::warn_incompatible_qualified_id || 17398 DiagKind == diag::err_incompatible_qualified_id) && 17399 PDecl && IFace && !IFace->hasDefinition()) 17400 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 17401 << IFace << PDecl; 17402 17403 if (SecondType == Context.OverloadTy) 17404 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 17405 FirstType, /*TakingAddress=*/true); 17406 17407 if (CheckInferredResultType) 17408 EmitRelatedResultTypeNote(SrcExpr); 17409 17410 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 17411 EmitRelatedResultTypeNoteForReturn(DstType); 17412 17413 if (Complained) 17414 *Complained = true; 17415 return isInvalid; 17416 } 17417 17418 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 17419 llvm::APSInt *Result, 17420 AllowFoldKind CanFold) { 17421 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 17422 public: 17423 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, 17424 QualType T) override { 17425 return S.Diag(Loc, diag::err_ice_not_integral) 17426 << T << S.LangOpts.CPlusPlus; 17427 } 17428 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 17429 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus; 17430 } 17431 } Diagnoser; 17432 17433 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 17434 } 17435 17436 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 17437 llvm::APSInt *Result, 17438 unsigned DiagID, 17439 AllowFoldKind CanFold) { 17440 class IDDiagnoser : public VerifyICEDiagnoser { 17441 unsigned DiagID; 17442 17443 public: 17444 IDDiagnoser(unsigned DiagID) 17445 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 17446 17447 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override { 17448 return S.Diag(Loc, DiagID); 17449 } 17450 } Diagnoser(DiagID); 17451 17452 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold); 17453 } 17454 17455 Sema::SemaDiagnosticBuilder 17456 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc, 17457 QualType T) { 17458 return diagnoseNotICE(S, Loc); 17459 } 17460 17461 Sema::SemaDiagnosticBuilder 17462 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) { 17463 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus; 17464 } 17465 17466 ExprResult 17467 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 17468 VerifyICEDiagnoser &Diagnoser, 17469 AllowFoldKind CanFold) { 17470 SourceLocation DiagLoc = E->getBeginLoc(); 17471 17472 if (getLangOpts().CPlusPlus11) { 17473 // C++11 [expr.const]p5: 17474 // If an expression of literal class type is used in a context where an 17475 // integral constant expression is required, then that class type shall 17476 // have a single non-explicit conversion function to an integral or 17477 // unscoped enumeration type 17478 ExprResult Converted; 17479 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 17480 VerifyICEDiagnoser &BaseDiagnoser; 17481 public: 17482 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser) 17483 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, 17484 BaseDiagnoser.Suppress, true), 17485 BaseDiagnoser(BaseDiagnoser) {} 17486 17487 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 17488 QualType T) override { 17489 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T); 17490 } 17491 17492 SemaDiagnosticBuilder diagnoseIncomplete( 17493 Sema &S, SourceLocation Loc, QualType T) override { 17494 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 17495 } 17496 17497 SemaDiagnosticBuilder diagnoseExplicitConv( 17498 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 17499 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 17500 } 17501 17502 SemaDiagnosticBuilder noteExplicitConv( 17503 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 17504 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 17505 << ConvTy->isEnumeralType() << ConvTy; 17506 } 17507 17508 SemaDiagnosticBuilder diagnoseAmbiguous( 17509 Sema &S, SourceLocation Loc, QualType T) override { 17510 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 17511 } 17512 17513 SemaDiagnosticBuilder noteAmbiguous( 17514 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 17515 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 17516 << ConvTy->isEnumeralType() << ConvTy; 17517 } 17518 17519 SemaDiagnosticBuilder diagnoseConversion( 17520 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 17521 llvm_unreachable("conversion functions are permitted"); 17522 } 17523 } ConvertDiagnoser(Diagnoser); 17524 17525 Converted = PerformContextualImplicitConversion(DiagLoc, E, 17526 ConvertDiagnoser); 17527 if (Converted.isInvalid()) 17528 return Converted; 17529 E = Converted.get(); 17530 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 17531 return ExprError(); 17532 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 17533 // An ICE must be of integral or unscoped enumeration type. 17534 if (!Diagnoser.Suppress) 17535 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType()) 17536 << E->getSourceRange(); 17537 return ExprError(); 17538 } 17539 17540 ExprResult RValueExpr = DefaultLvalueConversion(E); 17541 if (RValueExpr.isInvalid()) 17542 return ExprError(); 17543 17544 E = RValueExpr.get(); 17545 17546 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 17547 // in the non-ICE case. 17548 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 17549 if (Result) 17550 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 17551 if (!isa<ConstantExpr>(E)) 17552 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result)) 17553 : ConstantExpr::Create(Context, E); 17554 return E; 17555 } 17556 17557 Expr::EvalResult EvalResult; 17558 SmallVector<PartialDiagnosticAt, 8> Notes; 17559 EvalResult.Diag = &Notes; 17560 17561 // Try to evaluate the expression, and produce diagnostics explaining why it's 17562 // not a constant expression as a side-effect. 17563 bool Folded = 17564 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) && 17565 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 17566 17567 if (!isa<ConstantExpr>(E)) 17568 E = ConstantExpr::Create(Context, E, EvalResult.Val); 17569 17570 // In C++11, we can rely on diagnostics being produced for any expression 17571 // which is not a constant expression. If no diagnostics were produced, then 17572 // this is a constant expression. 17573 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 17574 if (Result) 17575 *Result = EvalResult.Val.getInt(); 17576 return E; 17577 } 17578 17579 // If our only note is the usual "invalid subexpression" note, just point 17580 // the caret at its location rather than producing an essentially 17581 // redundant note. 17582 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 17583 diag::note_invalid_subexpr_in_const_expr) { 17584 DiagLoc = Notes[0].first; 17585 Notes.clear(); 17586 } 17587 17588 if (!Folded || !CanFold) { 17589 if (!Diagnoser.Suppress) { 17590 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange(); 17591 for (const PartialDiagnosticAt &Note : Notes) 17592 Diag(Note.first, Note.second); 17593 } 17594 17595 return ExprError(); 17596 } 17597 17598 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange(); 17599 for (const PartialDiagnosticAt &Note : Notes) 17600 Diag(Note.first, Note.second); 17601 17602 if (Result) 17603 *Result = EvalResult.Val.getInt(); 17604 return E; 17605 } 17606 17607 namespace { 17608 // Handle the case where we conclude a expression which we speculatively 17609 // considered to be unevaluated is actually evaluated. 17610 class TransformToPE : public TreeTransform<TransformToPE> { 17611 typedef TreeTransform<TransformToPE> BaseTransform; 17612 17613 public: 17614 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 17615 17616 // Make sure we redo semantic analysis 17617 bool AlwaysRebuild() { return true; } 17618 bool ReplacingOriginal() { return true; } 17619 17620 // We need to special-case DeclRefExprs referring to FieldDecls which 17621 // are not part of a member pointer formation; normal TreeTransforming 17622 // doesn't catch this case because of the way we represent them in the AST. 17623 // FIXME: This is a bit ugly; is it really the best way to handle this 17624 // case? 17625 // 17626 // Error on DeclRefExprs referring to FieldDecls. 17627 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 17628 if (isa<FieldDecl>(E->getDecl()) && 17629 !SemaRef.isUnevaluatedContext()) 17630 return SemaRef.Diag(E->getLocation(), 17631 diag::err_invalid_non_static_member_use) 17632 << E->getDecl() << E->getSourceRange(); 17633 17634 return BaseTransform::TransformDeclRefExpr(E); 17635 } 17636 17637 // Exception: filter out member pointer formation 17638 ExprResult TransformUnaryOperator(UnaryOperator *E) { 17639 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 17640 return E; 17641 17642 return BaseTransform::TransformUnaryOperator(E); 17643 } 17644 17645 // The body of a lambda-expression is in a separate expression evaluation 17646 // context so never needs to be transformed. 17647 // FIXME: Ideally we wouldn't transform the closure type either, and would 17648 // just recreate the capture expressions and lambda expression. 17649 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { 17650 return SkipLambdaBody(E, Body); 17651 } 17652 }; 17653 } 17654 17655 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 17656 assert(isUnevaluatedContext() && 17657 "Should only transform unevaluated expressions"); 17658 ExprEvalContexts.back().Context = 17659 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 17660 if (isUnevaluatedContext()) 17661 return E; 17662 return TransformToPE(*this).TransformExpr(E); 17663 } 17664 17665 TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) { 17666 assert(isUnevaluatedContext() && 17667 "Should only transform unevaluated expressions"); 17668 ExprEvalContexts.back().Context = 17669 ExprEvalContexts[ExprEvalContexts.size() - 2].Context; 17670 if (isUnevaluatedContext()) 17671 return TInfo; 17672 return TransformToPE(*this).TransformType(TInfo); 17673 } 17674 17675 void 17676 Sema::PushExpressionEvaluationContext( 17677 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 17678 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 17679 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 17680 LambdaContextDecl, ExprContext); 17681 17682 // Discarded statements and immediate contexts nested in other 17683 // discarded statements or immediate context are themselves 17684 // a discarded statement or an immediate context, respectively. 17685 ExprEvalContexts.back().InDiscardedStatement = 17686 ExprEvalContexts[ExprEvalContexts.size() - 2] 17687 .isDiscardedStatementContext(); 17688 ExprEvalContexts.back().InImmediateFunctionContext = 17689 ExprEvalContexts[ExprEvalContexts.size() - 2] 17690 .isImmediateFunctionContext(); 17691 17692 Cleanup.reset(); 17693 if (!MaybeODRUseExprs.empty()) 17694 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 17695 } 17696 17697 void 17698 Sema::PushExpressionEvaluationContext( 17699 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 17700 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 17701 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 17702 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 17703 } 17704 17705 namespace { 17706 17707 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) { 17708 PossibleDeref = PossibleDeref->IgnoreParenImpCasts(); 17709 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) { 17710 if (E->getOpcode() == UO_Deref) 17711 return CheckPossibleDeref(S, E->getSubExpr()); 17712 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) { 17713 return CheckPossibleDeref(S, E->getBase()); 17714 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) { 17715 return CheckPossibleDeref(S, E->getBase()); 17716 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) { 17717 QualType Inner; 17718 QualType Ty = E->getType(); 17719 if (const auto *Ptr = Ty->getAs<PointerType>()) 17720 Inner = Ptr->getPointeeType(); 17721 else if (const auto *Arr = S.Context.getAsArrayType(Ty)) 17722 Inner = Arr->getElementType(); 17723 else 17724 return nullptr; 17725 17726 if (Inner->hasAttr(attr::NoDeref)) 17727 return E; 17728 } 17729 return nullptr; 17730 } 17731 17732 } // namespace 17733 17734 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) { 17735 for (const Expr *E : Rec.PossibleDerefs) { 17736 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E); 17737 if (DeclRef) { 17738 const ValueDecl *Decl = DeclRef->getDecl(); 17739 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type) 17740 << Decl->getName() << E->getSourceRange(); 17741 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName(); 17742 } else { 17743 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl) 17744 << E->getSourceRange(); 17745 } 17746 } 17747 Rec.PossibleDerefs.clear(); 17748 } 17749 17750 /// Check whether E, which is either a discarded-value expression or an 17751 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue, 17752 /// and if so, remove it from the list of volatile-qualified assignments that 17753 /// we are going to warn are deprecated. 17754 void Sema::CheckUnusedVolatileAssignment(Expr *E) { 17755 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20) 17756 return; 17757 17758 // Note: ignoring parens here is not justified by the standard rules, but 17759 // ignoring parentheses seems like a more reasonable approach, and this only 17760 // drives a deprecation warning so doesn't affect conformance. 17761 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) { 17762 if (BO->getOpcode() == BO_Assign) { 17763 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs; 17764 llvm::erase_value(LHSs, BO->getLHS()); 17765 } 17766 } 17767 } 17768 17769 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) { 17770 if (isUnevaluatedContext() || !E.isUsable() || !Decl || 17771 !Decl->isConsteval() || isConstantEvaluated() || 17772 isCheckingDefaultArgumentOrInitializer() || 17773 RebuildingImmediateInvocation || isImmediateFunctionContext()) 17774 return E; 17775 17776 /// Opportunistically remove the callee from ReferencesToConsteval if we can. 17777 /// It's OK if this fails; we'll also remove this in 17778 /// HandleImmediateInvocations, but catching it here allows us to avoid 17779 /// walking the AST looking for it in simple cases. 17780 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit())) 17781 if (auto *DeclRef = 17782 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit())) 17783 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef); 17784 17785 E = MaybeCreateExprWithCleanups(E); 17786 17787 ConstantExpr *Res = ConstantExpr::Create( 17788 getASTContext(), E.get(), 17789 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(), 17790 getASTContext()), 17791 /*IsImmediateInvocation*/ true); 17792 /// Value-dependent constant expressions should not be immediately 17793 /// evaluated until they are instantiated. 17794 if (!Res->isValueDependent()) 17795 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0); 17796 return Res; 17797 } 17798 17799 static void EvaluateAndDiagnoseImmediateInvocation( 17800 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) { 17801 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 17802 Expr::EvalResult Eval; 17803 Eval.Diag = &Notes; 17804 ConstantExpr *CE = Candidate.getPointer(); 17805 bool Result = CE->EvaluateAsConstantExpr( 17806 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation); 17807 if (!Result || !Notes.empty()) { 17808 SemaRef.FailedImmediateInvocations.insert(CE); 17809 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit(); 17810 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr)) 17811 InnerExpr = FunctionalCast->getSubExpr(); 17812 FunctionDecl *FD = nullptr; 17813 if (auto *Call = dyn_cast<CallExpr>(InnerExpr)) 17814 FD = cast<FunctionDecl>(Call->getCalleeDecl()); 17815 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr)) 17816 FD = Call->getConstructor(); 17817 else 17818 llvm_unreachable("unhandled decl kind"); 17819 assert(FD && FD->isConsteval()); 17820 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD; 17821 if (auto Context = 17822 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) { 17823 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer) 17824 << Context->Decl; 17825 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at); 17826 } 17827 for (auto &Note : Notes) 17828 SemaRef.Diag(Note.first, Note.second); 17829 return; 17830 } 17831 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext()); 17832 } 17833 17834 static void RemoveNestedImmediateInvocation( 17835 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, 17836 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) { 17837 struct ComplexRemove : TreeTransform<ComplexRemove> { 17838 using Base = TreeTransform<ComplexRemove>; 17839 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 17840 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet; 17841 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator 17842 CurrentII; 17843 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR, 17844 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II, 17845 SmallVector<Sema::ImmediateInvocationCandidate, 17846 4>::reverse_iterator Current) 17847 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {} 17848 void RemoveImmediateInvocation(ConstantExpr* E) { 17849 auto It = std::find_if(CurrentII, IISet.rend(), 17850 [E](Sema::ImmediateInvocationCandidate Elem) { 17851 return Elem.getPointer() == E; 17852 }); 17853 // It is possible that some subexpression of the current immediate 17854 // invocation was handled from another expression evaluation context. Do 17855 // not handle the current immediate invocation if some of its 17856 // subexpressions failed before. 17857 if (It == IISet.rend()) { 17858 if (SemaRef.FailedImmediateInvocations.contains(E)) 17859 CurrentII->setInt(1); 17860 } else { 17861 It->setInt(1); // Mark as deleted 17862 } 17863 } 17864 ExprResult TransformConstantExpr(ConstantExpr *E) { 17865 if (!E->isImmediateInvocation()) 17866 return Base::TransformConstantExpr(E); 17867 RemoveImmediateInvocation(E); 17868 return Base::TransformExpr(E->getSubExpr()); 17869 } 17870 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so 17871 /// we need to remove its DeclRefExpr from the DRSet. 17872 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 17873 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit())); 17874 return Base::TransformCXXOperatorCallExpr(E); 17875 } 17876 /// Base::TransformInitializer skip ConstantExpr so we need to visit them 17877 /// here. 17878 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) { 17879 if (!Init) 17880 return Init; 17881 /// ConstantExpr are the first layer of implicit node to be removed so if 17882 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped. 17883 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 17884 if (CE->isImmediateInvocation()) 17885 RemoveImmediateInvocation(CE); 17886 return Base::TransformInitializer(Init, NotCopyInit); 17887 } 17888 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 17889 DRSet.erase(E); 17890 return E; 17891 } 17892 ExprResult TransformLambdaExpr(LambdaExpr *E) { 17893 // Do not rebuild lambdas to avoid creating a new type. 17894 // Lambdas have already been processed inside their eval context. 17895 return E; 17896 } 17897 bool AlwaysRebuild() { return false; } 17898 bool ReplacingOriginal() { return true; } 17899 bool AllowSkippingCXXConstructExpr() { 17900 bool Res = AllowSkippingFirstCXXConstructExpr; 17901 AllowSkippingFirstCXXConstructExpr = true; 17902 return Res; 17903 } 17904 bool AllowSkippingFirstCXXConstructExpr = true; 17905 } Transformer(SemaRef, Rec.ReferenceToConsteval, 17906 Rec.ImmediateInvocationCandidates, It); 17907 17908 /// CXXConstructExpr with a single argument are getting skipped by 17909 /// TreeTransform in some situtation because they could be implicit. This 17910 /// can only occur for the top-level CXXConstructExpr because it is used 17911 /// nowhere in the expression being transformed therefore will not be rebuilt. 17912 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from 17913 /// skipping the first CXXConstructExpr. 17914 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit())) 17915 Transformer.AllowSkippingFirstCXXConstructExpr = false; 17916 17917 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr()); 17918 // The result may not be usable in case of previous compilation errors. 17919 // In this case evaluation of the expression may result in crash so just 17920 // don't do anything further with the result. 17921 if (Res.isUsable()) { 17922 Res = SemaRef.MaybeCreateExprWithCleanups(Res); 17923 It->getPointer()->setSubExpr(Res.get()); 17924 } 17925 } 17926 17927 static void 17928 HandleImmediateInvocations(Sema &SemaRef, 17929 Sema::ExpressionEvaluationContextRecord &Rec) { 17930 if ((Rec.ImmediateInvocationCandidates.size() == 0 && 17931 Rec.ReferenceToConsteval.size() == 0) || 17932 SemaRef.RebuildingImmediateInvocation) 17933 return; 17934 17935 /// When we have more than 1 ImmediateInvocationCandidates or previously 17936 /// failed immediate invocations, we need to check for nested 17937 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics. 17938 /// Otherwise we only need to remove ReferenceToConsteval in the immediate 17939 /// invocation. 17940 if (Rec.ImmediateInvocationCandidates.size() > 1 || 17941 !SemaRef.FailedImmediateInvocations.empty()) { 17942 17943 /// Prevent sema calls during the tree transform from adding pointers that 17944 /// are already in the sets. 17945 llvm::SaveAndRestore DisableIITracking( 17946 SemaRef.RebuildingImmediateInvocation, true); 17947 17948 /// Prevent diagnostic during tree transfrom as they are duplicates 17949 Sema::TentativeAnalysisScope DisableDiag(SemaRef); 17950 17951 for (auto It = Rec.ImmediateInvocationCandidates.rbegin(); 17952 It != Rec.ImmediateInvocationCandidates.rend(); It++) 17953 if (!It->getInt()) 17954 RemoveNestedImmediateInvocation(SemaRef, Rec, It); 17955 } else if (Rec.ImmediateInvocationCandidates.size() == 1 && 17956 Rec.ReferenceToConsteval.size()) { 17957 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> { 17958 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet; 17959 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {} 17960 bool VisitDeclRefExpr(DeclRefExpr *E) { 17961 DRSet.erase(E); 17962 return DRSet.size(); 17963 } 17964 } Visitor(Rec.ReferenceToConsteval); 17965 Visitor.TraverseStmt( 17966 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr()); 17967 } 17968 for (auto CE : Rec.ImmediateInvocationCandidates) 17969 if (!CE.getInt()) 17970 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE); 17971 for (auto *DR : Rec.ReferenceToConsteval) { 17972 auto *FD = cast<FunctionDecl>(DR->getDecl()); 17973 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address) 17974 << FD; 17975 SemaRef.Diag(FD->getLocation(), diag::note_declared_at); 17976 } 17977 } 17978 17979 void Sema::PopExpressionEvaluationContext() { 17980 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 17981 unsigned NumTypos = Rec.NumTypos; 17982 17983 if (!Rec.Lambdas.empty()) { 17984 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 17985 if (!getLangOpts().CPlusPlus20 && 17986 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || 17987 Rec.isUnevaluated() || 17988 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) { 17989 unsigned D; 17990 if (Rec.isUnevaluated()) { 17991 // C++11 [expr.prim.lambda]p2: 17992 // A lambda-expression shall not appear in an unevaluated operand 17993 // (Clause 5). 17994 D = diag::err_lambda_unevaluated_operand; 17995 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 17996 // C++1y [expr.const]p2: 17997 // A conditional-expression e is a core constant expression unless the 17998 // evaluation of e, following the rules of the abstract machine, would 17999 // evaluate [...] a lambda-expression. 18000 D = diag::err_lambda_in_constant_expression; 18001 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 18002 // C++17 [expr.prim.lamda]p2: 18003 // A lambda-expression shall not appear [...] in a template-argument. 18004 D = diag::err_lambda_in_invalid_context; 18005 } else 18006 llvm_unreachable("Couldn't infer lambda error message."); 18007 18008 for (const auto *L : Rec.Lambdas) 18009 Diag(L->getBeginLoc(), D); 18010 } 18011 } 18012 18013 WarnOnPendingNoDerefs(Rec); 18014 HandleImmediateInvocations(*this, Rec); 18015 18016 // Warn on any volatile-qualified simple-assignments that are not discarded- 18017 // value expressions nor unevaluated operands (those cases get removed from 18018 // this list by CheckUnusedVolatileAssignment). 18019 for (auto *BO : Rec.VolatileAssignmentLHSs) 18020 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile) 18021 << BO->getType(); 18022 18023 // When are coming out of an unevaluated context, clear out any 18024 // temporaries that we may have created as part of the evaluation of 18025 // the expression in that context: they aren't relevant because they 18026 // will never be constructed. 18027 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 18028 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 18029 ExprCleanupObjects.end()); 18030 Cleanup = Rec.ParentCleanup; 18031 CleanupVarDeclMarking(); 18032 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 18033 // Otherwise, merge the contexts together. 18034 } else { 18035 Cleanup.mergeFrom(Rec.ParentCleanup); 18036 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 18037 Rec.SavedMaybeODRUseExprs.end()); 18038 } 18039 18040 // Pop the current expression evaluation context off the stack. 18041 ExprEvalContexts.pop_back(); 18042 18043 // The global expression evaluation context record is never popped. 18044 ExprEvalContexts.back().NumTypos += NumTypos; 18045 } 18046 18047 void Sema::DiscardCleanupsInEvaluationContext() { 18048 ExprCleanupObjects.erase( 18049 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 18050 ExprCleanupObjects.end()); 18051 Cleanup.reset(); 18052 MaybeODRUseExprs.clear(); 18053 } 18054 18055 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 18056 ExprResult Result = CheckPlaceholderExpr(E); 18057 if (Result.isInvalid()) 18058 return ExprError(); 18059 E = Result.get(); 18060 if (!E->getType()->isVariablyModifiedType()) 18061 return E; 18062 return TransformToPotentiallyEvaluated(E); 18063 } 18064 18065 /// Are we in a context that is potentially constant evaluated per C++20 18066 /// [expr.const]p12? 18067 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) { 18068 /// C++2a [expr.const]p12: 18069 // An expression or conversion is potentially constant evaluated if it is 18070 switch (SemaRef.ExprEvalContexts.back().Context) { 18071 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 18072 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 18073 18074 // -- a manifestly constant-evaluated expression, 18075 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 18076 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18077 case Sema::ExpressionEvaluationContext::DiscardedStatement: 18078 // -- a potentially-evaluated expression, 18079 case Sema::ExpressionEvaluationContext::UnevaluatedList: 18080 // -- an immediate subexpression of a braced-init-list, 18081 18082 // -- [FIXME] an expression of the form & cast-expression that occurs 18083 // within a templated entity 18084 // -- a subexpression of one of the above that is not a subexpression of 18085 // a nested unevaluated operand. 18086 return true; 18087 18088 case Sema::ExpressionEvaluationContext::Unevaluated: 18089 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 18090 // Expressions in this context are never evaluated. 18091 return false; 18092 } 18093 llvm_unreachable("Invalid context"); 18094 } 18095 18096 /// Return true if this function has a calling convention that requires mangling 18097 /// in the size of the parameter pack. 18098 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) { 18099 // These manglings don't do anything on non-Windows or non-x86 platforms, so 18100 // we don't need parameter type sizes. 18101 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 18102 if (!TT.isOSWindows() || !TT.isX86()) 18103 return false; 18104 18105 // If this is C++ and this isn't an extern "C" function, parameters do not 18106 // need to be complete. In this case, C++ mangling will apply, which doesn't 18107 // use the size of the parameters. 18108 if (S.getLangOpts().CPlusPlus && !FD->isExternC()) 18109 return false; 18110 18111 // Stdcall, fastcall, and vectorcall need this special treatment. 18112 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 18113 switch (CC) { 18114 case CC_X86StdCall: 18115 case CC_X86FastCall: 18116 case CC_X86VectorCall: 18117 return true; 18118 default: 18119 break; 18120 } 18121 return false; 18122 } 18123 18124 /// Require that all of the parameter types of function be complete. Normally, 18125 /// parameter types are only required to be complete when a function is called 18126 /// or defined, but to mangle functions with certain calling conventions, the 18127 /// mangler needs to know the size of the parameter list. In this situation, 18128 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles 18129 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually 18130 /// result in a linker error. Clang doesn't implement this behavior, and instead 18131 /// attempts to error at compile time. 18132 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, 18133 SourceLocation Loc) { 18134 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser { 18135 FunctionDecl *FD; 18136 ParmVarDecl *Param; 18137 18138 public: 18139 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param) 18140 : FD(FD), Param(Param) {} 18141 18142 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 18143 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 18144 StringRef CCName; 18145 switch (CC) { 18146 case CC_X86StdCall: 18147 CCName = "stdcall"; 18148 break; 18149 case CC_X86FastCall: 18150 CCName = "fastcall"; 18151 break; 18152 case CC_X86VectorCall: 18153 CCName = "vectorcall"; 18154 break; 18155 default: 18156 llvm_unreachable("CC does not need mangling"); 18157 } 18158 18159 S.Diag(Loc, diag::err_cconv_incomplete_param_type) 18160 << Param->getDeclName() << FD->getDeclName() << CCName; 18161 } 18162 }; 18163 18164 for (ParmVarDecl *Param : FD->parameters()) { 18165 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param); 18166 S.RequireCompleteType(Loc, Param->getType(), Diagnoser); 18167 } 18168 } 18169 18170 namespace { 18171 enum class OdrUseContext { 18172 /// Declarations in this context are not odr-used. 18173 None, 18174 /// Declarations in this context are formally odr-used, but this is a 18175 /// dependent context. 18176 Dependent, 18177 /// Declarations in this context are odr-used but not actually used (yet). 18178 FormallyOdrUsed, 18179 /// Declarations in this context are used. 18180 Used 18181 }; 18182 } 18183 18184 /// Are we within a context in which references to resolved functions or to 18185 /// variables result in odr-use? 18186 static OdrUseContext isOdrUseContext(Sema &SemaRef) { 18187 OdrUseContext Result; 18188 18189 switch (SemaRef.ExprEvalContexts.back().Context) { 18190 case Sema::ExpressionEvaluationContext::Unevaluated: 18191 case Sema::ExpressionEvaluationContext::UnevaluatedList: 18192 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 18193 return OdrUseContext::None; 18194 18195 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 18196 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext: 18197 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 18198 Result = OdrUseContext::Used; 18199 break; 18200 18201 case Sema::ExpressionEvaluationContext::DiscardedStatement: 18202 Result = OdrUseContext::FormallyOdrUsed; 18203 break; 18204 18205 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 18206 // A default argument formally results in odr-use, but doesn't actually 18207 // result in a use in any real sense until it itself is used. 18208 Result = OdrUseContext::FormallyOdrUsed; 18209 break; 18210 } 18211 18212 if (SemaRef.CurContext->isDependentContext()) 18213 return OdrUseContext::Dependent; 18214 18215 return Result; 18216 } 18217 18218 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 18219 if (!Func->isConstexpr()) 18220 return false; 18221 18222 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided()) 18223 return true; 18224 auto *CCD = dyn_cast<CXXConstructorDecl>(Func); 18225 return CCD && CCD->getInheritedConstructor(); 18226 } 18227 18228 /// Mark a function referenced, and check whether it is odr-used 18229 /// (C++ [basic.def.odr]p2, C99 6.9p3) 18230 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 18231 bool MightBeOdrUse) { 18232 assert(Func && "No function?"); 18233 18234 Func->setReferenced(); 18235 18236 // Recursive functions aren't really used until they're used from some other 18237 // context. 18238 bool IsRecursiveCall = CurContext == Func; 18239 18240 // C++11 [basic.def.odr]p3: 18241 // A function whose name appears as a potentially-evaluated expression is 18242 // odr-used if it is the unique lookup result or the selected member of a 18243 // set of overloaded functions [...]. 18244 // 18245 // We (incorrectly) mark overload resolution as an unevaluated context, so we 18246 // can just check that here. 18247 OdrUseContext OdrUse = 18248 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None; 18249 if (IsRecursiveCall && OdrUse == OdrUseContext::Used) 18250 OdrUse = OdrUseContext::FormallyOdrUsed; 18251 18252 // Trivial default constructors and destructors are never actually used. 18253 // FIXME: What about other special members? 18254 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() && 18255 OdrUse == OdrUseContext::Used) { 18256 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func)) 18257 if (Constructor->isDefaultConstructor()) 18258 OdrUse = OdrUseContext::FormallyOdrUsed; 18259 if (isa<CXXDestructorDecl>(Func)) 18260 OdrUse = OdrUseContext::FormallyOdrUsed; 18261 } 18262 18263 // C++20 [expr.const]p12: 18264 // A function [...] is needed for constant evaluation if it is [...] a 18265 // constexpr function that is named by an expression that is potentially 18266 // constant evaluated 18267 bool NeededForConstantEvaluation = 18268 isPotentiallyConstantEvaluatedContext(*this) && 18269 isImplicitlyDefinableConstexprFunction(Func); 18270 18271 // Determine whether we require a function definition to exist, per 18272 // C++11 [temp.inst]p3: 18273 // Unless a function template specialization has been explicitly 18274 // instantiated or explicitly specialized, the function template 18275 // specialization is implicitly instantiated when the specialization is 18276 // referenced in a context that requires a function definition to exist. 18277 // C++20 [temp.inst]p7: 18278 // The existence of a definition of a [...] function is considered to 18279 // affect the semantics of the program if the [...] function is needed for 18280 // constant evaluation by an expression 18281 // C++20 [basic.def.odr]p10: 18282 // Every program shall contain exactly one definition of every non-inline 18283 // function or variable that is odr-used in that program outside of a 18284 // discarded statement 18285 // C++20 [special]p1: 18286 // The implementation will implicitly define [defaulted special members] 18287 // if they are odr-used or needed for constant evaluation. 18288 // 18289 // Note that we skip the implicit instantiation of templates that are only 18290 // used in unused default arguments or by recursive calls to themselves. 18291 // This is formally non-conforming, but seems reasonable in practice. 18292 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used || 18293 NeededForConstantEvaluation); 18294 18295 // C++14 [temp.expl.spec]p6: 18296 // If a template [...] is explicitly specialized then that specialization 18297 // shall be declared before the first use of that specialization that would 18298 // cause an implicit instantiation to take place, in every translation unit 18299 // in which such a use occurs 18300 if (NeedDefinition && 18301 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 18302 Func->getMemberSpecializationInfo())) 18303 checkSpecializationReachability(Loc, Func); 18304 18305 if (getLangOpts().CUDA) 18306 CheckCUDACall(Loc, Func); 18307 18308 if (getLangOpts().SYCLIsDevice) 18309 checkSYCLDeviceFunction(Loc, Func); 18310 18311 // If we need a definition, try to create one. 18312 if (NeedDefinition && !Func->getBody()) { 18313 runWithSufficientStackSpace(Loc, [&] { 18314 if (CXXConstructorDecl *Constructor = 18315 dyn_cast<CXXConstructorDecl>(Func)) { 18316 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 18317 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 18318 if (Constructor->isDefaultConstructor()) { 18319 if (Constructor->isTrivial() && 18320 !Constructor->hasAttr<DLLExportAttr>()) 18321 return; 18322 DefineImplicitDefaultConstructor(Loc, Constructor); 18323 } else if (Constructor->isCopyConstructor()) { 18324 DefineImplicitCopyConstructor(Loc, Constructor); 18325 } else if (Constructor->isMoveConstructor()) { 18326 DefineImplicitMoveConstructor(Loc, Constructor); 18327 } 18328 } else if (Constructor->getInheritedConstructor()) { 18329 DefineInheritingConstructor(Loc, Constructor); 18330 } 18331 } else if (CXXDestructorDecl *Destructor = 18332 dyn_cast<CXXDestructorDecl>(Func)) { 18333 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 18334 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 18335 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 18336 return; 18337 DefineImplicitDestructor(Loc, Destructor); 18338 } 18339 if (Destructor->isVirtual() && getLangOpts().AppleKext) 18340 MarkVTableUsed(Loc, Destructor->getParent()); 18341 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 18342 if (MethodDecl->isOverloadedOperator() && 18343 MethodDecl->getOverloadedOperator() == OO_Equal) { 18344 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 18345 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 18346 if (MethodDecl->isCopyAssignmentOperator()) 18347 DefineImplicitCopyAssignment(Loc, MethodDecl); 18348 else if (MethodDecl->isMoveAssignmentOperator()) 18349 DefineImplicitMoveAssignment(Loc, MethodDecl); 18350 } 18351 } else if (isa<CXXConversionDecl>(MethodDecl) && 18352 MethodDecl->getParent()->isLambda()) { 18353 CXXConversionDecl *Conversion = 18354 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 18355 if (Conversion->isLambdaToBlockPointerConversion()) 18356 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 18357 else 18358 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 18359 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 18360 MarkVTableUsed(Loc, MethodDecl->getParent()); 18361 } 18362 18363 if (Func->isDefaulted() && !Func->isDeleted()) { 18364 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func); 18365 if (DCK != DefaultedComparisonKind::None) 18366 DefineDefaultedComparison(Loc, Func, DCK); 18367 } 18368 18369 // Implicit instantiation of function templates and member functions of 18370 // class templates. 18371 if (Func->isImplicitlyInstantiable()) { 18372 TemplateSpecializationKind TSK = 18373 Func->getTemplateSpecializationKindForInstantiation(); 18374 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 18375 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 18376 if (FirstInstantiation) { 18377 PointOfInstantiation = Loc; 18378 if (auto *MSI = Func->getMemberSpecializationInfo()) 18379 MSI->setPointOfInstantiation(Loc); 18380 // FIXME: Notify listener. 18381 else 18382 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 18383 } else if (TSK != TSK_ImplicitInstantiation) { 18384 // Use the point of use as the point of instantiation, instead of the 18385 // point of explicit instantiation (which we track as the actual point 18386 // of instantiation). This gives better backtraces in diagnostics. 18387 PointOfInstantiation = Loc; 18388 } 18389 18390 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 18391 Func->isConstexpr()) { 18392 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 18393 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 18394 CodeSynthesisContexts.size()) 18395 PendingLocalImplicitInstantiations.push_back( 18396 std::make_pair(Func, PointOfInstantiation)); 18397 else if (Func->isConstexpr()) 18398 // Do not defer instantiations of constexpr functions, to avoid the 18399 // expression evaluator needing to call back into Sema if it sees a 18400 // call to such a function. 18401 InstantiateFunctionDefinition(PointOfInstantiation, Func); 18402 else { 18403 Func->setInstantiationIsPending(true); 18404 PendingInstantiations.push_back( 18405 std::make_pair(Func, PointOfInstantiation)); 18406 // Notify the consumer that a function was implicitly instantiated. 18407 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 18408 } 18409 } 18410 } else { 18411 // Walk redefinitions, as some of them may be instantiable. 18412 for (auto *i : Func->redecls()) { 18413 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 18414 MarkFunctionReferenced(Loc, i, MightBeOdrUse); 18415 } 18416 } 18417 }); 18418 } 18419 18420 // If a constructor was defined in the context of a default parameter 18421 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed 18422 // context), its initializers may not be referenced yet. 18423 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 18424 for (CXXCtorInitializer *Init : Constructor->inits()) { 18425 if (Init->isInClassMemberInitializer()) 18426 MarkDeclarationsReferencedInExpr(Init->getInit()); 18427 } 18428 } 18429 18430 // C++14 [except.spec]p17: 18431 // An exception-specification is considered to be needed when: 18432 // - the function is odr-used or, if it appears in an unevaluated operand, 18433 // would be odr-used if the expression were potentially-evaluated; 18434 // 18435 // Note, we do this even if MightBeOdrUse is false. That indicates that the 18436 // function is a pure virtual function we're calling, and in that case the 18437 // function was selected by overload resolution and we need to resolve its 18438 // exception specification for a different reason. 18439 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 18440 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 18441 ResolveExceptionSpec(Loc, FPT); 18442 18443 // If this is the first "real" use, act on that. 18444 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) { 18445 // Keep track of used but undefined functions. 18446 if (!Func->isDefined()) { 18447 if (mightHaveNonExternalLinkage(Func)) 18448 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 18449 else if (Func->getMostRecentDecl()->isInlined() && 18450 !LangOpts.GNUInline && 18451 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 18452 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 18453 else if (isExternalWithNoLinkageType(Func)) 18454 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 18455 } 18456 18457 // Some x86 Windows calling conventions mangle the size of the parameter 18458 // pack into the name. Computing the size of the parameters requires the 18459 // parameter types to be complete. Check that now. 18460 if (funcHasParameterSizeMangling(*this, Func)) 18461 CheckCompleteParameterTypesForMangler(*this, Func, Loc); 18462 18463 // In the MS C++ ABI, the compiler emits destructor variants where they are 18464 // used. If the destructor is used here but defined elsewhere, mark the 18465 // virtual base destructors referenced. If those virtual base destructors 18466 // are inline, this will ensure they are defined when emitting the complete 18467 // destructor variant. This checking may be redundant if the destructor is 18468 // provided later in this TU. 18469 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 18470 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) { 18471 CXXRecordDecl *Parent = Dtor->getParent(); 18472 if (Parent->getNumVBases() > 0 && !Dtor->getBody()) 18473 CheckCompleteDestructorVariant(Loc, Dtor); 18474 } 18475 } 18476 18477 Func->markUsed(Context); 18478 } 18479 } 18480 18481 /// Directly mark a variable odr-used. Given a choice, prefer to use 18482 /// MarkVariableReferenced since it does additional checks and then 18483 /// calls MarkVarDeclODRUsed. 18484 /// If the variable must be captured: 18485 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext 18486 /// - else capture it in the DeclContext that maps to the 18487 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack. 18488 static void 18489 MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef, 18490 const unsigned *const FunctionScopeIndexToStopAt = nullptr) { 18491 // Keep track of used but undefined variables. 18492 // FIXME: We shouldn't suppress this warning for static data members. 18493 VarDecl *Var = V->getPotentiallyDecomposedVarDecl(); 18494 assert(Var && "expected a capturable variable"); 18495 18496 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly && 18497 (!Var->isExternallyVisible() || Var->isInline() || 18498 SemaRef.isExternalWithNoLinkageType(Var)) && 18499 !(Var->isStaticDataMember() && Var->hasInit())) { 18500 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()]; 18501 if (old.isInvalid()) 18502 old = Loc; 18503 } 18504 QualType CaptureType, DeclRefType; 18505 if (SemaRef.LangOpts.OpenMP) 18506 SemaRef.tryCaptureOpenMPLambdas(V); 18507 SemaRef.tryCaptureVariable(V, Loc, Sema::TryCapture_Implicit, 18508 /*EllipsisLoc*/ SourceLocation(), 18509 /*BuildAndDiagnose*/ true, CaptureType, 18510 DeclRefType, FunctionScopeIndexToStopAt); 18511 18512 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) { 18513 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext); 18514 auto VarTarget = SemaRef.IdentifyCUDATarget(Var); 18515 auto UserTarget = SemaRef.IdentifyCUDATarget(FD); 18516 if (VarTarget == Sema::CVT_Host && 18517 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice || 18518 UserTarget == Sema::CFT_Global)) { 18519 // Diagnose ODR-use of host global variables in device functions. 18520 // Reference of device global variables in host functions is allowed 18521 // through shadow variables therefore it is not diagnosed. 18522 if (SemaRef.LangOpts.CUDAIsDevice) { 18523 SemaRef.targetDiag(Loc, diag::err_ref_bad_target) 18524 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget; 18525 SemaRef.targetDiag(Var->getLocation(), 18526 Var->getType().isConstQualified() 18527 ? diag::note_cuda_const_var_unpromoted 18528 : diag::note_cuda_host_var); 18529 } 18530 } else if (VarTarget == Sema::CVT_Device && 18531 (UserTarget == Sema::CFT_Host || 18532 UserTarget == Sema::CFT_HostDevice)) { 18533 // Record a CUDA/HIP device side variable if it is ODR-used 18534 // by host code. This is done conservatively, when the variable is 18535 // referenced in any of the following contexts: 18536 // - a non-function context 18537 // - a host function 18538 // - a host device function 18539 // This makes the ODR-use of the device side variable by host code to 18540 // be visible in the device compilation for the compiler to be able to 18541 // emit template variables instantiated by host code only and to 18542 // externalize the static device side variable ODR-used by host code. 18543 if (!Var->hasExternalStorage()) 18544 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var); 18545 else if (SemaRef.LangOpts.GPURelocatableDeviceCode) 18546 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var); 18547 } 18548 } 18549 18550 V->markUsed(SemaRef.Context); 18551 } 18552 18553 void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, 18554 SourceLocation Loc, 18555 unsigned CapturingScopeIndex) { 18556 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex); 18557 } 18558 18559 void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc, 18560 ValueDecl *var) { 18561 DeclContext *VarDC = var->getDeclContext(); 18562 18563 // If the parameter still belongs to the translation unit, then 18564 // we're actually just using one parameter in the declaration of 18565 // the next. 18566 if (isa<ParmVarDecl>(var) && 18567 isa<TranslationUnitDecl>(VarDC)) 18568 return; 18569 18570 // For C code, don't diagnose about capture if we're not actually in code 18571 // right now; it's impossible to write a non-constant expression outside of 18572 // function context, so we'll get other (more useful) diagnostics later. 18573 // 18574 // For C++, things get a bit more nasty... it would be nice to suppress this 18575 // diagnostic for certain cases like using a local variable in an array bound 18576 // for a member of a local class, but the correct predicate is not obvious. 18577 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 18578 return; 18579 18580 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 18581 unsigned ContextKind = 3; // unknown 18582 if (isa<CXXMethodDecl>(VarDC) && 18583 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 18584 ContextKind = 2; 18585 } else if (isa<FunctionDecl>(VarDC)) { 18586 ContextKind = 0; 18587 } else if (isa<BlockDecl>(VarDC)) { 18588 ContextKind = 1; 18589 } 18590 18591 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 18592 << var << ValueKind << ContextKind << VarDC; 18593 S.Diag(var->getLocation(), diag::note_entity_declared_at) 18594 << var; 18595 18596 // FIXME: Add additional diagnostic info about class etc. which prevents 18597 // capture. 18598 } 18599 18600 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, 18601 ValueDecl *Var, 18602 bool &SubCapturesAreNested, 18603 QualType &CaptureType, 18604 QualType &DeclRefType) { 18605 // Check whether we've already captured it. 18606 if (CSI->CaptureMap.count(Var)) { 18607 // If we found a capture, any subcaptures are nested. 18608 SubCapturesAreNested = true; 18609 18610 // Retrieve the capture type for this variable. 18611 CaptureType = CSI->getCapture(Var).getCaptureType(); 18612 18613 // Compute the type of an expression that refers to this variable. 18614 DeclRefType = CaptureType.getNonReferenceType(); 18615 18616 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 18617 // are mutable in the sense that user can change their value - they are 18618 // private instances of the captured declarations. 18619 const Capture &Cap = CSI->getCapture(Var); 18620 if (Cap.isCopyCapture() && 18621 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 18622 !(isa<CapturedRegionScopeInfo>(CSI) && 18623 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 18624 DeclRefType.addConst(); 18625 return true; 18626 } 18627 return false; 18628 } 18629 18630 // Only block literals, captured statements, and lambda expressions can 18631 // capture; other scopes don't work. 18632 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, 18633 ValueDecl *Var, 18634 SourceLocation Loc, 18635 const bool Diagnose, 18636 Sema &S) { 18637 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 18638 return getLambdaAwareParentOfDeclContext(DC); 18639 18640 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl(); 18641 if (Underlying) { 18642 if (Underlying->hasLocalStorage() && Diagnose) 18643 diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var); 18644 } 18645 return nullptr; 18646 } 18647 18648 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 18649 // certain types of variables (unnamed, variably modified types etc.) 18650 // so check for eligibility. 18651 static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var, 18652 SourceLocation Loc, const bool Diagnose, 18653 Sema &S) { 18654 18655 assert((isa<VarDecl, BindingDecl>(Var)) && 18656 "Only variables and structured bindings can be captured"); 18657 18658 bool IsBlock = isa<BlockScopeInfo>(CSI); 18659 bool IsLambda = isa<LambdaScopeInfo>(CSI); 18660 18661 // Lambdas are not allowed to capture unnamed variables 18662 // (e.g. anonymous unions). 18663 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 18664 // assuming that's the intent. 18665 if (IsLambda && !Var->getDeclName()) { 18666 if (Diagnose) { 18667 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 18668 S.Diag(Var->getLocation(), diag::note_declared_at); 18669 } 18670 return false; 18671 } 18672 18673 // Prohibit variably-modified types in blocks; they're difficult to deal with. 18674 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 18675 if (Diagnose) { 18676 S.Diag(Loc, diag::err_ref_vm_type); 18677 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18678 } 18679 return false; 18680 } 18681 // Prohibit structs with flexible array members too. 18682 // We cannot capture what is in the tail end of the struct. 18683 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 18684 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 18685 if (Diagnose) { 18686 if (IsBlock) 18687 S.Diag(Loc, diag::err_ref_flexarray_type); 18688 else 18689 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var; 18690 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18691 } 18692 return false; 18693 } 18694 } 18695 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 18696 // Lambdas and captured statements are not allowed to capture __block 18697 // variables; they don't support the expected semantics. 18698 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 18699 if (Diagnose) { 18700 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda; 18701 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18702 } 18703 return false; 18704 } 18705 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 18706 if (S.getLangOpts().OpenCL && IsBlock && 18707 Var->getType()->isBlockPointerType()) { 18708 if (Diagnose) 18709 S.Diag(Loc, diag::err_opencl_block_ref_block); 18710 return false; 18711 } 18712 18713 if (isa<BindingDecl>(Var)) { 18714 if (!IsLambda || !S.getLangOpts().CPlusPlus) { 18715 if (Diagnose) 18716 diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var); 18717 return false; 18718 } else if (Diagnose && S.getLangOpts().CPlusPlus) { 18719 S.Diag(Loc, S.LangOpts.CPlusPlus20 18720 ? diag::warn_cxx17_compat_capture_binding 18721 : diag::ext_capture_binding) 18722 << Var; 18723 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var; 18724 } 18725 } 18726 18727 return true; 18728 } 18729 18730 // Returns true if the capture by block was successful. 18731 static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var, 18732 SourceLocation Loc, const bool BuildAndDiagnose, 18733 QualType &CaptureType, QualType &DeclRefType, 18734 const bool Nested, Sema &S, bool Invalid) { 18735 bool ByRef = false; 18736 18737 // Blocks are not allowed to capture arrays, excepting OpenCL. 18738 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 18739 // (decayed to pointers). 18740 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 18741 if (BuildAndDiagnose) { 18742 S.Diag(Loc, diag::err_ref_array_type); 18743 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18744 Invalid = true; 18745 } else { 18746 return false; 18747 } 18748 } 18749 18750 // Forbid the block-capture of autoreleasing variables. 18751 if (!Invalid && 18752 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 18753 if (BuildAndDiagnose) { 18754 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 18755 << /*block*/ 0; 18756 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var; 18757 Invalid = true; 18758 } else { 18759 return false; 18760 } 18761 } 18762 18763 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 18764 if (const auto *PT = CaptureType->getAs<PointerType>()) { 18765 QualType PointeeTy = PT->getPointeeType(); 18766 18767 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() && 18768 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 18769 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) { 18770 if (BuildAndDiagnose) { 18771 SourceLocation VarLoc = Var->getLocation(); 18772 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 18773 S.Diag(VarLoc, diag::note_declare_parameter_strong); 18774 } 18775 } 18776 } 18777 18778 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 18779 if (HasBlocksAttr || CaptureType->isReferenceType() || 18780 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 18781 // Block capture by reference does not change the capture or 18782 // declaration reference types. 18783 ByRef = true; 18784 } else { 18785 // Block capture by copy introduces 'const'. 18786 CaptureType = CaptureType.getNonReferenceType().withConst(); 18787 DeclRefType = CaptureType; 18788 } 18789 18790 // Actually capture the variable. 18791 if (BuildAndDiagnose) 18792 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(), 18793 CaptureType, Invalid); 18794 18795 return !Invalid; 18796 } 18797 18798 /// Capture the given variable in the captured region. 18799 static bool captureInCapturedRegion( 18800 CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc, 18801 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, 18802 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, 18803 bool IsTopScope, Sema &S, bool Invalid) { 18804 // By default, capture variables by reference. 18805 bool ByRef = true; 18806 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 18807 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 18808 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 18809 // Using an LValue reference type is consistent with Lambdas (see below). 18810 if (S.isOpenMPCapturedDecl(Var)) { 18811 bool HasConst = DeclRefType.isConstQualified(); 18812 DeclRefType = DeclRefType.getUnqualifiedType(); 18813 // Don't lose diagnostics about assignments to const. 18814 if (HasConst) 18815 DeclRefType.addConst(); 18816 } 18817 // Do not capture firstprivates in tasks. 18818 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) != 18819 OMPC_unknown) 18820 return true; 18821 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel, 18822 RSI->OpenMPCaptureLevel); 18823 } 18824 18825 if (ByRef) 18826 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 18827 else 18828 CaptureType = DeclRefType; 18829 18830 // Actually capture the variable. 18831 if (BuildAndDiagnose) 18832 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable, 18833 Loc, SourceLocation(), CaptureType, Invalid); 18834 18835 return !Invalid; 18836 } 18837 18838 /// Capture the given variable in the lambda. 18839 static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var, 18840 SourceLocation Loc, const bool BuildAndDiagnose, 18841 QualType &CaptureType, QualType &DeclRefType, 18842 const bool RefersToCapturedVariable, 18843 const Sema::TryCaptureKind Kind, 18844 SourceLocation EllipsisLoc, const bool IsTopScope, 18845 Sema &S, bool Invalid) { 18846 // Determine whether we are capturing by reference or by value. 18847 bool ByRef = false; 18848 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 18849 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 18850 } else { 18851 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 18852 } 18853 18854 BindingDecl *BD = dyn_cast<BindingDecl>(Var); 18855 // FIXME: We should support capturing structured bindings in OpenMP. 18856 if (!Invalid && BD && S.LangOpts.OpenMP) { 18857 if (BuildAndDiagnose) { 18858 S.Diag(Loc, diag::err_capture_binding_openmp) << Var; 18859 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var; 18860 } 18861 Invalid = true; 18862 } 18863 18864 // Compute the type of the field that will capture this variable. 18865 if (ByRef) { 18866 // C++11 [expr.prim.lambda]p15: 18867 // An entity is captured by reference if it is implicitly or 18868 // explicitly captured but not captured by copy. It is 18869 // unspecified whether additional unnamed non-static data 18870 // members are declared in the closure type for entities 18871 // captured by reference. 18872 // 18873 // FIXME: It is not clear whether we want to build an lvalue reference 18874 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 18875 // to do the former, while EDG does the latter. Core issue 1249 will 18876 // clarify, but for now we follow GCC because it's a more permissive and 18877 // easily defensible position. 18878 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 18879 } else { 18880 // C++11 [expr.prim.lambda]p14: 18881 // For each entity captured by copy, an unnamed non-static 18882 // data member is declared in the closure type. The 18883 // declaration order of these members is unspecified. The type 18884 // of such a data member is the type of the corresponding 18885 // captured entity if the entity is not a reference to an 18886 // object, or the referenced type otherwise. [Note: If the 18887 // captured entity is a reference to a function, the 18888 // corresponding data member is also a reference to a 18889 // function. - end note ] 18890 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 18891 if (!RefType->getPointeeType()->isFunctionType()) 18892 CaptureType = RefType->getPointeeType(); 18893 } 18894 18895 // Forbid the lambda copy-capture of autoreleasing variables. 18896 if (!Invalid && 18897 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 18898 if (BuildAndDiagnose) { 18899 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 18900 S.Diag(Var->getLocation(), diag::note_previous_decl) 18901 << Var->getDeclName(); 18902 Invalid = true; 18903 } else { 18904 return false; 18905 } 18906 } 18907 18908 // Make sure that by-copy captures are of a complete and non-abstract type. 18909 if (!Invalid && BuildAndDiagnose) { 18910 if (!CaptureType->isDependentType() && 18911 S.RequireCompleteSizedType( 18912 Loc, CaptureType, 18913 diag::err_capture_of_incomplete_or_sizeless_type, 18914 Var->getDeclName())) 18915 Invalid = true; 18916 else if (S.RequireNonAbstractType(Loc, CaptureType, 18917 diag::err_capture_of_abstract_type)) 18918 Invalid = true; 18919 } 18920 } 18921 18922 // Compute the type of a reference to this captured variable. 18923 if (ByRef) 18924 DeclRefType = CaptureType.getNonReferenceType(); 18925 else { 18926 // C++ [expr.prim.lambda]p5: 18927 // The closure type for a lambda-expression has a public inline 18928 // function call operator [...]. This function call operator is 18929 // declared const (9.3.1) if and only if the lambda-expression's 18930 // parameter-declaration-clause is not followed by mutable. 18931 DeclRefType = CaptureType.getNonReferenceType(); 18932 if (!LSI->Mutable && !CaptureType->isReferenceType()) 18933 DeclRefType.addConst(); 18934 } 18935 18936 // Add the capture. 18937 if (BuildAndDiagnose) 18938 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable, 18939 Loc, EllipsisLoc, CaptureType, Invalid); 18940 18941 return !Invalid; 18942 } 18943 18944 static bool canCaptureVariableByCopy(ValueDecl *Var, 18945 const ASTContext &Context) { 18946 // Offer a Copy fix even if the type is dependent. 18947 if (Var->getType()->isDependentType()) 18948 return true; 18949 QualType T = Var->getType().getNonReferenceType(); 18950 if (T.isTriviallyCopyableType(Context)) 18951 return true; 18952 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 18953 18954 if (!(RD = RD->getDefinition())) 18955 return false; 18956 if (RD->hasSimpleCopyConstructor()) 18957 return true; 18958 if (RD->hasUserDeclaredCopyConstructor()) 18959 for (CXXConstructorDecl *Ctor : RD->ctors()) 18960 if (Ctor->isCopyConstructor()) 18961 return !Ctor->isDeleted(); 18962 } 18963 return false; 18964 } 18965 18966 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or 18967 /// default capture. Fixes may be omitted if they aren't allowed by the 18968 /// standard, for example we can't emit a default copy capture fix-it if we 18969 /// already explicitly copy capture capture another variable. 18970 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, 18971 ValueDecl *Var) { 18972 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None); 18973 // Don't offer Capture by copy of default capture by copy fixes if Var is 18974 // known not to be copy constructible. 18975 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext()); 18976 18977 SmallString<32> FixBuffer; 18978 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : ""; 18979 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) { 18980 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd(); 18981 if (ShouldOfferCopyFix) { 18982 // Offer fixes to insert an explicit capture for the variable. 18983 // [] -> [VarName] 18984 // [OtherCapture] -> [OtherCapture, VarName] 18985 FixBuffer.assign({Separator, Var->getName()}); 18986 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 18987 << Var << /*value*/ 0 18988 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 18989 } 18990 // As above but capture by reference. 18991 FixBuffer.assign({Separator, "&", Var->getName()}); 18992 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit) 18993 << Var << /*reference*/ 1 18994 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer); 18995 } 18996 18997 // Only try to offer default capture if there are no captures excluding this 18998 // and init captures. 18999 // [this]: OK. 19000 // [X = Y]: OK. 19001 // [&A, &B]: Don't offer. 19002 // [A, B]: Don't offer. 19003 if (llvm::any_of(LSI->Captures, [](Capture &C) { 19004 return !C.isThisCapture() && !C.isInitCapture(); 19005 })) 19006 return; 19007 19008 // The default capture specifiers, '=' or '&', must appear first in the 19009 // capture body. 19010 SourceLocation DefaultInsertLoc = 19011 LSI->IntroducerRange.getBegin().getLocWithOffset(1); 19012 19013 if (ShouldOfferCopyFix) { 19014 bool CanDefaultCopyCapture = true; 19015 // [=, *this] OK since c++17 19016 // [=, this] OK since c++20 19017 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20) 19018 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17 19019 ? LSI->getCXXThisCapture().isCopyCapture() 19020 : false; 19021 // We can't use default capture by copy if any captures already specified 19022 // capture by copy. 19023 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) { 19024 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture(); 19025 })) { 19026 FixBuffer.assign({"=", Separator}); 19027 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 19028 << /*value*/ 0 19029 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 19030 } 19031 } 19032 19033 // We can't use default capture by reference if any captures already specified 19034 // capture by reference. 19035 if (llvm::none_of(LSI->Captures, [](Capture &C) { 19036 return !C.isInitCapture() && C.isReferenceCapture() && 19037 !C.isThisCapture(); 19038 })) { 19039 FixBuffer.assign({"&", Separator}); 19040 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit) 19041 << /*reference*/ 1 19042 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer); 19043 } 19044 } 19045 19046 bool Sema::tryCaptureVariable( 19047 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 19048 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 19049 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 19050 // An init-capture is notionally from the context surrounding its 19051 // declaration, but its parent DC is the lambda class. 19052 DeclContext *VarDC = Var->getDeclContext(); 19053 const auto *VD = dyn_cast<VarDecl>(Var); 19054 if (VD) { 19055 if (VD->isInitCapture()) 19056 VarDC = VarDC->getParent(); 19057 } else { 19058 VD = Var->getPotentiallyDecomposedVarDecl(); 19059 } 19060 assert(VD && "Cannot capture a null variable"); 19061 19062 DeclContext *DC = CurContext; 19063 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 19064 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 19065 // We need to sync up the Declaration Context with the 19066 // FunctionScopeIndexToStopAt 19067 if (FunctionScopeIndexToStopAt) { 19068 unsigned FSIndex = FunctionScopes.size() - 1; 19069 while (FSIndex != MaxFunctionScopesIndex) { 19070 DC = getLambdaAwareParentOfDeclContext(DC); 19071 --FSIndex; 19072 } 19073 } 19074 19075 19076 // If the variable is declared in the current context, there is no need to 19077 // capture it. 19078 if (VarDC == DC) return true; 19079 19080 // Capture global variables if it is required to use private copy of this 19081 // variable. 19082 bool IsGlobal = !VD->hasLocalStorage(); 19083 if (IsGlobal && 19084 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true, 19085 MaxFunctionScopesIndex))) 19086 return true; 19087 19088 if (isa<VarDecl>(Var)) 19089 Var = cast<VarDecl>(Var->getCanonicalDecl()); 19090 19091 // Walk up the stack to determine whether we can capture the variable, 19092 // performing the "simple" checks that don't depend on type. We stop when 19093 // we've either hit the declared scope of the variable or find an existing 19094 // capture of that variable. We start from the innermost capturing-entity 19095 // (the DC) and ensure that all intervening capturing-entities 19096 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 19097 // declcontext can either capture the variable or have already captured 19098 // the variable. 19099 CaptureType = Var->getType(); 19100 DeclRefType = CaptureType.getNonReferenceType(); 19101 bool Nested = false; 19102 bool Explicit = (Kind != TryCapture_Implicit); 19103 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 19104 do { 19105 // Only block literals, captured statements, and lambda expressions can 19106 // capture; other scopes don't work. 19107 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 19108 ExprLoc, 19109 BuildAndDiagnose, 19110 *this); 19111 // We need to check for the parent *first* because, if we *have* 19112 // private-captured a global variable, we need to recursively capture it in 19113 // intermediate blocks, lambdas, etc. 19114 if (!ParentDC) { 19115 if (IsGlobal) { 19116 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 19117 break; 19118 } 19119 return true; 19120 } 19121 19122 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 19123 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 19124 19125 19126 // Check whether we've already captured it. 19127 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 19128 DeclRefType)) { 19129 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 19130 break; 19131 } 19132 // If we are instantiating a generic lambda call operator body, 19133 // we do not want to capture new variables. What was captured 19134 // during either a lambdas transformation or initial parsing 19135 // should be used. 19136 if (isGenericLambdaCallOperatorSpecialization(DC)) { 19137 if (BuildAndDiagnose) { 19138 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 19139 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 19140 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 19141 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 19142 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 19143 buildLambdaCaptureFixit(*this, LSI, Var); 19144 } else 19145 diagnoseUncapturableValueReferenceOrBinding(*this, ExprLoc, Var); 19146 } 19147 return true; 19148 } 19149 19150 // Try to capture variable-length arrays types. 19151 if (Var->getType()->isVariablyModifiedType()) { 19152 // We're going to walk down into the type and look for VLA 19153 // expressions. 19154 QualType QTy = Var->getType(); 19155 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 19156 QTy = PVD->getOriginalType(); 19157 captureVariablyModifiedType(Context, QTy, CSI); 19158 } 19159 19160 if (getLangOpts().OpenMP) { 19161 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 19162 // OpenMP private variables should not be captured in outer scope, so 19163 // just break here. Similarly, global variables that are captured in a 19164 // target region should not be captured outside the scope of the region. 19165 if (RSI->CapRegionKind == CR_OpenMP) { 19166 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl( 19167 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel); 19168 // If the variable is private (i.e. not captured) and has variably 19169 // modified type, we still need to capture the type for correct 19170 // codegen in all regions, associated with the construct. Currently, 19171 // it is captured in the innermost captured region only. 19172 if (IsOpenMPPrivateDecl != OMPC_unknown && 19173 Var->getType()->isVariablyModifiedType()) { 19174 QualType QTy = Var->getType(); 19175 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 19176 QTy = PVD->getOriginalType(); 19177 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel); 19178 I < E; ++I) { 19179 auto *OuterRSI = cast<CapturedRegionScopeInfo>( 19180 FunctionScopes[FunctionScopesIndex - I]); 19181 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel && 19182 "Wrong number of captured regions associated with the " 19183 "OpenMP construct."); 19184 captureVariablyModifiedType(Context, QTy, OuterRSI); 19185 } 19186 } 19187 bool IsTargetCap = 19188 IsOpenMPPrivateDecl != OMPC_private && 19189 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel, 19190 RSI->OpenMPCaptureLevel); 19191 // Do not capture global if it is not privatized in outer regions. 19192 bool IsGlobalCap = 19193 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel, 19194 RSI->OpenMPCaptureLevel); 19195 19196 // When we detect target captures we are looking from inside the 19197 // target region, therefore we need to propagate the capture from the 19198 // enclosing region. Therefore, the capture is not initially nested. 19199 if (IsTargetCap) 19200 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 19201 19202 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private || 19203 (IsGlobal && !IsGlobalCap)) { 19204 Nested = !IsTargetCap; 19205 bool HasConst = DeclRefType.isConstQualified(); 19206 DeclRefType = DeclRefType.getUnqualifiedType(); 19207 // Don't lose diagnostics about assignments to const. 19208 if (HasConst) 19209 DeclRefType.addConst(); 19210 CaptureType = Context.getLValueReferenceType(DeclRefType); 19211 break; 19212 } 19213 } 19214 } 19215 } 19216 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 19217 // No capture-default, and this is not an explicit capture 19218 // so cannot capture this variable. 19219 if (BuildAndDiagnose) { 19220 Diag(ExprLoc, diag::err_lambda_impcap) << Var; 19221 Diag(Var->getLocation(), diag::note_previous_decl) << Var; 19222 auto *LSI = cast<LambdaScopeInfo>(CSI); 19223 if (LSI->Lambda) { 19224 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 19225 buildLambdaCaptureFixit(*this, LSI, Var); 19226 } 19227 // FIXME: If we error out because an outer lambda can not implicitly 19228 // capture a variable that an inner lambda explicitly captures, we 19229 // should have the inner lambda do the explicit capture - because 19230 // it makes for cleaner diagnostics later. This would purely be done 19231 // so that the diagnostic does not misleadingly claim that a variable 19232 // can not be captured by a lambda implicitly even though it is captured 19233 // explicitly. Suggestion: 19234 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 19235 // at the function head 19236 // - cache the StartingDeclContext - this must be a lambda 19237 // - captureInLambda in the innermost lambda the variable. 19238 } 19239 return true; 19240 } 19241 19242 FunctionScopesIndex--; 19243 DC = ParentDC; 19244 Explicit = false; 19245 } while (!VarDC->Equals(DC)); 19246 19247 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 19248 // computing the type of the capture at each step, checking type-specific 19249 // requirements, and adding captures if requested. 19250 // If the variable had already been captured previously, we start capturing 19251 // at the lambda nested within that one. 19252 bool Invalid = false; 19253 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 19254 ++I) { 19255 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 19256 19257 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 19258 // certain types of variables (unnamed, variably modified types etc.) 19259 // so check for eligibility. 19260 if (!Invalid) 19261 Invalid = 19262 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this); 19263 19264 // After encountering an error, if we're actually supposed to capture, keep 19265 // capturing in nested contexts to suppress any follow-on diagnostics. 19266 if (Invalid && !BuildAndDiagnose) 19267 return true; 19268 19269 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 19270 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 19271 DeclRefType, Nested, *this, Invalid); 19272 Nested = true; 19273 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 19274 Invalid = !captureInCapturedRegion( 19275 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested, 19276 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid); 19277 Nested = true; 19278 } else { 19279 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 19280 Invalid = 19281 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, 19282 DeclRefType, Nested, Kind, EllipsisLoc, 19283 /*IsTopScope*/ I == N - 1, *this, Invalid); 19284 Nested = true; 19285 } 19286 19287 if (Invalid && !BuildAndDiagnose) 19288 return true; 19289 } 19290 return Invalid; 19291 } 19292 19293 bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, 19294 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 19295 QualType CaptureType; 19296 QualType DeclRefType; 19297 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 19298 /*BuildAndDiagnose=*/true, CaptureType, 19299 DeclRefType, nullptr); 19300 } 19301 19302 bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) { 19303 QualType CaptureType; 19304 QualType DeclRefType; 19305 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 19306 /*BuildAndDiagnose=*/false, CaptureType, 19307 DeclRefType, nullptr); 19308 } 19309 19310 QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) { 19311 QualType CaptureType; 19312 QualType DeclRefType; 19313 19314 // Determine whether we can capture this variable. 19315 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 19316 /*BuildAndDiagnose=*/false, CaptureType, 19317 DeclRefType, nullptr)) 19318 return QualType(); 19319 19320 return DeclRefType; 19321 } 19322 19323 namespace { 19324 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr. 19325 // The produced TemplateArgumentListInfo* points to data stored within this 19326 // object, so should only be used in contexts where the pointer will not be 19327 // used after the CopiedTemplateArgs object is destroyed. 19328 class CopiedTemplateArgs { 19329 bool HasArgs; 19330 TemplateArgumentListInfo TemplateArgStorage; 19331 public: 19332 template<typename RefExpr> 19333 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) { 19334 if (HasArgs) 19335 E->copyTemplateArgumentsInto(TemplateArgStorage); 19336 } 19337 operator TemplateArgumentListInfo*() 19338 #ifdef __has_cpp_attribute 19339 #if __has_cpp_attribute(clang::lifetimebound) 19340 [[clang::lifetimebound]] 19341 #endif 19342 #endif 19343 { 19344 return HasArgs ? &TemplateArgStorage : nullptr; 19345 } 19346 }; 19347 } 19348 19349 /// Walk the set of potential results of an expression and mark them all as 19350 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason. 19351 /// 19352 /// \return A new expression if we found any potential results, ExprEmpty() if 19353 /// not, and ExprError() if we diagnosed an error. 19354 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, 19355 NonOdrUseReason NOUR) { 19356 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 19357 // an object that satisfies the requirements for appearing in a 19358 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 19359 // is immediately applied." This function handles the lvalue-to-rvalue 19360 // conversion part. 19361 // 19362 // If we encounter a node that claims to be an odr-use but shouldn't be, we 19363 // transform it into the relevant kind of non-odr-use node and rebuild the 19364 // tree of nodes leading to it. 19365 // 19366 // This is a mini-TreeTransform that only transforms a restricted subset of 19367 // nodes (and only certain operands of them). 19368 19369 // Rebuild a subexpression. 19370 auto Rebuild = [&](Expr *Sub) { 19371 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR); 19372 }; 19373 19374 // Check whether a potential result satisfies the requirements of NOUR. 19375 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) { 19376 // Any entity other than a VarDecl is always odr-used whenever it's named 19377 // in a potentially-evaluated expression. 19378 auto *VD = dyn_cast<VarDecl>(D); 19379 if (!VD) 19380 return true; 19381 19382 // C++2a [basic.def.odr]p4: 19383 // A variable x whose name appears as a potentially-evalauted expression 19384 // e is odr-used by e unless 19385 // -- x is a reference that is usable in constant expressions, or 19386 // -- x is a variable of non-reference type that is usable in constant 19387 // expressions and has no mutable subobjects, and e is an element of 19388 // the set of potential results of an expression of 19389 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 19390 // conversion is applied, or 19391 // -- x is a variable of non-reference type, and e is an element of the 19392 // set of potential results of a discarded-value expression to which 19393 // the lvalue-to-rvalue conversion is not applied 19394 // 19395 // We check the first bullet and the "potentially-evaluated" condition in 19396 // BuildDeclRefExpr. We check the type requirements in the second bullet 19397 // in CheckLValueToRValueConversionOperand below. 19398 switch (NOUR) { 19399 case NOUR_None: 19400 case NOUR_Unevaluated: 19401 llvm_unreachable("unexpected non-odr-use-reason"); 19402 19403 case NOUR_Constant: 19404 // Constant references were handled when they were built. 19405 if (VD->getType()->isReferenceType()) 19406 return true; 19407 if (auto *RD = VD->getType()->getAsCXXRecordDecl()) 19408 if (RD->hasMutableFields()) 19409 return true; 19410 if (!VD->isUsableInConstantExpressions(S.Context)) 19411 return true; 19412 break; 19413 19414 case NOUR_Discarded: 19415 if (VD->getType()->isReferenceType()) 19416 return true; 19417 break; 19418 } 19419 return false; 19420 }; 19421 19422 // Mark that this expression does not constitute an odr-use. 19423 auto MarkNotOdrUsed = [&] { 19424 S.MaybeODRUseExprs.remove(E); 19425 if (LambdaScopeInfo *LSI = S.getCurLambda()) 19426 LSI->markVariableExprAsNonODRUsed(E); 19427 }; 19428 19429 // C++2a [basic.def.odr]p2: 19430 // The set of potential results of an expression e is defined as follows: 19431 switch (E->getStmtClass()) { 19432 // -- If e is an id-expression, ... 19433 case Expr::DeclRefExprClass: { 19434 auto *DRE = cast<DeclRefExpr>(E); 19435 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl())) 19436 break; 19437 19438 // Rebuild as a non-odr-use DeclRefExpr. 19439 MarkNotOdrUsed(); 19440 return DeclRefExpr::Create( 19441 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(), 19442 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(), 19443 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(), 19444 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR); 19445 } 19446 19447 case Expr::FunctionParmPackExprClass: { 19448 auto *FPPE = cast<FunctionParmPackExpr>(E); 19449 // If any of the declarations in the pack is odr-used, then the expression 19450 // as a whole constitutes an odr-use. 19451 for (VarDecl *D : *FPPE) 19452 if (IsPotentialResultOdrUsed(D)) 19453 return ExprEmpty(); 19454 19455 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice, 19456 // nothing cares about whether we marked this as an odr-use, but it might 19457 // be useful for non-compiler tools. 19458 MarkNotOdrUsed(); 19459 break; 19460 } 19461 19462 // -- If e is a subscripting operation with an array operand... 19463 case Expr::ArraySubscriptExprClass: { 19464 auto *ASE = cast<ArraySubscriptExpr>(E); 19465 Expr *OldBase = ASE->getBase()->IgnoreImplicit(); 19466 if (!OldBase->getType()->isArrayType()) 19467 break; 19468 ExprResult Base = Rebuild(OldBase); 19469 if (!Base.isUsable()) 19470 return Base; 19471 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS(); 19472 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS(); 19473 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored. 19474 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS, 19475 ASE->getRBracketLoc()); 19476 } 19477 19478 case Expr::MemberExprClass: { 19479 auto *ME = cast<MemberExpr>(E); 19480 // -- If e is a class member access expression [...] naming a non-static 19481 // data member... 19482 if (isa<FieldDecl>(ME->getMemberDecl())) { 19483 ExprResult Base = Rebuild(ME->getBase()); 19484 if (!Base.isUsable()) 19485 return Base; 19486 return MemberExpr::Create( 19487 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(), 19488 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), 19489 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(), 19490 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(), 19491 ME->getObjectKind(), ME->isNonOdrUse()); 19492 } 19493 19494 if (ME->getMemberDecl()->isCXXInstanceMember()) 19495 break; 19496 19497 // -- If e is a class member access expression naming a static data member, 19498 // ... 19499 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl())) 19500 break; 19501 19502 // Rebuild as a non-odr-use MemberExpr. 19503 MarkNotOdrUsed(); 19504 return MemberExpr::Create( 19505 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(), 19506 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(), 19507 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME), 19508 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR); 19509 } 19510 19511 case Expr::BinaryOperatorClass: { 19512 auto *BO = cast<BinaryOperator>(E); 19513 Expr *LHS = BO->getLHS(); 19514 Expr *RHS = BO->getRHS(); 19515 // -- If e is a pointer-to-member expression of the form e1 .* e2 ... 19516 if (BO->getOpcode() == BO_PtrMemD) { 19517 ExprResult Sub = Rebuild(LHS); 19518 if (!Sub.isUsable()) 19519 return Sub; 19520 LHS = Sub.get(); 19521 // -- If e is a comma expression, ... 19522 } else if (BO->getOpcode() == BO_Comma) { 19523 ExprResult Sub = Rebuild(RHS); 19524 if (!Sub.isUsable()) 19525 return Sub; 19526 RHS = Sub.get(); 19527 } else { 19528 break; 19529 } 19530 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(), 19531 LHS, RHS); 19532 } 19533 19534 // -- If e has the form (e1)... 19535 case Expr::ParenExprClass: { 19536 auto *PE = cast<ParenExpr>(E); 19537 ExprResult Sub = Rebuild(PE->getSubExpr()); 19538 if (!Sub.isUsable()) 19539 return Sub; 19540 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get()); 19541 } 19542 19543 // -- If e is a glvalue conditional expression, ... 19544 // We don't apply this to a binary conditional operator. FIXME: Should we? 19545 case Expr::ConditionalOperatorClass: { 19546 auto *CO = cast<ConditionalOperator>(E); 19547 ExprResult LHS = Rebuild(CO->getLHS()); 19548 if (LHS.isInvalid()) 19549 return ExprError(); 19550 ExprResult RHS = Rebuild(CO->getRHS()); 19551 if (RHS.isInvalid()) 19552 return ExprError(); 19553 if (!LHS.isUsable() && !RHS.isUsable()) 19554 return ExprEmpty(); 19555 if (!LHS.isUsable()) 19556 LHS = CO->getLHS(); 19557 if (!RHS.isUsable()) 19558 RHS = CO->getRHS(); 19559 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(), 19560 CO->getCond(), LHS.get(), RHS.get()); 19561 } 19562 19563 // [Clang extension] 19564 // -- If e has the form __extension__ e1... 19565 case Expr::UnaryOperatorClass: { 19566 auto *UO = cast<UnaryOperator>(E); 19567 if (UO->getOpcode() != UO_Extension) 19568 break; 19569 ExprResult Sub = Rebuild(UO->getSubExpr()); 19570 if (!Sub.isUsable()) 19571 return Sub; 19572 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension, 19573 Sub.get()); 19574 } 19575 19576 // [Clang extension] 19577 // -- If e has the form _Generic(...), the set of potential results is the 19578 // union of the sets of potential results of the associated expressions. 19579 case Expr::GenericSelectionExprClass: { 19580 auto *GSE = cast<GenericSelectionExpr>(E); 19581 19582 SmallVector<Expr *, 4> AssocExprs; 19583 bool AnyChanged = false; 19584 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) { 19585 ExprResult AssocExpr = Rebuild(OrigAssocExpr); 19586 if (AssocExpr.isInvalid()) 19587 return ExprError(); 19588 if (AssocExpr.isUsable()) { 19589 AssocExprs.push_back(AssocExpr.get()); 19590 AnyChanged = true; 19591 } else { 19592 AssocExprs.push_back(OrigAssocExpr); 19593 } 19594 } 19595 19596 return AnyChanged ? S.CreateGenericSelectionExpr( 19597 GSE->getGenericLoc(), GSE->getDefaultLoc(), 19598 GSE->getRParenLoc(), GSE->getControllingExpr(), 19599 GSE->getAssocTypeSourceInfos(), AssocExprs) 19600 : ExprEmpty(); 19601 } 19602 19603 // [Clang extension] 19604 // -- If e has the form __builtin_choose_expr(...), the set of potential 19605 // results is the union of the sets of potential results of the 19606 // second and third subexpressions. 19607 case Expr::ChooseExprClass: { 19608 auto *CE = cast<ChooseExpr>(E); 19609 19610 ExprResult LHS = Rebuild(CE->getLHS()); 19611 if (LHS.isInvalid()) 19612 return ExprError(); 19613 19614 ExprResult RHS = Rebuild(CE->getLHS()); 19615 if (RHS.isInvalid()) 19616 return ExprError(); 19617 19618 if (!LHS.get() && !RHS.get()) 19619 return ExprEmpty(); 19620 if (!LHS.isUsable()) 19621 LHS = CE->getLHS(); 19622 if (!RHS.isUsable()) 19623 RHS = CE->getRHS(); 19624 19625 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(), 19626 RHS.get(), CE->getRParenLoc()); 19627 } 19628 19629 // Step through non-syntactic nodes. 19630 case Expr::ConstantExprClass: { 19631 auto *CE = cast<ConstantExpr>(E); 19632 ExprResult Sub = Rebuild(CE->getSubExpr()); 19633 if (!Sub.isUsable()) 19634 return Sub; 19635 return ConstantExpr::Create(S.Context, Sub.get()); 19636 } 19637 19638 // We could mostly rely on the recursive rebuilding to rebuild implicit 19639 // casts, but not at the top level, so rebuild them here. 19640 case Expr::ImplicitCastExprClass: { 19641 auto *ICE = cast<ImplicitCastExpr>(E); 19642 // Only step through the narrow set of cast kinds we expect to encounter. 19643 // Anything else suggests we've left the region in which potential results 19644 // can be found. 19645 switch (ICE->getCastKind()) { 19646 case CK_NoOp: 19647 case CK_DerivedToBase: 19648 case CK_UncheckedDerivedToBase: { 19649 ExprResult Sub = Rebuild(ICE->getSubExpr()); 19650 if (!Sub.isUsable()) 19651 return Sub; 19652 CXXCastPath Path(ICE->path()); 19653 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(), 19654 ICE->getValueKind(), &Path); 19655 } 19656 19657 default: 19658 break; 19659 } 19660 break; 19661 } 19662 19663 default: 19664 break; 19665 } 19666 19667 // Can't traverse through this node. Nothing to do. 19668 return ExprEmpty(); 19669 } 19670 19671 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) { 19672 // Check whether the operand is or contains an object of non-trivial C union 19673 // type. 19674 if (E->getType().isVolatileQualified() && 19675 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() || 19676 E->getType().hasNonTrivialToPrimitiveCopyCUnion())) 19677 checkNonTrivialCUnion(E->getType(), E->getExprLoc(), 19678 Sema::NTCUC_LValueToRValueVolatile, 19679 NTCUK_Destruct|NTCUK_Copy); 19680 19681 // C++2a [basic.def.odr]p4: 19682 // [...] an expression of non-volatile-qualified non-class type to which 19683 // the lvalue-to-rvalue conversion is applied [...] 19684 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>()) 19685 return E; 19686 19687 ExprResult Result = 19688 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant); 19689 if (Result.isInvalid()) 19690 return ExprError(); 19691 return Result.get() ? Result : E; 19692 } 19693 19694 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 19695 Res = CorrectDelayedTyposInExpr(Res); 19696 19697 if (!Res.isUsable()) 19698 return Res; 19699 19700 // If a constant-expression is a reference to a variable where we delay 19701 // deciding whether it is an odr-use, just assume we will apply the 19702 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 19703 // (a non-type template argument), we have special handling anyway. 19704 return CheckLValueToRValueConversionOperand(Res.get()); 19705 } 19706 19707 void Sema::CleanupVarDeclMarking() { 19708 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive 19709 // call. 19710 MaybeODRUseExprSet LocalMaybeODRUseExprs; 19711 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs); 19712 19713 for (Expr *E : LocalMaybeODRUseExprs) { 19714 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 19715 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()), 19716 DRE->getLocation(), *this); 19717 } else if (auto *ME = dyn_cast<MemberExpr>(E)) { 19718 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(), 19719 *this); 19720 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) { 19721 for (VarDecl *VD : *FP) 19722 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this); 19723 } else { 19724 llvm_unreachable("Unexpected expression"); 19725 } 19726 } 19727 19728 assert(MaybeODRUseExprs.empty() && 19729 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"); 19730 } 19731 19732 static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc, 19733 ValueDecl *Var, Expr *E) { 19734 VarDecl *VD = Var->getPotentiallyDecomposedVarDecl(); 19735 if (!VD) 19736 return; 19737 19738 const bool RefersToEnclosingScope = 19739 (SemaRef.CurContext != VD->getDeclContext() && 19740 VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage()); 19741 if (RefersToEnclosingScope) { 19742 LambdaScopeInfo *const LSI = 19743 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 19744 if (LSI && (!LSI->CallOperator || 19745 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 19746 // If a variable could potentially be odr-used, defer marking it so 19747 // until we finish analyzing the full expression for any 19748 // lvalue-to-rvalue 19749 // or discarded value conversions that would obviate odr-use. 19750 // Add it to the list of potential captures that will be analyzed 19751 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 19752 // unless the variable is a reference that was initialized by a constant 19753 // expression (this will never need to be captured or odr-used). 19754 // 19755 // FIXME: We can simplify this a lot after implementing P0588R1. 19756 assert(E && "Capture variable should be used in an expression."); 19757 if (!Var->getType()->isReferenceType() || 19758 !VD->isUsableInConstantExpressions(SemaRef.Context)) 19759 LSI->addPotentialCapture(E->IgnoreParens()); 19760 } 19761 } 19762 } 19763 19764 static void DoMarkVarDeclReferenced( 19765 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, 19766 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 19767 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || 19768 isa<FunctionParmPackExpr>(E)) && 19769 "Invalid Expr argument to DoMarkVarDeclReferenced"); 19770 Var->setReferenced(); 19771 19772 if (Var->isInvalidDecl()) 19773 return; 19774 19775 auto *MSI = Var->getMemberSpecializationInfo(); 19776 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind() 19777 : Var->getTemplateSpecializationKind(); 19778 19779 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 19780 bool UsableInConstantExpr = 19781 Var->mightBeUsableInConstantExpressions(SemaRef.Context); 19782 19783 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) { 19784 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++; 19785 } 19786 19787 // C++20 [expr.const]p12: 19788 // A variable [...] is needed for constant evaluation if it is [...] a 19789 // variable whose name appears as a potentially constant evaluated 19790 // expression that is either a contexpr variable or is of non-volatile 19791 // const-qualified integral type or of reference type 19792 bool NeededForConstantEvaluation = 19793 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr; 19794 19795 bool NeedDefinition = 19796 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation; 19797 19798 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 19799 "Can't instantiate a partial template specialization."); 19800 19801 // If this might be a member specialization of a static data member, check 19802 // the specialization is visible. We already did the checks for variable 19803 // template specializations when we created them. 19804 if (NeedDefinition && TSK != TSK_Undeclared && 19805 !isa<VarTemplateSpecializationDecl>(Var)) 19806 SemaRef.checkSpecializationVisibility(Loc, Var); 19807 19808 // Perform implicit instantiation of static data members, static data member 19809 // templates of class templates, and variable template specializations. Delay 19810 // instantiations of variable templates, except for those that could be used 19811 // in a constant expression. 19812 if (NeedDefinition && isTemplateInstantiation(TSK)) { 19813 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 19814 // instantiation declaration if a variable is usable in a constant 19815 // expression (among other cases). 19816 bool TryInstantiating = 19817 TSK == TSK_ImplicitInstantiation || 19818 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 19819 19820 if (TryInstantiating) { 19821 SourceLocation PointOfInstantiation = 19822 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation(); 19823 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 19824 if (FirstInstantiation) { 19825 PointOfInstantiation = Loc; 19826 if (MSI) 19827 MSI->setPointOfInstantiation(PointOfInstantiation); 19828 // FIXME: Notify listener. 19829 else 19830 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 19831 } 19832 19833 if (UsableInConstantExpr) { 19834 // Do not defer instantiations of variables that could be used in a 19835 // constant expression. 19836 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] { 19837 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 19838 }); 19839 19840 // Re-set the member to trigger a recomputation of the dependence bits 19841 // for the expression. 19842 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 19843 DRE->setDecl(DRE->getDecl()); 19844 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 19845 ME->setMemberDecl(ME->getMemberDecl()); 19846 } else if (FirstInstantiation || 19847 isa<VarTemplateSpecializationDecl>(Var)) { 19848 // FIXME: For a specialization of a variable template, we don't 19849 // distinguish between "declaration and type implicitly instantiated" 19850 // and "implicit instantiation of definition requested", so we have 19851 // no direct way to avoid enqueueing the pending instantiation 19852 // multiple times. 19853 SemaRef.PendingInstantiations 19854 .push_back(std::make_pair(Var, PointOfInstantiation)); 19855 } 19856 } 19857 } 19858 19859 // C++2a [basic.def.odr]p4: 19860 // A variable x whose name appears as a potentially-evaluated expression e 19861 // is odr-used by e unless 19862 // -- x is a reference that is usable in constant expressions 19863 // -- x is a variable of non-reference type that is usable in constant 19864 // expressions and has no mutable subobjects [FIXME], and e is an 19865 // element of the set of potential results of an expression of 19866 // non-volatile-qualified non-class type to which the lvalue-to-rvalue 19867 // conversion is applied 19868 // -- x is a variable of non-reference type, and e is an element of the set 19869 // of potential results of a discarded-value expression to which the 19870 // lvalue-to-rvalue conversion is not applied [FIXME] 19871 // 19872 // We check the first part of the second bullet here, and 19873 // Sema::CheckLValueToRValueConversionOperand deals with the second part. 19874 // FIXME: To get the third bullet right, we need to delay this even for 19875 // variables that are not usable in constant expressions. 19876 19877 // If we already know this isn't an odr-use, there's nothing more to do. 19878 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E)) 19879 if (DRE->isNonOdrUse()) 19880 return; 19881 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E)) 19882 if (ME->isNonOdrUse()) 19883 return; 19884 19885 switch (OdrUse) { 19886 case OdrUseContext::None: 19887 // In some cases, a variable may not have been marked unevaluated, if it 19888 // appears in a defaukt initializer. 19889 assert((!E || isa<FunctionParmPackExpr>(E) || 19890 SemaRef.isUnevaluatedContext()) && 19891 "missing non-odr-use marking for unevaluated decl ref"); 19892 break; 19893 19894 case OdrUseContext::FormallyOdrUsed: 19895 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture 19896 // behavior. 19897 break; 19898 19899 case OdrUseContext::Used: 19900 // If we might later find that this expression isn't actually an odr-use, 19901 // delay the marking. 19902 if (E && Var->isUsableInConstantExpressions(SemaRef.Context)) 19903 SemaRef.MaybeODRUseExprs.insert(E); 19904 else 19905 MarkVarDeclODRUsed(Var, Loc, SemaRef); 19906 break; 19907 19908 case OdrUseContext::Dependent: 19909 // If this is a dependent context, we don't need to mark variables as 19910 // odr-used, but we may still need to track them for lambda capture. 19911 // FIXME: Do we also need to do this inside dependent typeid expressions 19912 // (which are modeled as unevaluated at this point)? 19913 DoMarkPotentialCapture(SemaRef, Loc, Var, E); 19914 break; 19915 } 19916 } 19917 19918 static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc, 19919 BindingDecl *BD, Expr *E) { 19920 BD->setReferenced(); 19921 19922 if (BD->isInvalidDecl()) 19923 return; 19924 19925 OdrUseContext OdrUse = isOdrUseContext(SemaRef); 19926 if (OdrUse == OdrUseContext::Used) { 19927 QualType CaptureType, DeclRefType; 19928 SemaRef.tryCaptureVariable(BD, Loc, Sema::TryCapture_Implicit, 19929 /*EllipsisLoc*/ SourceLocation(), 19930 /*BuildAndDiagnose*/ true, CaptureType, 19931 DeclRefType, 19932 /*FunctionScopeIndexToStopAt*/ nullptr); 19933 } else if (OdrUse == OdrUseContext::Dependent) { 19934 DoMarkPotentialCapture(SemaRef, Loc, BD, E); 19935 } 19936 } 19937 19938 /// Mark a variable referenced, and check whether it is odr-used 19939 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 19940 /// used directly for normal expressions referring to VarDecl. 19941 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 19942 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments); 19943 } 19944 19945 static void 19946 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, 19947 bool MightBeOdrUse, 19948 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 19949 if (SemaRef.isInOpenMPDeclareTargetContext()) 19950 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 19951 19952 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 19953 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments); 19954 return; 19955 } 19956 19957 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) { 19958 DoMarkBindingDeclReferenced(SemaRef, Loc, Decl, E); 19959 return; 19960 } 19961 19962 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 19963 19964 // If this is a call to a method via a cast, also mark the method in the 19965 // derived class used in case codegen can devirtualize the call. 19966 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 19967 if (!ME) 19968 return; 19969 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 19970 if (!MD) 19971 return; 19972 // Only attempt to devirtualize if this is truly a virtual call. 19973 bool IsVirtualCall = MD->isVirtual() && 19974 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 19975 if (!IsVirtualCall) 19976 return; 19977 19978 // If it's possible to devirtualize the call, mark the called function 19979 // referenced. 19980 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 19981 ME->getBase(), SemaRef.getLangOpts().AppleKext); 19982 if (DM) 19983 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 19984 } 19985 19986 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 19987 /// 19988 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be 19989 /// handled with care if the DeclRefExpr is not newly-created. 19990 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 19991 // TODO: update this with DR# once a defect report is filed. 19992 // C++11 defect. The address of a pure member should not be an ODR use, even 19993 // if it's a qualified reference. 19994 bool OdrUse = true; 19995 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 19996 if (Method->isVirtual() && 19997 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 19998 OdrUse = false; 19999 20000 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) 20001 if (!isUnevaluatedContext() && !isConstantEvaluated() && 20002 !isImmediateFunctionContext() && 20003 !isCheckingDefaultArgumentOrInitializer() && FD->isConsteval() && 20004 !RebuildingImmediateInvocation && !FD->isDependentContext()) 20005 ExprEvalContexts.back().ReferenceToConsteval.insert(E); 20006 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse, 20007 RefsMinusAssignments); 20008 } 20009 20010 /// Perform reference-marking and odr-use handling for a MemberExpr. 20011 void Sema::MarkMemberReferenced(MemberExpr *E) { 20012 // C++11 [basic.def.odr]p2: 20013 // A non-overloaded function whose name appears as a potentially-evaluated 20014 // expression or a member of a set of candidate functions, if selected by 20015 // overload resolution when referred to from a potentially-evaluated 20016 // expression, is odr-used, unless it is a pure virtual function and its 20017 // name is not explicitly qualified. 20018 bool MightBeOdrUse = true; 20019 if (E->performsVirtualDispatch(getLangOpts())) { 20020 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 20021 if (Method->isPure()) 20022 MightBeOdrUse = false; 20023 } 20024 SourceLocation Loc = 20025 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 20026 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse, 20027 RefsMinusAssignments); 20028 } 20029 20030 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr. 20031 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) { 20032 for (VarDecl *VD : *E) 20033 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true, 20034 RefsMinusAssignments); 20035 } 20036 20037 /// Perform marking for a reference to an arbitrary declaration. It 20038 /// marks the declaration referenced, and performs odr-use checking for 20039 /// functions and variables. This method should not be used when building a 20040 /// normal expression which refers to a variable. 20041 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 20042 bool MightBeOdrUse) { 20043 if (MightBeOdrUse) { 20044 if (auto *VD = dyn_cast<VarDecl>(D)) { 20045 MarkVariableReferenced(Loc, VD); 20046 return; 20047 } 20048 } 20049 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 20050 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 20051 return; 20052 } 20053 D->setReferenced(); 20054 } 20055 20056 namespace { 20057 // Mark all of the declarations used by a type as referenced. 20058 // FIXME: Not fully implemented yet! We need to have a better understanding 20059 // of when we're entering a context we should not recurse into. 20060 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 20061 // TreeTransforms rebuilding the type in a new context. Rather than 20062 // duplicating the TreeTransform logic, we should consider reusing it here. 20063 // Currently that causes problems when rebuilding LambdaExprs. 20064 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 20065 Sema &S; 20066 SourceLocation Loc; 20067 20068 public: 20069 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 20070 20071 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 20072 20073 bool TraverseTemplateArgument(const TemplateArgument &Arg); 20074 }; 20075 } 20076 20077 bool MarkReferencedDecls::TraverseTemplateArgument( 20078 const TemplateArgument &Arg) { 20079 { 20080 // A non-type template argument is a constant-evaluated context. 20081 EnterExpressionEvaluationContext Evaluated( 20082 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 20083 if (Arg.getKind() == TemplateArgument::Declaration) { 20084 if (Decl *D = Arg.getAsDecl()) 20085 S.MarkAnyDeclReferenced(Loc, D, true); 20086 } else if (Arg.getKind() == TemplateArgument::Expression) { 20087 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 20088 } 20089 } 20090 20091 return Inherited::TraverseTemplateArgument(Arg); 20092 } 20093 20094 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 20095 MarkReferencedDecls Marker(*this, Loc); 20096 Marker.TraverseType(T); 20097 } 20098 20099 namespace { 20100 /// Helper class that marks all of the declarations referenced by 20101 /// potentially-evaluated subexpressions as "referenced". 20102 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> { 20103 public: 20104 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited; 20105 bool SkipLocalVariables; 20106 ArrayRef<const Expr *> StopAt; 20107 20108 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables, 20109 ArrayRef<const Expr *> StopAt) 20110 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {} 20111 20112 void visitUsedDecl(SourceLocation Loc, Decl *D) { 20113 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D)); 20114 } 20115 20116 void Visit(Expr *E) { 20117 if (llvm::is_contained(StopAt, E)) 20118 return; 20119 Inherited::Visit(E); 20120 } 20121 20122 void VisitConstantExpr(ConstantExpr *E) { 20123 // Don't mark declarations within a ConstantExpression, as this expression 20124 // will be evaluated and folded to a value. 20125 } 20126 20127 void VisitDeclRefExpr(DeclRefExpr *E) { 20128 // If we were asked not to visit local variables, don't. 20129 if (SkipLocalVariables) { 20130 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 20131 if (VD->hasLocalStorage()) 20132 return; 20133 } 20134 20135 // FIXME: This can trigger the instantiation of the initializer of a 20136 // variable, which can cause the expression to become value-dependent 20137 // or error-dependent. Do we need to propagate the new dependence bits? 20138 S.MarkDeclRefReferenced(E); 20139 } 20140 20141 void VisitMemberExpr(MemberExpr *E) { 20142 S.MarkMemberReferenced(E); 20143 Visit(E->getBase()); 20144 } 20145 }; 20146 } // namespace 20147 20148 /// Mark any declarations that appear within this expression or any 20149 /// potentially-evaluated subexpressions as "referenced". 20150 /// 20151 /// \param SkipLocalVariables If true, don't mark local variables as 20152 /// 'referenced'. 20153 /// \param StopAt Subexpressions that we shouldn't recurse into. 20154 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 20155 bool SkipLocalVariables, 20156 ArrayRef<const Expr*> StopAt) { 20157 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E); 20158 } 20159 20160 /// Emit a diagnostic when statements are reachable. 20161 /// FIXME: check for reachability even in expressions for which we don't build a 20162 /// CFG (eg, in the initializer of a global or in a constant expression). 20163 /// For example, 20164 /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; } 20165 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, 20166 const PartialDiagnostic &PD) { 20167 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) { 20168 if (!FunctionScopes.empty()) 20169 FunctionScopes.back()->PossiblyUnreachableDiags.push_back( 20170 sema::PossiblyUnreachableDiag(PD, Loc, Stmts)); 20171 return true; 20172 } 20173 20174 // The initializer of a constexpr variable or of the first declaration of a 20175 // static data member is not syntactically a constant evaluated constant, 20176 // but nonetheless is always required to be a constant expression, so we 20177 // can skip diagnosing. 20178 // FIXME: Using the mangling context here is a hack. 20179 if (auto *VD = dyn_cast_or_null<VarDecl>( 20180 ExprEvalContexts.back().ManglingContextDecl)) { 20181 if (VD->isConstexpr() || 20182 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 20183 return false; 20184 // FIXME: For any other kind of variable, we should build a CFG for its 20185 // initializer and check whether the context in question is reachable. 20186 } 20187 20188 Diag(Loc, PD); 20189 return true; 20190 } 20191 20192 /// Emit a diagnostic that describes an effect on the run-time behavior 20193 /// of the program being compiled. 20194 /// 20195 /// This routine emits the given diagnostic when the code currently being 20196 /// type-checked is "potentially evaluated", meaning that there is a 20197 /// possibility that the code will actually be executable. Code in sizeof() 20198 /// expressions, code used only during overload resolution, etc., are not 20199 /// potentially evaluated. This routine will suppress such diagnostics or, 20200 /// in the absolutely nutty case of potentially potentially evaluated 20201 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 20202 /// later. 20203 /// 20204 /// This routine should be used for all diagnostics that describe the run-time 20205 /// behavior of a program, such as passing a non-POD value through an ellipsis. 20206 /// Failure to do so will likely result in spurious diagnostics or failures 20207 /// during overload resolution or within sizeof/alignof/typeof/typeid. 20208 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 20209 const PartialDiagnostic &PD) { 20210 20211 if (ExprEvalContexts.back().isDiscardedStatementContext()) 20212 return false; 20213 20214 switch (ExprEvalContexts.back().Context) { 20215 case ExpressionEvaluationContext::Unevaluated: 20216 case ExpressionEvaluationContext::UnevaluatedList: 20217 case ExpressionEvaluationContext::UnevaluatedAbstract: 20218 case ExpressionEvaluationContext::DiscardedStatement: 20219 // The argument will never be evaluated, so don't complain. 20220 break; 20221 20222 case ExpressionEvaluationContext::ConstantEvaluated: 20223 case ExpressionEvaluationContext::ImmediateFunctionContext: 20224 // Relevant diagnostics should be produced by constant evaluation. 20225 break; 20226 20227 case ExpressionEvaluationContext::PotentiallyEvaluated: 20228 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 20229 return DiagIfReachable(Loc, Stmts, PD); 20230 } 20231 20232 return false; 20233 } 20234 20235 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 20236 const PartialDiagnostic &PD) { 20237 return DiagRuntimeBehavior( 20238 Loc, Statement ? llvm::ArrayRef(Statement) : std::nullopt, PD); 20239 } 20240 20241 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 20242 CallExpr *CE, FunctionDecl *FD) { 20243 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 20244 return false; 20245 20246 // If we're inside a decltype's expression, don't check for a valid return 20247 // type or construct temporaries until we know whether this is the last call. 20248 if (ExprEvalContexts.back().ExprContext == 20249 ExpressionEvaluationContextRecord::EK_Decltype) { 20250 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 20251 return false; 20252 } 20253 20254 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 20255 FunctionDecl *FD; 20256 CallExpr *CE; 20257 20258 public: 20259 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 20260 : FD(FD), CE(CE) { } 20261 20262 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 20263 if (!FD) { 20264 S.Diag(Loc, diag::err_call_incomplete_return) 20265 << T << CE->getSourceRange(); 20266 return; 20267 } 20268 20269 S.Diag(Loc, diag::err_call_function_incomplete_return) 20270 << CE->getSourceRange() << FD << T; 20271 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 20272 << FD->getDeclName(); 20273 } 20274 } Diagnoser(FD, CE); 20275 20276 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 20277 return true; 20278 20279 return false; 20280 } 20281 20282 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 20283 // will prevent this condition from triggering, which is what we want. 20284 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 20285 SourceLocation Loc; 20286 20287 unsigned diagnostic = diag::warn_condition_is_assignment; 20288 bool IsOrAssign = false; 20289 20290 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 20291 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 20292 return; 20293 20294 IsOrAssign = Op->getOpcode() == BO_OrAssign; 20295 20296 // Greylist some idioms by putting them into a warning subcategory. 20297 if (ObjCMessageExpr *ME 20298 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 20299 Selector Sel = ME->getSelector(); 20300 20301 // self = [<foo> init...] 20302 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 20303 diagnostic = diag::warn_condition_is_idiomatic_assignment; 20304 20305 // <foo> = [<bar> nextObject] 20306 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 20307 diagnostic = diag::warn_condition_is_idiomatic_assignment; 20308 } 20309 20310 Loc = Op->getOperatorLoc(); 20311 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 20312 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 20313 return; 20314 20315 IsOrAssign = Op->getOperator() == OO_PipeEqual; 20316 Loc = Op->getOperatorLoc(); 20317 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 20318 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 20319 else { 20320 // Not an assignment. 20321 return; 20322 } 20323 20324 Diag(Loc, diagnostic) << E->getSourceRange(); 20325 20326 SourceLocation Open = E->getBeginLoc(); 20327 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 20328 Diag(Loc, diag::note_condition_assign_silence) 20329 << FixItHint::CreateInsertion(Open, "(") 20330 << FixItHint::CreateInsertion(Close, ")"); 20331 20332 if (IsOrAssign) 20333 Diag(Loc, diag::note_condition_or_assign_to_comparison) 20334 << FixItHint::CreateReplacement(Loc, "!="); 20335 else 20336 Diag(Loc, diag::note_condition_assign_to_comparison) 20337 << FixItHint::CreateReplacement(Loc, "=="); 20338 } 20339 20340 /// Redundant parentheses over an equality comparison can indicate 20341 /// that the user intended an assignment used as condition. 20342 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 20343 // Don't warn if the parens came from a macro. 20344 SourceLocation parenLoc = ParenE->getBeginLoc(); 20345 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 20346 return; 20347 // Don't warn for dependent expressions. 20348 if (ParenE->isTypeDependent()) 20349 return; 20350 20351 Expr *E = ParenE->IgnoreParens(); 20352 20353 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 20354 if (opE->getOpcode() == BO_EQ && 20355 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 20356 == Expr::MLV_Valid) { 20357 SourceLocation Loc = opE->getOperatorLoc(); 20358 20359 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 20360 SourceRange ParenERange = ParenE->getSourceRange(); 20361 Diag(Loc, diag::note_equality_comparison_silence) 20362 << FixItHint::CreateRemoval(ParenERange.getBegin()) 20363 << FixItHint::CreateRemoval(ParenERange.getEnd()); 20364 Diag(Loc, diag::note_equality_comparison_to_assign) 20365 << FixItHint::CreateReplacement(Loc, "="); 20366 } 20367 } 20368 20369 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 20370 bool IsConstexpr) { 20371 DiagnoseAssignmentAsCondition(E); 20372 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 20373 DiagnoseEqualityWithExtraParens(parenE); 20374 20375 ExprResult result = CheckPlaceholderExpr(E); 20376 if (result.isInvalid()) return ExprError(); 20377 E = result.get(); 20378 20379 if (!E->isTypeDependent()) { 20380 if (getLangOpts().CPlusPlus) 20381 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 20382 20383 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 20384 if (ERes.isInvalid()) 20385 return ExprError(); 20386 E = ERes.get(); 20387 20388 QualType T = E->getType(); 20389 if (!T->isScalarType()) { // C99 6.8.4.1p1 20390 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 20391 << T << E->getSourceRange(); 20392 return ExprError(); 20393 } 20394 CheckBoolLikeConversion(E, Loc); 20395 } 20396 20397 return E; 20398 } 20399 20400 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 20401 Expr *SubExpr, ConditionKind CK, 20402 bool MissingOK) { 20403 // MissingOK indicates whether having no condition expression is valid 20404 // (for loop) or invalid (e.g. while loop). 20405 if (!SubExpr) 20406 return MissingOK ? ConditionResult() : ConditionError(); 20407 20408 ExprResult Cond; 20409 switch (CK) { 20410 case ConditionKind::Boolean: 20411 Cond = CheckBooleanCondition(Loc, SubExpr); 20412 break; 20413 20414 case ConditionKind::ConstexprIf: 20415 Cond = CheckBooleanCondition(Loc, SubExpr, true); 20416 break; 20417 20418 case ConditionKind::Switch: 20419 Cond = CheckSwitchCondition(Loc, SubExpr); 20420 break; 20421 } 20422 if (Cond.isInvalid()) { 20423 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(), 20424 {SubExpr}, PreferredConditionType(CK)); 20425 if (!Cond.get()) 20426 return ConditionError(); 20427 } 20428 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 20429 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 20430 if (!FullExpr.get()) 20431 return ConditionError(); 20432 20433 return ConditionResult(*this, nullptr, FullExpr, 20434 CK == ConditionKind::ConstexprIf); 20435 } 20436 20437 namespace { 20438 /// A visitor for rebuilding a call to an __unknown_any expression 20439 /// to have an appropriate type. 20440 struct RebuildUnknownAnyFunction 20441 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 20442 20443 Sema &S; 20444 20445 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 20446 20447 ExprResult VisitStmt(Stmt *S) { 20448 llvm_unreachable("unexpected statement!"); 20449 } 20450 20451 ExprResult VisitExpr(Expr *E) { 20452 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 20453 << E->getSourceRange(); 20454 return ExprError(); 20455 } 20456 20457 /// Rebuild an expression which simply semantically wraps another 20458 /// expression which it shares the type and value kind of. 20459 template <class T> ExprResult rebuildSugarExpr(T *E) { 20460 ExprResult SubResult = Visit(E->getSubExpr()); 20461 if (SubResult.isInvalid()) return ExprError(); 20462 20463 Expr *SubExpr = SubResult.get(); 20464 E->setSubExpr(SubExpr); 20465 E->setType(SubExpr->getType()); 20466 E->setValueKind(SubExpr->getValueKind()); 20467 assert(E->getObjectKind() == OK_Ordinary); 20468 return E; 20469 } 20470 20471 ExprResult VisitParenExpr(ParenExpr *E) { 20472 return rebuildSugarExpr(E); 20473 } 20474 20475 ExprResult VisitUnaryExtension(UnaryOperator *E) { 20476 return rebuildSugarExpr(E); 20477 } 20478 20479 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 20480 ExprResult SubResult = Visit(E->getSubExpr()); 20481 if (SubResult.isInvalid()) return ExprError(); 20482 20483 Expr *SubExpr = SubResult.get(); 20484 E->setSubExpr(SubExpr); 20485 E->setType(S.Context.getPointerType(SubExpr->getType())); 20486 assert(E->isPRValue()); 20487 assert(E->getObjectKind() == OK_Ordinary); 20488 return E; 20489 } 20490 20491 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 20492 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 20493 20494 E->setType(VD->getType()); 20495 20496 assert(E->isPRValue()); 20497 if (S.getLangOpts().CPlusPlus && 20498 !(isa<CXXMethodDecl>(VD) && 20499 cast<CXXMethodDecl>(VD)->isInstance())) 20500 E->setValueKind(VK_LValue); 20501 20502 return E; 20503 } 20504 20505 ExprResult VisitMemberExpr(MemberExpr *E) { 20506 return resolveDecl(E, E->getMemberDecl()); 20507 } 20508 20509 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 20510 return resolveDecl(E, E->getDecl()); 20511 } 20512 }; 20513 } 20514 20515 /// Given a function expression of unknown-any type, try to rebuild it 20516 /// to have a function type. 20517 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 20518 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 20519 if (Result.isInvalid()) return ExprError(); 20520 return S.DefaultFunctionArrayConversion(Result.get()); 20521 } 20522 20523 namespace { 20524 /// A visitor for rebuilding an expression of type __unknown_anytype 20525 /// into one which resolves the type directly on the referring 20526 /// expression. Strict preservation of the original source 20527 /// structure is not a goal. 20528 struct RebuildUnknownAnyExpr 20529 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 20530 20531 Sema &S; 20532 20533 /// The current destination type. 20534 QualType DestType; 20535 20536 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 20537 : S(S), DestType(CastType) {} 20538 20539 ExprResult VisitStmt(Stmt *S) { 20540 llvm_unreachable("unexpected statement!"); 20541 } 20542 20543 ExprResult VisitExpr(Expr *E) { 20544 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 20545 << E->getSourceRange(); 20546 return ExprError(); 20547 } 20548 20549 ExprResult VisitCallExpr(CallExpr *E); 20550 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 20551 20552 /// Rebuild an expression which simply semantically wraps another 20553 /// expression which it shares the type and value kind of. 20554 template <class T> ExprResult rebuildSugarExpr(T *E) { 20555 ExprResult SubResult = Visit(E->getSubExpr()); 20556 if (SubResult.isInvalid()) return ExprError(); 20557 Expr *SubExpr = SubResult.get(); 20558 E->setSubExpr(SubExpr); 20559 E->setType(SubExpr->getType()); 20560 E->setValueKind(SubExpr->getValueKind()); 20561 assert(E->getObjectKind() == OK_Ordinary); 20562 return E; 20563 } 20564 20565 ExprResult VisitParenExpr(ParenExpr *E) { 20566 return rebuildSugarExpr(E); 20567 } 20568 20569 ExprResult VisitUnaryExtension(UnaryOperator *E) { 20570 return rebuildSugarExpr(E); 20571 } 20572 20573 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 20574 const PointerType *Ptr = DestType->getAs<PointerType>(); 20575 if (!Ptr) { 20576 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 20577 << E->getSourceRange(); 20578 return ExprError(); 20579 } 20580 20581 if (isa<CallExpr>(E->getSubExpr())) { 20582 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 20583 << E->getSourceRange(); 20584 return ExprError(); 20585 } 20586 20587 assert(E->isPRValue()); 20588 assert(E->getObjectKind() == OK_Ordinary); 20589 E->setType(DestType); 20590 20591 // Build the sub-expression as if it were an object of the pointee type. 20592 DestType = Ptr->getPointeeType(); 20593 ExprResult SubResult = Visit(E->getSubExpr()); 20594 if (SubResult.isInvalid()) return ExprError(); 20595 E->setSubExpr(SubResult.get()); 20596 return E; 20597 } 20598 20599 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 20600 20601 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 20602 20603 ExprResult VisitMemberExpr(MemberExpr *E) { 20604 return resolveDecl(E, E->getMemberDecl()); 20605 } 20606 20607 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 20608 return resolveDecl(E, E->getDecl()); 20609 } 20610 }; 20611 } 20612 20613 /// Rebuilds a call expression which yielded __unknown_anytype. 20614 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 20615 Expr *CalleeExpr = E->getCallee(); 20616 20617 enum FnKind { 20618 FK_MemberFunction, 20619 FK_FunctionPointer, 20620 FK_BlockPointer 20621 }; 20622 20623 FnKind Kind; 20624 QualType CalleeType = CalleeExpr->getType(); 20625 if (CalleeType == S.Context.BoundMemberTy) { 20626 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 20627 Kind = FK_MemberFunction; 20628 CalleeType = Expr::findBoundMemberType(CalleeExpr); 20629 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 20630 CalleeType = Ptr->getPointeeType(); 20631 Kind = FK_FunctionPointer; 20632 } else { 20633 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 20634 Kind = FK_BlockPointer; 20635 } 20636 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 20637 20638 // Verify that this is a legal result type of a function. 20639 if (DestType->isArrayType() || DestType->isFunctionType()) { 20640 unsigned diagID = diag::err_func_returning_array_function; 20641 if (Kind == FK_BlockPointer) 20642 diagID = diag::err_block_returning_array_function; 20643 20644 S.Diag(E->getExprLoc(), diagID) 20645 << DestType->isFunctionType() << DestType; 20646 return ExprError(); 20647 } 20648 20649 // Otherwise, go ahead and set DestType as the call's result. 20650 E->setType(DestType.getNonLValueExprType(S.Context)); 20651 E->setValueKind(Expr::getValueKindForType(DestType)); 20652 assert(E->getObjectKind() == OK_Ordinary); 20653 20654 // Rebuild the function type, replacing the result type with DestType. 20655 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 20656 if (Proto) { 20657 // __unknown_anytype(...) is a special case used by the debugger when 20658 // it has no idea what a function's signature is. 20659 // 20660 // We want to build this call essentially under the K&R 20661 // unprototyped rules, but making a FunctionNoProtoType in C++ 20662 // would foul up all sorts of assumptions. However, we cannot 20663 // simply pass all arguments as variadic arguments, nor can we 20664 // portably just call the function under a non-variadic type; see 20665 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 20666 // However, it turns out that in practice it is generally safe to 20667 // call a function declared as "A foo(B,C,D);" under the prototype 20668 // "A foo(B,C,D,...);". The only known exception is with the 20669 // Windows ABI, where any variadic function is implicitly cdecl 20670 // regardless of its normal CC. Therefore we change the parameter 20671 // types to match the types of the arguments. 20672 // 20673 // This is a hack, but it is far superior to moving the 20674 // corresponding target-specific code from IR-gen to Sema/AST. 20675 20676 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 20677 SmallVector<QualType, 8> ArgTypes; 20678 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 20679 ArgTypes.reserve(E->getNumArgs()); 20680 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 20681 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i))); 20682 } 20683 ParamTypes = ArgTypes; 20684 } 20685 DestType = S.Context.getFunctionType(DestType, ParamTypes, 20686 Proto->getExtProtoInfo()); 20687 } else { 20688 DestType = S.Context.getFunctionNoProtoType(DestType, 20689 FnType->getExtInfo()); 20690 } 20691 20692 // Rebuild the appropriate pointer-to-function type. 20693 switch (Kind) { 20694 case FK_MemberFunction: 20695 // Nothing to do. 20696 break; 20697 20698 case FK_FunctionPointer: 20699 DestType = S.Context.getPointerType(DestType); 20700 break; 20701 20702 case FK_BlockPointer: 20703 DestType = S.Context.getBlockPointerType(DestType); 20704 break; 20705 } 20706 20707 // Finally, we can recurse. 20708 ExprResult CalleeResult = Visit(CalleeExpr); 20709 if (!CalleeResult.isUsable()) return ExprError(); 20710 E->setCallee(CalleeResult.get()); 20711 20712 // Bind a temporary if necessary. 20713 return S.MaybeBindToTemporary(E); 20714 } 20715 20716 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 20717 // Verify that this is a legal result type of a call. 20718 if (DestType->isArrayType() || DestType->isFunctionType()) { 20719 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 20720 << DestType->isFunctionType() << DestType; 20721 return ExprError(); 20722 } 20723 20724 // Rewrite the method result type if available. 20725 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 20726 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 20727 Method->setReturnType(DestType); 20728 } 20729 20730 // Change the type of the message. 20731 E->setType(DestType.getNonReferenceType()); 20732 E->setValueKind(Expr::getValueKindForType(DestType)); 20733 20734 return S.MaybeBindToTemporary(E); 20735 } 20736 20737 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 20738 // The only case we should ever see here is a function-to-pointer decay. 20739 if (E->getCastKind() == CK_FunctionToPointerDecay) { 20740 assert(E->isPRValue()); 20741 assert(E->getObjectKind() == OK_Ordinary); 20742 20743 E->setType(DestType); 20744 20745 // Rebuild the sub-expression as the pointee (function) type. 20746 DestType = DestType->castAs<PointerType>()->getPointeeType(); 20747 20748 ExprResult Result = Visit(E->getSubExpr()); 20749 if (!Result.isUsable()) return ExprError(); 20750 20751 E->setSubExpr(Result.get()); 20752 return E; 20753 } else if (E->getCastKind() == CK_LValueToRValue) { 20754 assert(E->isPRValue()); 20755 assert(E->getObjectKind() == OK_Ordinary); 20756 20757 assert(isa<BlockPointerType>(E->getType())); 20758 20759 E->setType(DestType); 20760 20761 // The sub-expression has to be a lvalue reference, so rebuild it as such. 20762 DestType = S.Context.getLValueReferenceType(DestType); 20763 20764 ExprResult Result = Visit(E->getSubExpr()); 20765 if (!Result.isUsable()) return ExprError(); 20766 20767 E->setSubExpr(Result.get()); 20768 return E; 20769 } else { 20770 llvm_unreachable("Unhandled cast type!"); 20771 } 20772 } 20773 20774 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 20775 ExprValueKind ValueKind = VK_LValue; 20776 QualType Type = DestType; 20777 20778 // We know how to make this work for certain kinds of decls: 20779 20780 // - functions 20781 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 20782 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 20783 DestType = Ptr->getPointeeType(); 20784 ExprResult Result = resolveDecl(E, VD); 20785 if (Result.isInvalid()) return ExprError(); 20786 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay, 20787 VK_PRValue); 20788 } 20789 20790 if (!Type->isFunctionType()) { 20791 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 20792 << VD << E->getSourceRange(); 20793 return ExprError(); 20794 } 20795 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 20796 // We must match the FunctionDecl's type to the hack introduced in 20797 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 20798 // type. See the lengthy commentary in that routine. 20799 QualType FDT = FD->getType(); 20800 const FunctionType *FnType = FDT->castAs<FunctionType>(); 20801 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 20802 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 20803 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 20804 SourceLocation Loc = FD->getLocation(); 20805 FunctionDecl *NewFD = FunctionDecl::Create( 20806 S.Context, FD->getDeclContext(), Loc, Loc, 20807 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(), 20808 SC_None, S.getCurFPFeatures().isFPConstrained(), 20809 false /*isInlineSpecified*/, FD->hasPrototype(), 20810 /*ConstexprKind*/ ConstexprSpecKind::Unspecified); 20811 20812 if (FD->getQualifier()) 20813 NewFD->setQualifierInfo(FD->getQualifierLoc()); 20814 20815 SmallVector<ParmVarDecl*, 16> Params; 20816 for (const auto &AI : FT->param_types()) { 20817 ParmVarDecl *Param = 20818 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 20819 Param->setScopeInfo(0, Params.size()); 20820 Params.push_back(Param); 20821 } 20822 NewFD->setParams(Params); 20823 DRE->setDecl(NewFD); 20824 VD = DRE->getDecl(); 20825 } 20826 } 20827 20828 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 20829 if (MD->isInstance()) { 20830 ValueKind = VK_PRValue; 20831 Type = S.Context.BoundMemberTy; 20832 } 20833 20834 // Function references aren't l-values in C. 20835 if (!S.getLangOpts().CPlusPlus) 20836 ValueKind = VK_PRValue; 20837 20838 // - variables 20839 } else if (isa<VarDecl>(VD)) { 20840 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 20841 Type = RefTy->getPointeeType(); 20842 } else if (Type->isFunctionType()) { 20843 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 20844 << VD << E->getSourceRange(); 20845 return ExprError(); 20846 } 20847 20848 // - nothing else 20849 } else { 20850 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 20851 << VD << E->getSourceRange(); 20852 return ExprError(); 20853 } 20854 20855 // Modifying the declaration like this is friendly to IR-gen but 20856 // also really dangerous. 20857 VD->setType(DestType); 20858 E->setType(Type); 20859 E->setValueKind(ValueKind); 20860 return E; 20861 } 20862 20863 /// Check a cast of an unknown-any type. We intentionally only 20864 /// trigger this for C-style casts. 20865 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 20866 Expr *CastExpr, CastKind &CastKind, 20867 ExprValueKind &VK, CXXCastPath &Path) { 20868 // The type we're casting to must be either void or complete. 20869 if (!CastType->isVoidType() && 20870 RequireCompleteType(TypeRange.getBegin(), CastType, 20871 diag::err_typecheck_cast_to_incomplete)) 20872 return ExprError(); 20873 20874 // Rewrite the casted expression from scratch. 20875 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 20876 if (!result.isUsable()) return ExprError(); 20877 20878 CastExpr = result.get(); 20879 VK = CastExpr->getValueKind(); 20880 CastKind = CK_NoOp; 20881 20882 return CastExpr; 20883 } 20884 20885 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 20886 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 20887 } 20888 20889 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 20890 Expr *arg, QualType ¶mType) { 20891 // If the syntactic form of the argument is not an explicit cast of 20892 // any sort, just do default argument promotion. 20893 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 20894 if (!castArg) { 20895 ExprResult result = DefaultArgumentPromotion(arg); 20896 if (result.isInvalid()) return ExprError(); 20897 paramType = result.get()->getType(); 20898 return result; 20899 } 20900 20901 // Otherwise, use the type that was written in the explicit cast. 20902 assert(!arg->hasPlaceholderType()); 20903 paramType = castArg->getTypeAsWritten(); 20904 20905 // Copy-initialize a parameter of that type. 20906 InitializedEntity entity = 20907 InitializedEntity::InitializeParameter(Context, paramType, 20908 /*consumed*/ false); 20909 return PerformCopyInitialization(entity, callLoc, arg); 20910 } 20911 20912 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 20913 Expr *orig = E; 20914 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 20915 while (true) { 20916 E = E->IgnoreParenImpCasts(); 20917 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 20918 E = call->getCallee(); 20919 diagID = diag::err_uncasted_call_of_unknown_any; 20920 } else { 20921 break; 20922 } 20923 } 20924 20925 SourceLocation loc; 20926 NamedDecl *d; 20927 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 20928 loc = ref->getLocation(); 20929 d = ref->getDecl(); 20930 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 20931 loc = mem->getMemberLoc(); 20932 d = mem->getMemberDecl(); 20933 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 20934 diagID = diag::err_uncasted_call_of_unknown_any; 20935 loc = msg->getSelectorStartLoc(); 20936 d = msg->getMethodDecl(); 20937 if (!d) { 20938 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 20939 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 20940 << orig->getSourceRange(); 20941 return ExprError(); 20942 } 20943 } else { 20944 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 20945 << E->getSourceRange(); 20946 return ExprError(); 20947 } 20948 20949 S.Diag(loc, diagID) << d << orig->getSourceRange(); 20950 20951 // Never recoverable. 20952 return ExprError(); 20953 } 20954 20955 /// Check for operands with placeholder types and complain if found. 20956 /// Returns ExprError() if there was an error and no recovery was possible. 20957 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 20958 if (!Context.isDependenceAllowed()) { 20959 // C cannot handle TypoExpr nodes on either side of a binop because it 20960 // doesn't handle dependent types properly, so make sure any TypoExprs have 20961 // been dealt with before checking the operands. 20962 ExprResult Result = CorrectDelayedTyposInExpr(E); 20963 if (!Result.isUsable()) return ExprError(); 20964 E = Result.get(); 20965 } 20966 20967 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 20968 if (!placeholderType) return E; 20969 20970 switch (placeholderType->getKind()) { 20971 20972 // Overloaded expressions. 20973 case BuiltinType::Overload: { 20974 // Try to resolve a single function template specialization. 20975 // This is obligatory. 20976 ExprResult Result = E; 20977 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 20978 return Result; 20979 20980 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 20981 // leaves Result unchanged on failure. 20982 Result = E; 20983 if (resolveAndFixAddressOfSingleOverloadCandidate(Result)) 20984 return Result; 20985 20986 // If that failed, try to recover with a call. 20987 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 20988 /*complain*/ true); 20989 return Result; 20990 } 20991 20992 // Bound member functions. 20993 case BuiltinType::BoundMember: { 20994 ExprResult result = E; 20995 const Expr *BME = E->IgnoreParens(); 20996 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 20997 // Try to give a nicer diagnostic if it is a bound member that we recognize. 20998 if (isa<CXXPseudoDestructorExpr>(BME)) { 20999 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 21000 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 21001 if (ME->getMemberNameInfo().getName().getNameKind() == 21002 DeclarationName::CXXDestructorName) 21003 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 21004 } 21005 tryToRecoverWithCall(result, PD, 21006 /*complain*/ true); 21007 return result; 21008 } 21009 21010 // ARC unbridged casts. 21011 case BuiltinType::ARCUnbridgedCast: { 21012 Expr *realCast = stripARCUnbridgedCast(E); 21013 diagnoseARCUnbridgedCast(realCast); 21014 return realCast; 21015 } 21016 21017 // Expressions of unknown type. 21018 case BuiltinType::UnknownAny: 21019 return diagnoseUnknownAnyExpr(*this, E); 21020 21021 // Pseudo-objects. 21022 case BuiltinType::PseudoObject: 21023 return checkPseudoObjectRValue(E); 21024 21025 case BuiltinType::BuiltinFn: { 21026 // Accept __noop without parens by implicitly converting it to a call expr. 21027 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 21028 if (DRE) { 21029 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 21030 unsigned BuiltinID = FD->getBuiltinID(); 21031 if (BuiltinID == Builtin::BI__noop) { 21032 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 21033 CK_BuiltinFnToFnPtr) 21034 .get(); 21035 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy, 21036 VK_PRValue, SourceLocation(), 21037 FPOptionsOverride()); 21038 } 21039 21040 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) { 21041 // Any use of these other than a direct call is ill-formed as of C++20, 21042 // because they are not addressable functions. In earlier language 21043 // modes, warn and force an instantiation of the real body. 21044 Diag(E->getBeginLoc(), 21045 getLangOpts().CPlusPlus20 21046 ? diag::err_use_of_unaddressable_function 21047 : diag::warn_cxx20_compat_use_of_unaddressable_function); 21048 if (FD->isImplicitlyInstantiable()) { 21049 // Require a definition here because a normal attempt at 21050 // instantiation for a builtin will be ignored, and we won't try 21051 // again later. We assume that the definition of the template 21052 // precedes this use. 21053 InstantiateFunctionDefinition(E->getBeginLoc(), FD, 21054 /*Recursive=*/false, 21055 /*DefinitionRequired=*/true, 21056 /*AtEndOfTU=*/false); 21057 } 21058 // Produce a properly-typed reference to the function. 21059 CXXScopeSpec SS; 21060 SS.Adopt(DRE->getQualifierLoc()); 21061 TemplateArgumentListInfo TemplateArgs; 21062 DRE->copyTemplateArgumentsInto(TemplateArgs); 21063 return BuildDeclRefExpr( 21064 FD, FD->getType(), VK_LValue, DRE->getNameInfo(), 21065 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(), 21066 DRE->getTemplateKeywordLoc(), 21067 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr); 21068 } 21069 } 21070 21071 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 21072 return ExprError(); 21073 } 21074 21075 case BuiltinType::IncompleteMatrixIdx: 21076 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens()) 21077 ->getRowIdx() 21078 ->getBeginLoc(), 21079 diag::err_matrix_incomplete_index); 21080 return ExprError(); 21081 21082 // Expressions of unknown type. 21083 case BuiltinType::OMPArraySection: 21084 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 21085 return ExprError(); 21086 21087 // Expressions of unknown type. 21088 case BuiltinType::OMPArrayShaping: 21089 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use)); 21090 21091 case BuiltinType::OMPIterator: 21092 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use)); 21093 21094 // Everything else should be impossible. 21095 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 21096 case BuiltinType::Id: 21097 #include "clang/Basic/OpenCLImageTypes.def" 21098 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 21099 case BuiltinType::Id: 21100 #include "clang/Basic/OpenCLExtensionTypes.def" 21101 #define SVE_TYPE(Name, Id, SingletonId) \ 21102 case BuiltinType::Id: 21103 #include "clang/Basic/AArch64SVEACLETypes.def" 21104 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 21105 case BuiltinType::Id: 21106 #include "clang/Basic/PPCTypes.def" 21107 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: 21108 #include "clang/Basic/RISCVVTypes.def" 21109 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 21110 #define PLACEHOLDER_TYPE(Id, SingletonId) 21111 #include "clang/AST/BuiltinTypes.def" 21112 break; 21113 } 21114 21115 llvm_unreachable("invalid placeholder type!"); 21116 } 21117 21118 bool Sema::CheckCaseExpression(Expr *E) { 21119 if (E->isTypeDependent()) 21120 return true; 21121 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 21122 return E->getType()->isIntegralOrEnumerationType(); 21123 return false; 21124 } 21125 21126 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 21127 ExprResult 21128 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 21129 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 21130 "Unknown Objective-C Boolean value!"); 21131 QualType BoolT = Context.ObjCBuiltinBoolTy; 21132 if (!Context.getBOOLDecl()) { 21133 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 21134 Sema::LookupOrdinaryName); 21135 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 21136 NamedDecl *ND = Result.getFoundDecl(); 21137 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 21138 Context.setBOOLDecl(TD); 21139 } 21140 } 21141 if (Context.getBOOLDecl()) 21142 BoolT = Context.getBOOLType(); 21143 return new (Context) 21144 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 21145 } 21146 21147 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 21148 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 21149 SourceLocation RParen) { 21150 auto FindSpecVersion = 21151 [&](StringRef Platform) -> std::optional<VersionTuple> { 21152 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 21153 return Spec.getPlatform() == Platform; 21154 }); 21155 // Transcribe the "ios" availability check to "maccatalyst" when compiling 21156 // for "maccatalyst" if "maccatalyst" is not specified. 21157 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") { 21158 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) { 21159 return Spec.getPlatform() == "ios"; 21160 }); 21161 } 21162 if (Spec == AvailSpecs.end()) 21163 return std::nullopt; 21164 return Spec->getVersion(); 21165 }; 21166 21167 VersionTuple Version; 21168 if (auto MaybeVersion = 21169 FindSpecVersion(Context.getTargetInfo().getPlatformName())) 21170 Version = *MaybeVersion; 21171 21172 // The use of `@available` in the enclosing context should be analyzed to 21173 // warn when it's used inappropriately (i.e. not if(@available)). 21174 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext()) 21175 Context->HasPotentialAvailabilityViolations = true; 21176 21177 return new (Context) 21178 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 21179 } 21180 21181 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 21182 ArrayRef<Expr *> SubExprs, QualType T) { 21183 if (!Context.getLangOpts().RecoveryAST) 21184 return ExprError(); 21185 21186 if (isSFINAEContext()) 21187 return ExprError(); 21188 21189 if (T.isNull() || T->isUndeducedType() || 21190 !Context.getLangOpts().RecoveryASTType) 21191 // We don't know the concrete type, fallback to dependent type. 21192 T = Context.DependentTy; 21193 21194 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs); 21195 } 21196